How to easily open the Launcher with a secondary monitor to the left

Question: I have two monitors (24" as main and a 19" to the left).
Each time I want to swap to a different application or launch a new one, the launcher seems a little problematic to come up. Even though moving my mouse across the top Ubuntu logo gets it up, it still seems quite spasmodic.
Anybody else found a problem and is there a solution?
Answer: Create a Mouse Void
This is quite a long answer that I felt is better kept separate from my other one.
So that you understand where this solution came from, my monitor layout is as follows:

The two black area 1280x88 are off the screen but my mouse can still enter this due to an X bug. The workaround is a small program that prevents the mouse entering this void called XCreateMouseVoid.
Home Button Mouse Stopper
You can also use XCreateMouseVoid to create a small box that the mouse will stop against when pushed into the top left corner of the primary screen. This is what I have shown in green area of this image:

Installing

Download XCreateMouseVoid and extract the files to your home folder
Open the folder in Terminal and run this command:
cd ~/XCreateMouseVoid && make

Test the program with values:
~/XCreateMouseVoid/XCreateMouseVoid 0 0 1280 88

Add to Startup Applications so its always runs upon bootup.

Calculate Values
The values required for XCreateMouseVoid are: x, y , w, h

x & y refer to the start co-ordinates of the rectangle. These co-ordinates are based upon the whole desktop area and not individual monitors.
w & h refer to the width and height of the rectangle

For my setup to stop the mouse entering the top and bottom black 1280 x 88 areas along with stopping it travel past the Home Button, I run two instances of the program with these values:
XCreateMouseVoid 0 0 1280 88
XCreateMouseVoid 0 1112 1280 88

Small Rectangle
If you have a different setup you can create the small rectangle as I mentioned earlier. The rectangle measures 60 x 25, which is the minimum width needed to properly stop the mouse.
The only value you need to change is x which is calculated by subtracting 60 from your secondary monitor's width. e.g. 1280 x 1024 monitor I subtract 60 from 1280 to get the value 1220 for XCreateMouseVoid:
XCreateMouseVoid 1220 0 60 25

Trapped Mouse Cursor
Occasionally the mouse cursor can jump into the created mouse void and become trapped. The solution is to press either the Super or Menu key so that a menu opens and frees the mouse cursor.
Comment: It works, but the mouse cursor may get trapped by XCreateMouseVoid. The cursor won't get out from the void without killing the program. This seems to happen more likely if the cursor moves fast to the invisible area.
Comment: I only really get that happening on rare occasions when selecting desktop icons however I found that opening Dash with the super key seems to free the cursor. Let me know if that works for you and I can add that to my answer.
Comment: Super does not do anything on my lucid setup, however, pressing the menu key brings forth the context menu and frees the cursor. (I have a broken mouse at work, the cursor likes to jump large distances and thus makes the disappearance happen quite often. Kids do the same, actually, even with non-broken mice ;)
Answer: I have the same setup and it is quite annoying. The reason it doesn't work well with secondary monitor to the left is there is no barrier to stop the cursor from moving further to the left off from the home button which normally occurs in a single monitor scenario.
Mouse Precision
You need to be very precise and put the mouse cursor only in the top left corner pixels of the main screen.

Shortcuts can be used as an alternative:

Hold down the Super key and use either mouse or keypad
Press Alt+F1 and use arrow keys

Disable the Launcher from hiding:

Install Compiz Config Settings Manager
 from the Ubuntu Software Center
Open Compiz Config Settings Manager from Dash
Find Unity plugin and change Hide Launcher to Never

Open with left edge of screen:
You can actually open the Launcher by moving the mouse to the far left of the secondary monitor if you have enabled Pushes left edge of screen in Launchers and Menus.  It's not intuitive nor ergonomic but it works.


Read and manipulate values in a TStringGrid

Question: I have a StringGrid that looks like this:
<code>+----------+----------+----------+----------+----------+
| FixedRow | FixedRow | FixedRow | FixedRow | FixedRow |
+----------+----------+----------+----------+----------+
| Data     | Data     | Data     | 100      | Data     |
+----------+----------+----------+----------+----------+
| Data     | Data     | Data     | 158      | Data     |
+----------+----------+----------+----------+----------+
| Data     | Data     | Data     | 1002     | Data     |
+----------+----------+----------+----------+----------+
</code>
The StringGrid can have any number of rows and I want to, within a Timer's tick event, find the value of each cell in column 4 and decrease its value by 1.
How can I read and manipulate a TStringGrid in this way?
Comment: In VCL, I would typically use a `TListView` in virtual mode instead of using a `TStringGrid`. One, it just looks nicer since `TListView` is a native Windows control, and two, all of the data is kept wherever you want (memory, file, database, etc) in whatever format you want, so it makes editing a little easier. The `TListView` acts as just a display for the data, not a container for the data.
Comment: VCL or FMX? It matters here.
Answer: This is very straightforward.
Simply iterate over the data (non-header) rows, and for each row, obtain the value in the fourth column, convert it to an integer, decrease it, convert it back to a string, and set the cell's value to this string.
Since you have no fixed column, all columns are data columns. They are indexed 0, 1, 2, 3, 4, the fourth thus having index 3.
Since you have a fixed (header) row, the rows are indexed 0, 1, 2, ..., N − 1, with the data rows being 1, 2, ..., N − 1.
<code>procedure TForm1.Timer1Timer(Sender: TObject);
var
  y: Integer;
  Val: Integer;
begin
  for y := 1 to StringGrid1.RowCount - 1 do
  begin
    Val := StrToInt(StringGrid1.Cells[3, y]);
    Dec(Val);
    StringGrid1.Cells[3, y] := Val.ToString;
  end;
end;
</code>
Comment: Or maybe in general: `for y := StringGrid1.FixedRows to StringGrid1.RowCount - 1 do`.


how to get docker to include wwwroot static content aspnet core

Question: I am trying to get include a swagger.json file into my docker image.
I am using aspnet core 2.2
When I run my app locally it picks up the swagger.json file sitting in wwwroot.
when I create my docker image and run it, swagger starts but won't find the .json so it just errors out. I am very new to docker.
I should note it also didn't find a test.gif file I dropped into wwwroot either.
Am I missing something in the docker file?
I definitely want to include the .json file in my image.
dockerfile:
<code>        FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base
    WORKDIR /app
    EXPOSE 80
    EXPOSE 443

    FROM microsoft/dotnet:2.2-sdk AS build
    WORKDIR /src
    COPY ["myApp.Api/myApp.Api.csproj", "myApp.Api/"]
    COPY ["myApp.logic/myApp.logic.csproj", "myApp.logic/"]
    COPY ["myApp.Models/myApp.Models.csproj", "myApp.Models/"]
    RUN dotnet restore "myApp.Api/myApp.Api.csproj"
    COPY . .
    WORKDIR "/src/myApp.Api"
    RUN dotnet build "myApp.Api.csproj" -c Release -o /app

    FROM build AS publish
    RUN dotnet publish "myApp.Api.csproj" -c Release -o /app

    FROM base AS final
    WORKDIR /app
    COPY --from=publish /app .
    ENTRYPOINT ["dotnet", "myApp.Api.dll"]
</code>
csproj file:

<code>  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
    <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
    <UserSecretsId></UserSecretsId>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile></DocumentationFile>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.0.2105168" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="4.0.1" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\myApp.logic\myApp.logic.csproj" />
  </ItemGroup>

  <ItemGroup>
    <Content Update="wwwroot\swagger.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

</Project>
</code>
docker command
<code>docker run -it -p 5001:80 myapp:latest
</code>
Comment: Did you find a solution? I have the same problem on ASP.NET Core 2.1 but only with the Docker images. Windows 10 includes the `wwwroot` folder as expected without any modifications. But on docker it doesn't work. Tried different include directives e.g. ``, `` and others without success. The `wwwroot` folder exists in the Docker image, but after publishing it's missing in the publish target directory.
Answer: In my case, the solution was renaming subfolders and files to lowercase because paths are case sensitive with the Docker image.


Why modal data is not posted to controller

Question: I am trying to post data from modal in bootstrap to controller in codeigniter. But the data is not posted.
public function save()
{
     if (!empty($_POST['UserName'])){

         $data = $this->input->post('UserName');
         echo $data;
     }
     else
     {
         echo "Not posted";
     }
}

In the view,

    <?php echo form_open('Supplier/save'); ?>

                User Name
                <input id="UserName" name="UserName" type="text" class="validate" required>

    <?php echo form_close(); ?>

Comment: How are you submitting the form?
Answer: Maybe you need?
echo form_submit('mysubmit', 'Submit Post!');

Also consider using isset() instead of !empty(). For example when you check number value empty() for number 0 will return true.
Answer: First, you need to use a submit as said @Mateusz Petkiewicz.
then why you don`t use the CI input post and form_validator like
public function save(){

    $this->form_validation->set_rules('UserName', 'Username', 'trim|required|xss_clean');

    if( $this->form_validation->run()){
        echo $data;
    }
    else{
        echo validation_errors();
        echo "
Not posted";
    }
}


How to improve/maximize current Database/Table Structure efficiency?

Question: The current structure of my Database tables are as follows; I have two tables, Users, and Skills, with the following columns:
Users
user_id   f_name   l_name    biography    password   email          role
_____________________________________________________________________
1         John     Program   Short Bio    Password   johnprogram@   Programmer
2         Jeff     Analyst   Another Bio  Password   jeffanalyst@   Finance Analyst
3         Mister   Manager   My Bio       Password   mrmanager@     Project Manager

Skills
user_id   skill_1   skill_1_details      skill_2             skill_2_details     skill_3     skill_3_details
_________________________________________________________________________________
1         PHP       John writes PHP      Python              John writes Python  Perl        John writes Perl
2         Excel     I use Excel daily    SAP                 SAP Reporting       Reporting   Reports created with Excel
3         Billing   Oversee Bill. Team   Workflow Assignment I assign team acc.

Whenever I am querying the data in the tables to display on a Profile Page, the info is displayed as follows:
Name: John Program
Role: Programmer
Short Bio

Skill: PHP
Details: John writes PHP

Skill: Python
Details: John writes Python

Skill: Perl
Details: John writes Perl

Questions:
1) What re-adjustments/changes should be made to the table structures to increase efficiency/flexibility given the display requirements?
2) If I were to add a "Previous Projects Using Skill" column, for efficiency, would I add it to the second table as follows?:
user_id   skill_1   skill_1_details      projects_using_skill_1
_________________________________________________________________________________
1         PHP       John writes PHP      8                         Python              John writes Python  Perl        John writes Perl
2         Excel     I use Excel daily    12                        SAP                 SAP Reporting       Reporting   Reports created with Excel
3         Billing   Oversee Bill. Team   3                         Workflow Assignment I assign team acc.

Comment: What happen if Mary has four skills?
Comment: Exactly. How should the structure be adjusted if the option to add more skills is permitted?
Answer: For the skill - user relation, you can have two different solutions: if each user has its own skills and details, than you can use a skill table to represent them, with only one skill per user per row (so if a user has four skills, the table will have four rows):
Skills (user_id, skill, detail)

with primary key the couple user_id, skill.
In this way, to find all the skills for a certain user, you can join the two table and find all the relevant information.
If instead several users can have the same skills, you should use three tables:
Users (user_id, f_name, ...)
Skills (skill_id, skill_name, skill_detail)
UsersSkills (user_id, skill_id)

or, if you want that each user has its own details about a skill, but you want to share the skills, you could do something like the following:
Users (user_id, f_name, ...)
Skills (skill_id, skill_name)
UsersSkills (user_id, skill_id,  skill_detail)

For your second question, if a user has done several projects using a certain skill, assuming that you have selected the first solution above, you can define a new table:
ProjectUsers (user_id, skill, project_id)

with primary key all the three attributes, and with user_id, skill foreign key for the Skills table.


terminology relating to o(1)

Question: If someone says, for example, "I have an algorithm that runs in time $n^2+\varepsilon$ for any constant $\varepsilon>0$", the interpretation for this statement seems to be that for any constant  $\varepsilon>0$, there is an integer $N$ such that for all $n>N$, the algorithm runs in time at most $n^2+\varepsilon$.
This means that there is a sequence $\varepsilon_1=1/2$, $\varepsilon_2=1/4$, $\varepsilon_3=1/8$, etc along with associated integers $N_1 \leq N_2 \leq N_3 \leq...$
But does this not mean that the algorithm is $n^2 +o(1)$?
Comment: The example seems odd. I have never seen anything like it … After all, there is usually a constant in front, so the running time is big-O of something. But $O(n^2+\varepsilon)$ is the same as $O(n^2)$, which makes me wonder if they don't *really* mean to say $O(n^{2+\varepsilon})$. That, at least, is a sort of estimate one comes across frequently. But if what you wrote is really what they wrote, then yes, your analysis seems correct.
Comment: @Harald Hanche-Olsen supposing it was $O(n^{2+\varepsilon})$, would the argument fail because the hidden constant factor could increase?
Comment: Usually $O(n^{2+\epsilon})$ means $O(n^a)$ for every $a\gt2$. And no, this does not imply $O(n^2)$.
Answer: Suppose $f(n) = O(n^{2+\epsilon})$ as $n \to \infty$ for all $\epsilon > 0$.  Then $g(n) = f(n)/n^2 = O(n^\epsilon)$ for all $\epsilon > 0$; that is, for all $\epsilon > 0$ we can find $M_\epsilon, C_\epsilon > 0$ such that
$$
0 \leq g(n) \leq C_\epsilon n^\epsilon \qquad \text{for } n \geq M_\epsilon
$$
if we assume that $g(n) \geq 0$ for $n$ large enough.  If we further assume that $g(n) \geq 1$ for $n$ large enough then we can find $N_\epsilon > 0$ such that
$$
0 \leq \log_n g(n) \leq \log_n C_\epsilon + \epsilon \leq 2\epsilon \qquad \text{for } n \geq N_\epsilon.
$$
Since $\epsilon$ was arbitrary we must have $h(n) = \log_n g(n) = o(1)$ as $n \to \infty$.
Now $g(n) = n^{h(n)}$, so we can write $g(n) = n^{o(1)}$ and hence $f(n) = n^{2+o(1)}$.
It should be noted that the assumption that eventually $f(n)/n^2 \geq 1$ is sufficient but not necessary to obtain this result.

We can obtain a slightly weaker statement using $O$ if we only assume that $f(n) \geq 0$ eventually, which I assume is the case you will be encountering when analyzing algorithms.
Let $N_1$ be the set of all $n$ such that $g(n) \geq 1$, and let $N_2$ be the set for which $0 \leq g(n) < 1$.  Then
$$
g(n) \leq n^{\hat{h}(n)},
$$
where
$$
\hat{h}(n) = \begin{cases}
\log_n g(n) & \text{if } n \in N_1, \\
0 & \text{if } n \in N_2.
\end{cases}
$$
By the argument above we have $\hat{h}(n) = o(1)$ as $n \to \infty$, so we can write $g(n) \leq n^{o(1)}$.  Thus
$$
f(n) \leq n^{2+o(1)} \qquad \text{as } n \to \infty,
$$
or if you prefer, $f(n) = O(n^{2+o(1)})$ as $n \to \infty$.
Comment: OK, so if the complexity is bounded by $C_\epsilon n^\epsilon=n^{\log_n C_\epsilon+\epsilon}$ then we can let $\epsilon=\epsilon(n) \rightarrow 0$ arbitrarily slowly meaning $c_{\epsilon}$ rises arbitrarily slowly, slow enough such that $\log_n C_\epsilon=o(1)$. Hence we do indeed have $n^{o(1)}$.
Comment: Epsilon doesn't depend on $n$, though.  I don't really follow what you mean.
Comment: You say "Since $ϵ$ was arbitrary we must have $h(n)=log_n g(n)=o(1)$ as n→∞." so you are implicitly saying we choose a sequence of epsilons which go to zero with $n$, because you are bounding g(n) by a function of $\epsilon$.
Comment: Hmm, I am not saying that, explicitly or implicitly.  I am using the definition of "limit", which makes no reference to a sequence of epsilons.  The $\epsilon$ in $C_\epsilon$ is fixed at the beginning, and if you're now looking at these $\epsilon(n)$'s (which I suppose are just $\epsilon(n) = \log_n g(n)$?) then they are fundamentally distinct from from it.
Comment: Yes I know you are using the definition of a limit.  The definition of a limit implies that we can define a sequence of epsilons get progressively closer to zero, and which make a step function that bounds the function log g (or what ever), which means it gets closer to zero as well. // I am saying $log_n g(n)≤log_n C_\epsilon+\epsilon$ where $\epsilon=\epsilon(n)$
Comment: I really don't get what point you're making.
Comment: It's not important. Thanks for your answer.
Comment: Haha, okay :).  Glad I could help.

terminology relating to o(1)


AWS STS credentials access permission cross account

Question: I have 3 AWS accounts. Account A has a lambda (Lambda_Account_A), Account B has a role (Role_Account_B) and Account C has a s3 bucket (S3_Account_C). The resource in account C  is configured with a bucket policy that says - Role_Account_B can access this bucket.
If the lambda in Account A assumes Account B role (Role_Account_B) and generate STS credentials, will those credentials have access to Account C resource s3 bucket?
Account B and C has been configured to trust each other.
Account A lambda code:
try {
    AssumeRoleRequest roleRequest = new AssumeRoleRequest()
            .withRoleArn(assumeRole) //arn of the role in account B
            .withPolicy(policy) // policy contains "arn:aws:s3:::my_bucket"
            .withDurationSeconds(3600)
            .withRoleSessionName(SESSION_NAME);

    // Assume the IAM role
    AssumeRoleResult assumeResult = stsClient.assumeRole(roleRequest);

    final BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(
            assumeResult.getCredentials().getAccessKeyId(),
            assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());

    return temporaryCredentials;
} catch (AWSSecurityTokenServiceException e) {}

Bucket Policy in Account C:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::account_No:role/Account_B_role"
            },
            "Action": [
                "s3:Get*",
            ],
            "Resource": "arn:aws:s3:::my_bucket/*"
        }
    ]
}

Role_B Permission policy is
{
    "Version": "2012-10-17",
    "Statement": [

        {
            "Action": [
                "s3:*"
            ],
            "Resource": "*",
            "Effect": "Allow"
        }
    ]
}

It's trust relationship has both the Account A and Account C
Answer: When you assume a role in another account its treated as if you're in that account.
As long as account B has the IAM permissions on this IAM role to access bucket in account C it will be able to perform those actions.
To prevent unauthorised access to certain permissions you can lockdown by using external ids which are optionally specified when you assume a role. This allows you to lockdown specific permissions in the roles IAM policy by using conditions referencing the sts:ExternalId.
More information about external ids are available in this blog post.
Comment: In the trust relationship of Role_Account_B I have given access to Account C, and policy permission  as (s3*), but the STS generated can not access the Account C bucket.
I get this error:
`Received error response: com.amazonaws.services.s3.model.AmazonS3Exception: Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied;
Request ID: A51A3847E64F93D9; S3 Extended Request ID:`
Comment: Has the S3 bucket policy whitelisted the Account B role in its bucket policy? Have you got examples of your code?
Comment: Right I see the code there, although cannot see where these credentials are being used by S3 client. You appear to be specifying a policy but does the IAM role (configured in account B) itself have the permissions too? :)
Comment: You mean permission policy for Role_B. Yes. I have added that code as well.
The credentials are being used to create a S3 client in another part of the code
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/218134/discussion-between-chris-williams-and-ta).


404 customisation

Question: I want to make a custom 404 page.
I created a .htaccess containing only this line :
ErrorDocument 404 /errors/404.html

And the structure of my website is like this :

errors

404.html

index.php
.htaccess
includes

header.html

I always get this erros on the 404 page :
Not Found

The requested URL /blabla/bg was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

An idea ? Thank you !
Comment: Case sensitivity of the directory where your custom 404 page resides maybe?
Comment: My fault in the post, the folder is called "errors" without cap
Comment: Then any other `RewriteRule`s before that?
Comment: Similar suggestion: are you sure it's `html` not `htm`. Also you might need to post more of the htaccess file for context; that line should be fine. Are you using a virtual server setup?
Comment: I don't have any RewriteRule before, only the line mentionned. This is not a .htm problem. And i'm on my mamp server.
Comment: Can you post more context? It could be that you put the `ErrorDocument` line in the wrong place, or you might have the folders pointing to the wrong place, or as Havelock suggested you could be overriding it with another rule.
Comment: Also are you sure the htaccess file is even running? Some hosts disable htaccess files.
Comment: How could I be sure my .htaccess is running? But in the error page, the ErrorDocument is mentionned. So I wonder that it's running. And as told before, I don't have any other line in my .htaccess
Answer: My guess is that your document root is not equivalent to where your .htaccess is. Unfortunately, ErrorDocument is not relative to where your .htaccess is and instead bases the path on where your document root is (for instance /var/www/)
One (kind of hacky) solution I've used in the past to get "relative" 404 Error pages is to do the following:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.* 404.php [L]

The other (and more correct way) to do this is to specify the entire path from the true document root on your server.
To get this full path you'll want to open the 404 page in a browser (and make it a php page in your case so you can get this variable out: $_SERVER['SCRIPT_NAME']  or if you happen to have more knowledge of the setup of your directory structure.  You can base it off of $_SERVER['DOCUMENT_ROOT']
Comment: Well, you're first method works like a charm. I'll use the second one later, because i'm currently on my localhost and not the final server. Thank you for your answer !

404 customisation


malloc memory for pthread and then fork + execvp

Question: I get an event and based on that event i do some processing and then fork + execvp some other program (called some_jazzy_program). Initially i used a while loop where i did the following:
 while (some condition)
 {
      pid = fork();

      if (pid == 0)
      {
            do_some_work()

            execvp (some_jazzy_program..);
      }
      else
      {
            do_some_bookkeeping();
      }
 }

The problem with this design is that if do_some_work() takes up large amount of time then i am not able spawn new processes fast enough to launch some_jazzy_program. To fix this, i started using pthreads:
  pthread_t *work_threads[MAX_FORKS_ALLOWED];

  while (some condition)
  {
      work_threads[index] = (pthread_t *) malloc (sizeof (pthread_t));

      pthread_create(work_threads[index], NULL, do_some_good_work, NULL);

      index ++;
  }

  void * do_some_good_work (void *arg)
  {
      pid = fork();

      if (pid == 0)
      {
            do_some_work()

            execvp (some_jazzy_program..);
      }
      else
      {
            do_some_bookkeeping();
      }
 }

This design works. However, i have a few questions.
The fork + excvp is called which spawns a new process. Where should i call pthread_exit() in the parent program. With whatever i have read, i dont necessarily need to call pthread_exit since the thread automatically dies when the work its set out to do completes. In this context as soon as i do a fork + execvp it would die.
My other concern is about the work_threads[index] = (pthread_t *) malloc (sizeof (pthread_t)) -- the memory malloc that i am doing. When i use malloc i allocate memory from the heap. Where can i free this memory and release it back to the heap. Not doing anything looks like a memory leak to me.
Is what i am attempting here usually done -- first run multiple pthreads and within each pthread do a fork + execvp
Comment: Regarding the second problem, with you allocating memory, why simply *not* allocate memory and just have a plain array?
Comment: Also, having multiple threads that each does a `fork` is not very common I would think. At least not if the child-processes are running longer than the threads.
Comment: @JoachimPileborg I dont want to use a plain array since i may end up doing 30-40 forks under some scenarios. I didnt want to allocate such a high memory in the stack. Are you suggesting that i can never free malloc'd memory here?
Comment: `sizeof(pthread_t)` is not very much, you would need several hundred thousands, if not millions, to fill up the stack.
Comment: I am not sure i understand what you mean when you say the child-processes run longer than the thread. If i do a fork + execvp (some_other_program) then it should not matter how long the thread runs, right? As far as i am concerned, the thread dies only when the function do_some_good_work finishes. But, by then, i would have already forked + execvp'ed. Do you see any issues with that?
Answer: Regarding your first problem, you need not call pthread_exit. If your main program want to keep track of the threads, you may use pthread_join and check the return status of the threads.
Regarding your second problem, you can avoid heap memory allocation by just using:
pthread_t work_threads[MAX_FORKS_ALLOWED];
Regarding your third question, as Joachim said, it is not common to fork inside a thread; in fact a little dangerous too. Think before you mix them


Homorphism with injective and surjective

Question: I know the following is a true statement,
Let $f : G → G'$ be a homomorphism. If $\text{ker}(f) = \lbrace e \rbrace $ then $f$ is injective.
But I was wondering since I believe(please correct me if I'm wrong) a homorphism can be both injective and surjective. So, in the above statement could we say, ...if $\text{ker}(f) = \lbrace e \rbrace $ then $f$ is injection and surjective? I feel like I may be jumping to a conclusion that could be false.
Comment: There is no reason for $f$ to be surjective. Why should it?
Comment: @lhf That isn't true, for example take $G$ to be a proper subgroup of $G'$ and let $f$ be the identity embedding.
Answer: Let $G_1,G_2$ be two groups (with $|G_2|>1$),
Consider the map $\phi:G_1\to G_1\oplus G_2$, defined by $\phi(g_1)=(g_1,0).$
Here, $\phi$ is an injective homomorphism but clearly not surjective.
Answer: f need not be surjective if $ker f =$ {e}.An example is f(x) = 2x where G and G' are both the group of integers under addition. Here the kernel is {0} but f is not surjective.


How to bind a JavaFX Label to the selected item from a ListView

Question: I have a ListView full of POJOs and want a label in the GUI to display informations from the selected item.
My POJO looks something like that:
class Customer {
  private String name;
  ...
  public String getName() {
  return name;
  }

Now when the user selects a customer from the list I want the name of the selected customer displayed in a label.
Obviously I can't bind to the name directly because it is not a Property. (And I don't want to replace my Customers Strings with StringProperty-objects because the SimpleStringProperty is not serializable and I need the Customer to be transfered via RMI.)
I've tried the BeanPathAdapter from JFXtras (which looks really nice by the way) like this:
    BeanPathAdapter<MultipleSelectionModel> customerBeanPathAdapter;
    customerBeanPathAdapter = new BeanPathAdapter<>(lstCustomers.getSelectionModel());
    customerBeanPathAdapter.bindBidirectional("selectedItem.name", lblCustomerName.textProperty());

But this solution only throws me an Exception:
...
Caused by: java.lang.IllegalArgumentException: Unable to resolve accessor getSelectedItem
at jfxtras.labs.scene.control.BeanPathAdapter$FieldHandle.buildAccessor(BeanPathAdapter.java:3062)
at jfxtras.labs.scene.control.BeanPathAdapter$FieldHandle.buildAccessorWithLikelyPrefixes(BeanPathAdapter.java:3022)
at jfxtras.labs.scene.control.BeanPathAdapter$FieldHandle.updateMethodHandles(BeanPathAdapter.java:2986)
at jfxtras.labs.scene.control.BeanPathAdapter$FieldHandle.<init>(BeanPathAdapter.java:2977)
at jfxtras.labs.scene.control.BeanPathAdapter$FieldBean.performOperation(BeanPathAdapter.java:1348)
at jfxtras.labs.scene.control.BeanPathAdapter$FieldBean.performOperation(BeanPathAdapter.java:1186)
at jfxtras.labs.scene.control.BeanPathAdapter.bindBidirectional(BeanPathAdapter.java:567)
at jfxtras.labs.scene.control.BeanPathAdapter.bindBidirectional(BeanPathAdapter.java:369)
at at.gs1.sync.qm.client.gui.MainWindowController.initialize(MainWindowController.java:61)
... 22 more
Caused by: java.lang.IllegalAccessException: symbolic reference class is not public: class javafx.scene.control.ListView$ListViewBitSetSelectionModel, from jfxtras.labs.scene.control.BeanPathAdapter$FieldHandle
at java.lang.invoke.MemberName.makeAccessException(MemberName.java:512)
at java.lang.invoke.MethodHandles$Lookup.checkSymbolicClass(MethodHandles.java:1113)
at java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:1094)
at java.lang.invoke.MethodHandles$Lookup.findVirtual(MethodHandles.java:626)
at jfxtras.labs.scene.control.BeanPathAdapter$FieldHandle.buildAccessor(BeanPathAdapter.java:3049)
... 30 more

So I hoped there would be a better solution than to use lstCustomers.getSelectionModel().selectedItemProperty().addListener(...) and handle the population of the labels there manually.
Comment: Part of the problem is the access restricted implementation (looks like the adapter can't handle it). Another might be either a bug or invalid expectation (mine as well :-) - the value update seems to happen only in the direction from the bound property back to the adapted property (that is the path), not the other way round. At least couldn't make it work with the simplest of beans, neither one with fx-properties nor a plain core java bean property.
Answer: A better solution I think, to the one I gave before, is to use the BeanPathAdapter as you tried.
However the BeanPathAdapter needs to have the following property added to it:
private final ObjectProperty  beanProp = new SimpleObjectProperty<>();
{
    beanProp.addListener( new ChangeListener()
    {
        @Override
        public void changed( ObservableValue<? extends B> ob, B oldVal, B newVal )
        {
            setBean( newVal );
        }
    } );
}

public ObjectProperty beanProperty()
{
    return beanProp;
}

Then in your code you need the following:
BeanPathAdapter<Customer>  custBean;
custBean = new BeanPathAdapter<>( new Customer() );   // empty or any customer
custBean.bindBidirectional( "name", label.textProperty() );
custBean.beanProperty().bind( listview.getSelectionModel().selectedItemProperty() );

Comment: That looks very promising. I'll give it a try today. Thanks! (btw. sorry for the late reply!)
Answer: I don't think that there's a simple one liner that you are looking for.
You could do the following:
label.textProperty().bind( Bindings.selectString( listview.getSelectionModel().selectedItemProperty(), "name" ) );

But you will need to modify your Customer POJO like so:
class Customer
{
    private String name;
    ...
    public String getName() { return name;  }

    public ReadOnlyStringProperty nameProperty()
    {
        return new SimpleStringProperty( name );
    }
}

I don't think this is recommended though because properties are expected to reflect changes in the underlying data and the above will only reflect the name as it was when nameProperty is called. So if setName is called the property won't reflect the change. If the Customer name never changes then you could get away with this.


Display identical columns in R dataframe

Question: Suppose I have the following dataframe :
df <- data.frame(A=c(1,2,3),B=c("a","b","c"),C=c(2,1,3),D=c(1,2,3),E=c("a","b","c"),F=c(1,2,3))

> df
  A B C D E F
1 1 a 2 1 a 1
2 2 b 1 2 b 2
3 3 c 3 3 c 3

I want to filter out the columns that are identical. I know that I can do it with
DuplCols <- df[duplicated(as.list(df))]
UniqueCols <- df[ ! duplicated(as.list(df))]

In the real world my dataframe has more than 500 columns and I do not know how many identical columns of the same kind I have and I do not know the names of the columns. However, each columnname is unique (as in df). My desired result is (optimally) a dataframe where in each row the column names of the identical columns of one kind are stored. The number of columns in the DesiredResult dataframe is the maximal number of identical columns of one kind in the original dataframe and if there are less identical columns of another kind, NA should be stored:
> DesiredResult
  X1   X2   X3
1  A    D    F
2  B    E   NA
3  C   NA   NA

(With "identical column of the same kind" I mean the following: in df the columns A, D, F are identical columns of the same kind and B, E are identical columns of the same kind.)
Comment: possible duplicate of https://stackoverflow.com/q/9818125/4137985
Answer: You can use unique and then test with %in% where it matches to extract the colname.
tt_lapply(unique(as.list(df)), function(x) {colnames(df)[as.list(df) %in% list(x)]})
tt
#[[1]]
#[1] "A" "D" "F"
#
#[[2]]
#[1] "B" "E"
#
#[[3]]
#[1] "C"

t(sapply(tt, "length<-", max(lengths(tt)))) #As data.frame
#     [,1] [,2] [,3]
#[1,] "A"  "D"  "F"
#[2,] "B"  "E"  NA
#[3,] "C"  NA   NA


Run script no more than twice a day WITHOUT using cron

Question: Can a script be run no more than twice a day WITHOUT using cron ?
8/12/2018 5:46 p.m.
@Ravexina
This is my script using Ravexina recommendation.
SCRIPT=$(realpath "$0")
V=$(pstree -sp $$ | grep "($(pgrep -n atd))" -c)

if [ "$V" -ge 1 ];
then
        echo "$SCRIPT" | at "$(date +%H:%M) tomorrow"
fi

Docs_Backups=/media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Documents_Backups/
Scripts_Backups=/media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Script_Backups/
# Backup Documents
gxmessage -fg red -font  'sans 30' -timeout 3  ' BACKING UP FILES FOR UBUNTU_MATE 18.04.3 LTS'
cd ~/Documents
zip -u -q Ubuntu_Documents.zip *.txt *.doc *.rtf *.html *.png *.pdf *.odt *.ods *.odg
cp Ubuntu_Documents.zip /media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Documents_Backups/Ubuntu_Documents_`date +"%Y-%m-%d-%H-%M"`.zip # date is in year/month/day/hour/minute format
cd /media/andy/MAXTOR_SDB1/Ubuntu_Mate_18.04/Documents_Backups/
# This deletes unneeded date files except newest which are zero bytes
find . -type f -size 0b -delete
sleep 1
touch $( date '+%m-%d-%Y_%I:%M-%p' )

When I ran it, nothing happened at 17:41.
andy@7_~$ echo $HOME/script.sh | at 17:41
warning: commands will be executed using /bin/sh
job 4 at Sun Aug 12 17:41:00 2018

Comment: I have difficulties to see what you need, just run a script twice a day automatically or prevent a script from running more than twice a day? Please make your question a bit more clear.
Comment: I want to prevent a script from running more than twice.
Comment: I don't get it. Why don't you have cron call the backup script once a day and then optionally call it yourself on demand.
Comment: @fixit7 After the lines from my answer, before your script get started, add `echo hello > $HOME/my-script-output`, then add the script as a `at` job: `echo $HOME/script.sh | at HH:MM` after it got executed check the output of `~/my-script-output`. I want to make sure that the script is getting executed first.
Answer: As you mentioned about cron I suppose you are trying to run the script automatically twice a day.
It's better to use cron, however you can also use at command, lets say my script is located at $HOME/script.sh and is executable.
First I need to add these lines in the beginning of my script:
SCRIPT=$(realpath "$0")
V=$(pstree -sp $$ | grep "($(pgrep -n atd))" -c)

if [ "$V" -ge 1 ];
then
        echo "$SCRIPT" | at "$(date +%H:%M) tomorrow"
fi

The I need to run:
echo $HOME/script.sh | at 18:00
echo $HOME/script.sh | at 20:00

Now my script will be run at 6PM and 8PM and each time if it has been executed using at daemon it will schedule itself to be run tomorrow at the same time.
It's just a funny idea that I wanted to share ;)


Is there a way to pass a "C#" object to a controller via AJAX?

Question: It's simple enough to pass a string to a controller action via jQuery ajax, but is it possible to serialize a group of variables into an object, send it to the controller, and have the controller recognize it as an object?
For example:
In the server, you have a class Obj as such:
class Obj{
    string a; int b; double c;
}

And in the controller, you have a method that is expecting an Obj object
public JsonResult UpdateObj(Obj obj){
    //stuff
}

Is there a way in Jquery to serialize some JavaScript vars into a class Obj and then send it to an MVC controller action via an AJAX post?
Comment: It's already built into MVC 3. The JSON request just needs to match the properties in your `Obj` and the modelbinders will bind the values for you.
Answer: Sure, let's suppose that you have a strongly typed view:
@model Obj

and in the controller action:
public ActionResult SomeAction(Obj obj)
{
    ...
}

Just a remark about this Obj, make it have public properties instead of some fields:
public class Obj
{
    public string A { get; set; }
    public int B { get; set; }
    public double C { get; set; }
}

Comment: @Robert Harvey, with nothing, ASP.NET MVC 3 does that for you.
Comment: @Jay Sun, that's normal, you should not have circular references in your view models. It is impossible to JSON serialize objects that contain circular references. This is not supported and is a bad idea anyway. You should never be passing any EF domain models to your view. You should use and define view models which are specifically designed to the requirements of your view.
Comment: The whole Html.Raw looks solid, but I get syntax errors when I encode the model.
Comment: If I try and run that code as is, I get a server error "A circular reference was detected while serializing an object of type TitleDataEntity" which is the actual object I need to serialize.
Comment: Can we have "success: reloadPage" command in the Ajax request?
Answer: jQuery :::
.ajax{
     type: "POST",
     url: "yourUrl/UpdateObj",
     data: $("someHTMLForm").serialize(),
     contentType: "application/json; charset=utf-8"
     success: function(data){
           //data will house your JsonResult
     }
}

Comment: Don't need to deserialize.  application/json contentType tells MVC to match the JSON object with your .NET object via a dynamic serializer -- the System.Web.Services.Script.JavaScriptSErializer class


Civ 5 BNW: why are city states far tougher than major civ cities on settler?

Question: I started a game of Civ 5 BNW with the mod that makes the USA completely broken (every important unit is upgraded, start with all 4 base techs unlocked, start with 3 settlers, 3 workers and a super strong scout) to have some conquest fun (although I forgot to actually enable the conquest victory, or any victory for that matter). I didn't have any other factions on my continent (180X96 earth with true starting locations), so I could tech up in absolute peace and quiet.
So I teched up to Peacemaker (giant death robot of the US) and started conquering the other civs: Egypt, Russia, Korea, Venice and Greece. I saved Korea for last because they were the farthest away and I would have to cross  the entirety of Asia to get there. I was planning on taking over all the city states on my way there, but that actually wasn't feasible. While the cities of all other factions had extremely low defense (20-30 next to their shield icon), all the city states had stats in the mid-to high 100's, like 160-180. They could go toe to toe with my peacemakers and come out on top.
Why were those city states so damn strong? Is there a hidden effect for this somewhere?
Answer: The defense of a city is based on its owner's Technology level and its population. While there isn't a specific bonus to city states, this does tend to make them rather well defended for several reasons.
First, there are a lot of things city states cannot build. Since they never build wonders, settlers or more than 1-2 workers, and because each city state is essentially a capital, they tend to run out of things to produce. They usually build defensive structures as soon as they become available.
Second, since city states can only expand up rather than making more cities, don't deal with unhappiness, and are founded in 4000 BC they tend to be quite large- often comparable to capitals.
These factors can often cause city states to have higher defense than most cities anyway (though this makes up for their small armies). In this case there is another factor at work- City States don't have science. Instead, their technology is based on that of other civs. Typically they have any tech that two or more civs have but they can have more if there is a runaway tech leader.
This means that while the enemy civs are multiple ages behind you (since you mentioned needing to play on settler in addition to running that mod), city-states are much closer to your level.
You're also comparing them with cities that are completely crippled by your mod and difficulty. It's actually normal for cities to have a slightly higher defense than the units they're facing- taking cities requires a lot of units.


ProGuard fails when updating to Android SDK 23

Question: I am trying to update the Umweltzone Android application to SDK 23. Therefore, I change the project configuration as follows:
<code>// Excerpt from Umweltzone/build.gradle
compileSdkVersion 23
// ...
compile "com.android.support:design:23.1.1"
</code>
When I build a release version this fails with this error (tailing part):

...
  Note: there were 3 references to unknown classes.
        You should check your configuration for typos.
        (http://proguard.sourceforge.net/manual  /troubleshooting.html#unknownclass)
Note: there were 2 classes trying to access enclosing classes using
  reflection.
        You should consider keeping the inner classes attributes
        (using '-keepattributes InnerClasses').
        (http://proguard.sourceforge.net/manual/troubleshooting.html#attributes)
Note: there were 100 unkept descriptor classes in kept class members.
        You should consider explicitly keeping the mentioned classes
        (using '-keep').
        (http://proguard.sourceforge.net/manual/troubleshooting.html#descriptorclass)
Note: there were 5 unresolved dynamic references to classes or
  interfaces.
        You should check if you need to specify additional program jars.
        (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclass)
Note: there were 3 accesses to class members by means of
  introspection.
        You should consider explicitly keeping the mentioned class members
        (using '-keep' or '-keepclassmembers').
        (http://proguard.sourceforge.net/manual/troubleshooting.html#dynamicalclassmember)
Warning: there were 1 unresolved references to library class members.
           You probably need to update the library versions.
           (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedlibraryclassmember)
Warning: Exception while processing task java.io.IOException: Please
  correct the above warnings first.
  :Umweltzone:transformClassesAndResourcesWithProguardForRelease FAILED
FAILURE: Build failed with an exception.

What went wrong: Execution failed for task   ':Umweltzone:transformClassesAndResourcesWithProguardForRelease'.
  > java.io.IOException: Please correct the above warnings first.

The release build does work with SDK 22. The ProGuard configuration can be found here. The full build output can be found here since StackOverflow does not let me paste here because of length restrictions.
Answer: Stick to the error message, i.e. correct the above warnings first.
The above warning is:
<code>com.google.android.gms.auth.GoogleAuthUtil: can't find referenced method
'void setLatestEventInfo(android.content.Context,java.lang.CharSequence,
java.lang.CharSequence,android.app.PendingIntent)' in library class android.app.Notification
</code>
Most likely, you don't need that method. So you can get rid of the warning by adding the below line to the proguard config:
<code>-dontwarn com.google.android.gms.**
</code>
Comment: Nice! This actually fixed the build. Can you explain why this warning occurs even though I just increase the SDK version but did not change the code?
Comment: It looks like a glitch in the latest version of the Google Play Services (or support library).


PostgreSQL PSQL SELECT into a variable

Question: On the Postgres console (PSQL) I try to write a simple 'batch' test:
\set oid

\set username 'john'
\set emailadr 'email@example.com'
\set password 'jjjj'
INSERT INTO :oid SELECT auc_user_insert(:'username', :'emailadr', :'password');
SELECT auc_user_select(:oid);
SELECT auc_user_delete(:oid);

auc_user_insert, auc_user_select and auc_user_delete are application specific Postgres functions and work fine for each self (within the Query Tool).
The insert Function returns a bigint as unique id, which I would like to assign to the variable oid for usage in the next lines.
But in PSQL for the INTO :oid statement I get the error
ERROR:  Relation 'bigint' doesn't exist

What's wrong and what would be the right way to work with such a variable? Thanks for any hint!
Answer: Assuming the INSERT INTO is meant to affect the :oid variable rather than inserting the result of a select into a table, you want this instead:
SELECT auc_user_insert(:'username', :'emailadr', :'password') AS oid;
\gset
SELECT auc_user_select(:oid);
SELECT auc_user_delete(:oid);

\gset is a new meta-command since psql 9.3
If you have an older version, it's much harder to emulate this.
Description from the manpage:

\gset [ prefix ]
Sends the current query input buffer to the server and stores the query's output into psql variables (see Variables). The query to be
  executed must return exactly one row. Each column of the row is stored
  into a separate variable, named the same as the column

PostgreSQL PSQL SELECT into a variable


Using existing gas connection for new gas range?

Question: I would like to connect a regular GE gas stove like this to a connector that was used by a Vulcan residential gas range (similar to the one here)
Here is some information on the existing connector:
This is the pipe that supplies the gas to the Vulcan range.

This pipe has a nut attached to it. I unscrewed it and took pictures of it:

What would I need to do to use this existing gas connection with this regular GE gas stove?
Is it something that I can do?
Comment: Aside from the risk/benefit equation, once you investigate the required connections involved between the two stoves (which can only be done after moving the old stove out), you must factor in your time for at least 1 trip to the hardware store (usually more than one) as part of your DIY cost. then you should replace all of the flexible connections, do NOT re-use older flexible connectors because they can crack when you pull the old stove out away from the wall after sitting still for so long. There may also be code changes from how the new connections must be done vs when the old one was done.
Comment: Considering what might go wrong compared to the cost of hiring a licensed professional installer is this really something you want to do?
Comment: You'll need to decide on that yourself. Basically, the connection is made using a  yellow (usually) flex pipe from the existing gas pipe valve to the appliance. It isn't hard or complex, but is does need to be done just right. Also, some localities may prohibit installation of gas appliances by non-licensed persons. You should check the procedure on a home site or look at a you-tube video to see if that is something within your comfort zone and also make sure that you're even permitted to install it yourself.
Comment: Fitting size is important as well.  It's basically as easy as @Ring suggests _if_ the fittings are all the right size.  If you get into having to change fittings, that can get a lot more complicated.
Comment: more than likely, what does the gas connection look like?
Comment: @DonBoitnott, You're right to point that out. If the supply fitting was had been wrong, I'd not have even tried.
Comment: @J.Raefield, If I'm shifting stoves, that isn't so much an issue. I can look at fittings when I move the stove. Move residential units have a standard fitting (1/2 inch flare? It's been a long time since I did my stove).
Answer: I would call this a very simple job, if you can change a car tire this would be easier.  The basics are proper sealing compounds or tape at the joints, usually 2 adjustable wrenches or a pipe wrench and an adjustable wrench are the only tools needed. And last a bubble leak solution to check the new connections.
Some fittings use special pipe tape it is yellow or an approved for gas pipe dope going from pipe to the flair fitting.  After leak checking your fittings I will literally a match at a burner and turn it on, it may take a minute for the air to be purged from the lines, once a burner lights I do the others and the oven. I do the oven last because many of the ones I have had use a hot surface ignition and I like to reduce the amount of time that is firing.
It really not difficult at all. Using the proper gas rated flex pipe and make sure the fittings are the correct size is critical. Depending on your connection to the gas system you may not need any sealant at all. It could be flair fittings then being clean and following the instructions like hand tight and 1/4 additional turn then checking for leaks. It is quite simple but some basic safety checks are important.
Answer: Easy, I think I have that stove! The oven light went out after 2 months otherwise it's working well.
However you cannot seal gas connections with teflon tape or anything else but special gas-certified sealer, which looks like yellow mud. See this image 1.

Get a flexible connector to go from the stove to the gas wall connection.
Use proper sealer for gas on the joints and screw together.
Check for leaks on every joint very carefully by using a soapy water mixture. Paint the soapy water on with a new paintbrush. If you see bubbles forming you have a leak. Either tighten the threads or unscrew and add more sealer compound.


Why the environment variable is unset after using setenv( )

Question: I wrote a C program in Linux to set the values of environment variables using setenv, but after execution, when I run set or export, the environment variable itself seems to be unset. Why?
Here is the code snippet:
int main()
{
  char *mallocPtr, *callocPtr, *reallocPtr, *memalignPtr, *vallocPtr;
  struct sigaction sa;

  sa.sa_handler=SIGSEGV_handler;
  sigaction(SIGSEGV, &sa, NULL);

  if(setenv("ENV1", "3", 1) == 0)
         printf("ENV1 set to 3\n");
  else
         fprintf(stderr, "setenv failed on ENV1");

Answer: The environment variables are set within the context of your program.
When your program exits, you're back in the context from where your program was started.
Comment: "[..]each process has a separate copy of the environment. As a result, you can't change the value of an environment variable in another process, such as the shell." from [here](http://www.steve.org.uk/Reference/Unix/faq_2.html#SEC8).
Comment: The man page for `getenv(), setenv()`, etc. says: `These functions set, unset and fetch environment variables from the host
     environment list.`
Comment: @Didier: But if the option "1" last argument of setenv is set, then i am expecting it to overwrite the already existing ones right? But it is not overwriting.
Comment: @Rudy: That's it..so it means it should set in my shell (or at least overwrite), right?
Comment: @kingsmasher1: you need to read the man page more carefully: `The setenv() function inserts or resets the environment variable name in the current environment list.  If the variable name does not exist in the list, it
     is inserted with the given value.  If the variable does exist, the argument overwrite is tested; if overwrite is zero, the variable is not reset, otherwise
     it is reset to the given value.` -- the overwrite parameter just controls whether you overwrite your existing environment variable setting - it has nothing to do with exporting the environment variable.
Comment: It overwrites the existing ones in the current process - try calling getenv in your program to see the change - but the current process is not the shell
Comment: @Paul R: `it has nothing to do with exporting the environment variable` so it means since it is not exported, it won't be seen, also if i set reset to "1" then the program does not use the existing value, but the value specified in setenv, right?
Comment: I can see that getenv done within same program gets the value set using setenv, but another shared library cannot. It extracts the one exported in the shell.
Comment: @kingsmasher1: that is what one could read into it, but that is not what happens.
Comment: i downvoted this answer. there are no details at all. the answer by zwol is much better.
Answer: The C library treats environment variables as global settings you can read with getenv and adjust with setenv/putenv, and that inherit across calls to the exec family, but that is a convenient fiction.  As far as the kernel is concerned, the environment variables are a second set of arguments to main.  This becomes clear if you look at the actual system call, execve, underlying the exec family.  This is its C prototype:
int execve(const char *filename, char *const argv[], char *const envp[]);
                                                     ^^^^^^^^^^^^^^^^^^

See that third argument?  That's the only way for process A to set process B's environment variables.1  Therefore, the only time process A can set process B's environment variables is when process A starts process B, via fork and execve.
Your program is started by the shell, so the shell got to set its copy of the environment variables, but there is no way for it to push a change back to the shell -- just as there is no way for a C function to change the values of its arguments in its caller.
1 Do not bring up ptrace.
Comment: best answer, explains everything
Answer: Actually every process has its own envp char array. The main function has the following signature:
int main(int argc, char *argv[], char *envp[])

Usually, the envp of the parent inherit to the child, down the parent-child hierarchy. It is by no means communicated upwards in the parent-child hierarchy.
Comment: `main` with three arguments is definitely non-standard C. Some implementation may support it, but you shouldn't rely on it.


Can't use NSMutableArray data after Parsing with NSXMLParser (objective-c)

Question: Hi I did parsing with NSXMLParser of some xml :
<company>
     <name>Idan</name>
     <country>Israel</country>
      .....
     <gender>man</gender>
</company>

I see that parsing success , now I have the MutableArray with one object that contain all strings (Idan,Israel etc.) but when I want to use this array, I can't get strings it contain.
When I do :
NSMutableArray *use = [pars users ];
        NSLog(@"%@",use );

(users it's my array with object) I see:
 <List:03f5a78>

where List in my code is:
#import <Foundation/Foundation.h>
@interface List : NSObject{
    NSString *name;
    NSString *country;
    NSString *status;
    NSString *gender;
}
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *country;
@property (nonatomic, strong) NSString *status;
@property (nonatomic, strong) NSString *gender;
@end

#import "List.h"
@implementation List
@synthesize name,date,city,country,status, gender;
@end

I try to do something like this:
     NSMutableArray *use = [pars users.name ];
     NSLog(@"%@",use );

but is not working, any ideas how to fix this?
Comment: Just because the variable "use" is declared as an NSMutableArray doesn't mean it is one.  And it would be helpful to know what kind of object "pars" is, and what the "users" method of it is supposed to do.
Answer: Override the description method of your List class, and return a string which includes the values of all of the properties, then output it like you did the first time.  The console will then print the value you returned.
Example:
@implementation List

...
...
    -(NSString *)description
    {
        NSMutableString *desc = [NSMutableString string];
        [desc appendFormat:@"name=%@, ", self.name];
        [desc appendFormat:@"country=%@, ", self.country];
        [desc appendFormat:@"status=%@, ", self.status];
        [desc appendFormat:@"gender=%@", self.gender];
        return desc
    }
...
...
@end

Comment: Better is to create an NSDictionary with those fields and keys, and then run it through stringWithFormat.  Comes out nicely structured, and easy to maintain.
Comment: I agree if format was important for debugging and I didn't mind checking nil on each property.  The dictionary would be especially useful for huge classes.


bootstraps 4 Error: Collapse is transitioning

Question: can anyone help me please to slove transition issue bootstrap 4.
this is making error Uncaught Error: Collapse is transitioning issue is only when not include bootstrap css. in my case bootstrap css conflict my large css. can anyone help to slove out this hell

          Collapsible Group Item #1

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid.

          Collapsible Group Item #2

        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid.

Answer: This issue has been solved on Bootstrap 4.0.0-beta. The 4.2.1 version is available now!

There are several ways to download it:

Download the latest release in a zip file.
Clone the repo: git clone https://github.com/twbs/bootstrap.git
Install with npm: npm install bootstrap
Install with yarn: yarn add email@example.com
Install with Composer: composer require twbs/bootstrap:4.2.1
Install with NuGet: CSS: Install-Package bootstrap Sass: Install-Package bootstrap.sass

You can see the Beta 1 ship list #21568 link for more information.

INITIAL ANSWER
There is an error with the Bootstrap v4.0.0-alpha.6 version with the transitioning that will be solved on the next release.
See the issue 22256, pull 21743 and v4.0.0-beta milestone links for more information.
For while, you can use workarounds like the @Nayana_Das example.
Answer: Collapse div using following code:
$(".header").click(function () {

    $header = $(this);
    //getting the next element
    $content = $header.next();
    //open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
    $content.slideToggle(500, function () {
        //execute this after slideToggle is done
        //change text of header based on visibility of content div
        $header.text(function () {
            //change text based on condition
            return $content.is(":visible") ? "Collapse" : "Expand";
        });
    });

});

Check out this FIDDLE.
Comment: i know this but i'm looking for without bootstrap css.
Comment: @shivshankar : Glad, it worked for you, hope you will accept this answer.
Answer: I recently also had the problem with an older BT project. My problem was simply that I had 2 navbars and both had the same id (as I copied the example twice).
This does not seem to be the case here but I thought I mention it as somebody else might come across this question and has the same issue.
Answer: I have faced same problem and accidentally came up with a solution.

            Inbox

One

Two

Three

In the above Code I have to collapse id -> #collapse1
And Accidentally I created two div and when I reloaded my page the second one was working fine, and first one opened but was not closing and giving the error of transitioning. So I just deleted the content of first #collapse1 and keep it empty and the second one is working fine.
   I also tried other options such as updating Bootstrap version or changing the place of div, none of them worked. I hope this helps.
Thank you


Change . visible property in array by filtering based on array of indexes

Question: Need to create a new array3 from array1 by making visible false for indexes not present in array2.
Here in the following example I have indexes 0,2. So The outcome array must have visible as false for 1,3
var array1 = [{
    "visible": "true",
    "id": 0
}, {
    "visible": "true",
    "id": 1
}, {
    "visible": "true",
    "id": 2
}, {
    "visible": "true",
    "id": 3
}];

var array2 = [0,2]

Expected outcome:
array3 = [{
    "visible": "true",
    "id": 0
}, {
    "visible": "false",
    "id": 1
}, {
    "visible": "true",
    "id": 2
}, {
    "visible": "false",
    "id": 3
}];

Answer: One option could be to use map on array1 and use includes on array2. Inside map, create a copy of the original object so that the original objects in array1 will not be mutated.

var array1 = [{
  "visible": "true",
  "id": 0
}, {
  "visible": "true",
  "id": 1
}, {
  "visible": "true",
  "id": 2
}, {
  "visible": "true",
  "id": 3
}];

var array2 = [0, 2];

var array3 = array1.map(i => {
  var dc = JSON.parse(JSON.stringify(i));
  dc.visible = array2.includes(i.id).toString();
  return dc;
});

console.log(array3);
console.log(array1);
Answer: You could turn array2 into a Set for a constant lookup-time:

function hide(array1, array2) {
    const indexes = new Set(array2);
    return array1.map(o => !indexes.has(o.id) ? ({...o, visible: "false" }) : o);
}

var array1 = [{
  "visible": "true",
  "id": 0
}, {
  "visible": "true",
  "id": 1
}, {
  "visible": "true",
  "id": 2
}, {
  "visible": "true",
  "id": 3
}];

console.log(hide(array1, [0, 2]));

This will only do what is asked: turn visible to "false" where the id is not listed. It will not do the opposite, i.e. it will not turn visible to "true" when the id is listed: it will just copy the original setting.
If also the opposite should happen, then the original value of visible no longer plays a role:

function hide(array1, array2) {
    const indexes = new Set(array2);
    return array1.map(o => ({...o, visible: indexes.has(o.id)+"" }));
}

var array1 = [{
  "visible": "true",
  "id": 0
}, {
  "visible": "true",
  "id": 1
}, {
  "visible": "true",
  "id": 2
}, {
  "visible": "true",
  "id": 3
}];

console.log(hide(array1, [0, 2]));

Note that it would make more sense if visible were a boolean instead of a string (false and true instead of "false" and "true").


Segmentation Fault upon call to GetSystemTime() function (Windows)

Question: I'm having trouble dealing with a segmentation fault. The following sanity check throws one:
#include <windows.h>
int main()
{
    LPSYSTEMTIME startTime;
    GetSystemTime(startTime);
}

However, I've used the same code in a much larger program, and it runs without a problem. I've tried adding delays in various places in case the problem stems from some sort of multithreading within GetSystemTime(), but it did not solve the problem.
I'm compiling with MinGW-GCC in CodeBlocks.
Answer: LPSYSTEMTIME is a pointer to a SYSTEMTIME structure. You don't initialize the pointer so it's pointing somewhere into the scenery, hence the access violation/seg fault.
In order to make the code work, you have to make sure the pointer points to a valid SYSTEMTIME structure. As per the MSDN docs, Microsoft explicitly warns you that passing in NULL for the pointer will result in an access violation.
Comment: In general when you see LP they mean Long Pointer... (long is historical).  Generally if you strip the LP from a type, you have the actual structure with allocation storage on the stack... e.g. `SYSTEMTIME`, then you'd pass `&startTime`
Comment: Thanks. I really dislike how Microsoft defines a different name for everything - it just makes everything more confusing.
Answer: You are using an uninitialized pointer. This works better:
#include <windows.h>
int main()
{
    SYSTEMTIME startTime;
    GetSystemTime(&startTime);
}

Answer: LPSYSTEMTIME is a pointer, you need to either allocate memory or you need to loose the LP in LPSYSTEMTIME and call the function as in:
SYSTEMTIME startTime;
GetSystemTime(&startTime);

Answer: LPSYSTEMTIME is a pointer to SYSTEMTIME, but it hasn't been initialized.
Try this instead:
SYSTEMTIME startTime = { 0 };
GetSystemTime(&startTime);

Answer: For using  LPSYSTEMTIME you should write the following:
SYSTEMTIME  systemTime; //allocation of memory
printf("%p\n", &systemTime.wDay); // we can see address of wDay for example.
LPSYSTEMTIME st = &systemTime;
GetSystemTime(st);
printf("%d \n", st->wDay);  //display result
printf("%d \n", (*st).wDay); //display the same result


What items are excluded from Re-Tail premium list?

Question: What items can't be on the Re-Tail premium chalk board list? I want fossils but I've never seen it on the list nor can I find an answer anywhere. Is there a full list hidden somewhere of everything on the list? If not I could help build one for future use. I need one badly myself as I'm running out of room.
Answer: Fossils do show up on the chalk board for paying extra. I can verify that from personal experience. I don't believe I've ever seen a specific fossil, just the generic "Fossils".
As for what is excluded from being bought at premium? I'm not aware of anything specific. I've seen pretty much anything you can imagine show up on that board in one form or another on the two copies of the game I have. It can be anything from "Shoes" or "Furniture" to something specific like "Crucian carp".
Your question is a bit confusing though as when something is on the chalk board it's because Reese is paying extra for that item. You get fossils by digging up the X marks around town and having them appraised at the museum and you then donate them. It took me almost a year of grinding fossils to get a 100% set. Extra fossil sets can be taken to Cyrus to be turned into miniatures and beyond that you can sell them for Bells all the time and get paid well for them. They have to be appraised before you do anything with them though or Reese will pay almost nothing for them. If you're hording extras, just sell them and free up the space.
Comment: I was asking if the fossils could go on premium. Thanks so much. Lol I wasn't asking for fossils at the shop, I've been saving em in my storage for when they do go premium.


Nesting IF statement inside a loop throwing error

Question: The error I am receiving:

Exception: The parameters (String,number) don't match the method signature for SpreadsheetApp.Spreadsheet.getRange.

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  var VALUE = "Hide";
  var COLUMN_NUMBER = 11;

  ui.createMenu('Hidden Rows')
      .addItem('Hide Rows w/Status = Hidden', 'menuItem1')
      .addSeparator()
      .addItem('Unhide Rows w/Status = Hidden', 'menuItem2')
      .addToUi();
}

function menuItem1() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var activeSheet = ss.getActiveSheet();
  var cell = ss.getActiveCell()
  var cellValue = cell.getValue();

  for (r=1; r<lastRow; r++)  {
    ss.getRange(r,11);

      if(cellValue == VALUE){
        activeSheet.hideRow(cell);
      };
  }

}

function menuItem2() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
     .alert('Second menu item!');
}

Answer: Try this:
var VALUE = "Hide";//global

function menuItem1() {
  var ss = SpreadsheetApp.getActive();
  var activeSheet = ss.getActiveSheet();
  var cell = ss.getActiveCell()
  var cellValue = cell.getValue();
  for (let r=1;r<lastRow;r++)  {
    if(cellValue==VALUE){
      activeSheet.hideRow(cell.getRow());//this hides the row of the activeCell() not the row of the iteration index
    }
  }
}

These two values are not global scope in your script:
var VALUE = "Hide";
var COLUMN_NUMBER = 11;

They cannot get hoisted into global from function scope.
Interestingly enough that very line that caused the error does nothing.
ss.getRange(r,11);

You might have r defined to be a string some where so I declared r to have section scope in the loop.  You should probably review const,var and let in a JavaScript reference.
It's not clear to me from your script what you had it mind but perhaps this is it.
function runOne() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const rg=sh.getDataRange();
  const vs=rg.getValues();
  const cell=ss.getActiveCell()
  const cellValue=cell.getValue();
  vs.forEach(function(r,i){
    if(cellValue==r[10]){
      sh.hideRows(i+1);
    }
  });
}

Comment: Thank you, but how do I pass the column number into the loop?
Comment: The column number or the row number?
Comment: Column...I am trying to loop through column 11 (column K)
Comment: No actually you're looping through rows.  And I assumed from this `ss.getRange(r,11);` that you probably wanted the cell value of column 11.  That's what my latest example does.
Comment: I didn't see that for some reason.  You are right I was looking for cell value in Column 11, but now I'm getting:  Exception: The parameters (number) don't match the method signature for SpreadsheetApp.Sheet.hideRow.
Comment: Please try it again.
Comment: I spent an hour reading through for/each documentation and came up with this:   ` if(r[10] == "Hide"){`   Thank you so much for your help. Based on the number of down votes I received, I'm guessing I didn't explain how I initially was troubleshooting.
Comment: Learning to use the Array looping methods is well worth your time.


Failed to load Steamui.dll error

Question: I tried to install Steam on my PC today, and it didn't work due to the "Failed to load Steamui.dll" error.
Of course, I tried most of the solutions on the web, such as deleting and re-installing Steam, manually removing the Steamui.dll file and/or replacing it with one on the web, but these solutions didn't work. Every time I try any of these fixes, the same error occurs.
How can I fix this?
There are no Korean-named folders in the way, if you were wondering.
I also noticed something strange: when I was trying the fix where you delete the Steamui.dll and Libswscale-3.dll files, I noticed that my Steam installation didn't have the Libswscale-3.dll, but a Libswscale-4.dll, instead. I'm not sure if this is causing the problem, but I think this may be of importance. I didn't tamper with it just in case it would cause even more problems.
In the image below are the contents of my Steam's DLL folder.
Ignore the DLL named originalsteamui - it was what I was tampering with.
Comment: Hi Hu sh, it would be easier if you just mention the current state of affairs, and not the things you were looking for and then found. Also: what's the premise here? You *tried* reinstalling something which is Steam, I presume, but why did you do so, and why are you stuck at *trying*? It would also be a lot easier if you describe what we're supposed to see in the screenshots, so it's easier to follow your already muddled story.
Comment: Oop sorry, let me make it clearer. As you can probably tell, I'm not the most mature...
Comment: Hope this edit cleaned up any confusions!
Comment: Yes, thank you. I hope my answer will help you.
Answer:
In most cases it's practical to start troubleshooting a malfunctioning program by running it as an administrator of your system.
This is likely not the cause here, but it can help speeding up the process.
Temporarily disable any third-party firewall, anti-virus software (Windows Defender usually plays nice, for a change), or other intrusive software, and try restarting Steam.
Take caution, as this will also temporarily leave your system vulnerable, so be sure to re-enable directly after a problem is fixed (that is: disable only during that window of restarting Steam).
Try deleting that Libswscale-4.dll file: it surely is a newer version of Libswscale-3.dll, and, in any case, if Steam is missing files, it will redownload them.
There are a few more fixes explicitly for your case mentioned in this Steam Community thread, most successful of which seem to be (or seems to be a combination of) the following steps [edited slightly for readability]:

All you have to do is restart your computer in Safe Mode. Delete all of your Steam files other than the AppData folder and the Steam.exe file. Double click Steam.exe and it should successfully install the update.

and

Fastest way, instead of redownloading after deleting the files in Safe Mode, is to add the following parameters to your Steam shortcut: -clientbeta client_candidate (e.g. "C:\Program Files\Steam\Steam.exe" -clientbeta client_candidate).

Now, before you try this in Safe Mode, I suggest deleting the mentioned files - as administrator - in the normal Windows mode, creating a shortcut, adding those parameters, and running it - as administrator. If that doesn't work, you can always fiddle around in Safe Mode.
Comment: Thanks for the huge amount of help! I'll try them out and tell you the results.

Failed to load Steamui.dll error


Launching Another App

Question: Is it bad practice to launch a webpage in Safari from your iOS app? It seems to have its pro's and con's.
Pros

The transition to Safari looks better than to an in-app browser
Users are more comfortable using Safari because they use it more often
The overall layout/look of Safari looks better than in-app browsers

Cons

Less customization
Once users leave your app, there is no guarantee they will return

What would your advice be regarding this? The UX for viewing the webpage would increase probably, though it may hurt me in the long run.
Comment: Common way is to open web page inside your own app, add back/forward navigation and provide an "Open in Safari" action for those who really want (need) to go to Safari.
Comment: Addition to question: If it turns out that this is considered a bad practice, what alternatives do you have? What are some other ways to allow the user to do the same things without going to a browser?
Comment: An passive indication for the user that the following action will open another application is a good idea to avoid switch-shock.
Answer: Apps that people use a lot (e.g. Facebook, Twitter, etc.) from my experience all seem to have a built in browser, with the option to open in safari.
I'd say that's the best experience for a user; some users will want to open it in safari, and you're then providing that option for them. Others, however, will just expect to see the link, so they can then close it and continue with whatever it was they were doing in your app, without interrupting the flow of what they were doing.
Answer: I don't know what kind of app this is for, but often times users find too much navigation frustrating. Some people may not be aware that clicking this link will bring them to Safari, so offer a pop-up after clicking the link that confirms they would like to move to the page on Safari. The other issue you have is that your app will close and this unfortunately as you said may prevent the user from going back to the app. Personally, I think it's a good idea to keep the user on your app for as long as possible so try and work out a way that the app can run in the background while the user is on safari then upon hitting the back button they are brought back to the app. Just some suggestions, hope it helps.

Launching Another App


Will the Nouveau driver continue to get updates?

Question: I installed Natty yesterday and it gave me the option to install "Experimental 3D support for NVIDIA cards" (which I'm assuming is Nouveau). Now, is there a PPA I will need to add to receive regular updates for the driver or will Canonical push updates out to me automatically?
Answer: Unless there are security fixes or certain bug fixes specifically for the drivers in Ubuntu, it is unlikely that you will get regular updates of the Nouveau drivers.
You can read more about Stable Release Updates on the wiki but basically once a version is released it does not change much.
Nouveau is an open source graphics driver so there will be improved drivers each Ubuntu release. Nouveau's 3D support is rather new and there will definitely be performance improvements by the time Ubuntu 11.10 is released.
Comment: Ok, there is https://launchpad.net/~xorg-edgers/+archive/ppa but it is experimental so it may make your computer not work. Get familiar with ppa-purge before you use a PPA like that.
Comment: No PPA to speak of?
Comment: How can I **prevent** Nouveau from ever updating? I posted a [full question on this](http://stackoverflow.com/questions/16805424/prevent-nouveau-from-ever-updating-messes-up-cuda-installation).


Unable to compile bnull-transform.c - Apache Traffic Server

Question: I am trying to run bnull-transform example of Apache traffic server. After a making few changes which are not present on github version of the code, I was finally able to resolve the errors. But when I compile it using gcc I am getting the below errors -
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o: In function _start':
(.text+0x20): undefined reference tomain'
/tmp/cc5gVORu.o: In function my_data_alloc':
bnull-transform.c:(.text+0x13): undefined reference to_TSmalloc'
/tmp/cc5gVORu.o: In function my_data_destroy':
bnull-transform.c:(.text+0x7b): undefined reference toTSIOBufferDestroy'
bnull-transform.c:(.text+0x87): undefined reference to _TSfree'
/tmp/cc5gVORu.o: In functionhandle_buffering':
bnull-transform.c:(.text+0xa8): undefined reference to TSVConnWriteVIOGet'
bnull-transform.c:(.text+0xbe): undefined reference toTSIOBufferCreate'
bnull-transform.c:(.text+0xe7): undefined reference to _TSAssert'
bnull-transform.c:(.text+0xf9): undefined reference toTSIOBufferReaderAlloc'
bnull-transform.c:(.text+0x122): undefined reference to _TSAssert'
bnull-transform.c:(.text+0x130): undefined reference toTSVIOBufferGet'
bnull-transform.c:(.text+0x155): undefined reference to TSVIONTodoGet'
bnull-transform.c:(.text+0x16e): undefined reference toTSVIOReaderGet'
bnull-transform.c:(.text+0x176): undefined reference to TSIOBufferReaderAvail'
bnull-transform.c:(.text+0x19f): undefined reference toTSVIOReaderGet'
bnull-transform.c:(.text+0x1bd): undefined reference to TSIOBufferCopy'
bnull-transform.c:(.text+0x1cf): undefined reference toTSVIOReaderGet'
bnull-transform.c:(.text+0x1da): undefined reference to TSIOBufferReaderConsume'
bnull-transform.c:(.text+0x1e6): undefined reference toTSVIONDoneGet'
bnull-transform.c:(.text+0x1ff): undefined reference to TSVIONDoneSet'
bnull-transform.c:(.text+0x20b): undefined reference toTSVIONTodoGet'
bnull-transform.c:(.text+0x222): undefined reference to TSVIOContGet'
bnull-transform.c:(.text+0x233): undefined reference toTSContCall'
bnull-transform.c:(.text+0x24b): undefined reference to TSVIOContGet'
bnull-transform.c:(.text+0x25c): undefined reference toTSContCall'
/tmp/cc5gVORu.o: In function handle_output':
bnull-transform.c:(.text+0x294): undefined reference toTSTransformOutputVConnGet'
bnull-transform.c:(.text+0x2a8): undefined reference to TSIOBufferReaderAvail'
bnull-transform.c:(.text+0x2c6): undefined reference toTSVConnWrite'
bnull-transform.c:(.text+0x2ef): undefined reference to _TSAssert'
/tmp/cc5gVORu.o: In functionhandle_transform':
bnull-transform.c:(.text+0x315): undefined reference to TSContDataGet'
bnull-transform.c:(.text+0x341): undefined reference toTSContDataSet'
/tmp/cc5gVORu.o: In function bnull_transform':
bnull-transform.c:(.text+0x3b0): undefined reference toTSVConnClosedGet'
bnull-transform.c:(.text+0x3c0): undefined reference to TSContDataGet'
bnull-transform.c:(.text+0x3d4): undefined reference toTSContDestroy'
bnull-transform.c:(.text+0x3f1): undefined reference to TSVConnWriteVIOGet'
bnull-transform.c:(.text+0x401): undefined reference toTSVIOContGet'
bnull-transform.c:(.text+0x412): undefined reference to TSContCall'
bnull-transform.c:(.text+0x420): undefined reference toTSTransformOutputVConnGet'
bnull-transform.c:(.text+0x432): undefined reference to TSVConnShutdown'
/tmp/cc5gVORu.o: In functiontransformable':
bnull-transform.c:(.text+0x46a): undefined reference to TSHttpTxnServerRespGet'
bnull-transform.c:(.text+0x47d): undefined reference toTSHttpHdrStatusGet'
bnull-transform.c:(.text+0x49b): undefined reference to TS_NULL_MLOC'
bnull-transform.c:(.text+0x4aa): undefined reference toTSHandleMLocRelease'
bnull-transform.c:(.text+0x4be): undefined reference to TSError'
/tmp/cc5gVORu.o: In functiontransform_add':
bnull-transform.c:(.text+0x4e0): undefined reference to TSTransformCreate'
bnull-transform.c:(.text+0x4f9): undefined reference toTSHttpTxnHookAdd'
/tmp/cc5gVORu.o: In function transform_plugin':
bnull-transform.c:(.text+0x54e): undefined reference toTSHttpTxnReenable'
/tmp/cc5gVORu.o: In function TSPluginInit':
bnull-transform.c:(.text+0x59c): undefined reference toTSPluginRegister'
bnull-transform.c:(.text+0x5af): undefined reference to TSError'
bnull-transform.c:(.text+0x5bf): undefined reference toTSError'
bnull-transform.c:(.text+0x5d2): undefined reference to TSContCreate'
bnull-transform.c:(.text+0x5df): undefined reference toTSHttpHookAdd'
collect2: ld returned 1 exit status
Please help.
Answer: You are trying to compile this plugin (which is a .so) as a standalone app. That won't work. You should use the tsxs script that comes with your ATS installation, e.g.
tsxs -o null-transform.so null-transform.cc

Comment: I have no idea what you are doing, you must have found it before if you tried to compile it as above (which wouldn't work). It's built as part of the standard build if you do

    ./configure --enable-example-plugins


Do the Illusive Man's eyes mean anything?

Question: Throughout 2 and now beginning 3, I've wondered what is up with the Illusive Man's eyes and why they are so unique.
Is there an explanation by the series end that tells us why his eyes are so weird looking whether it be from biotic power which gained him his status and started the Cerberus group or maybe cybernetic infusion since it seems the Cerberus operatives are going under these changes/Shepard was infused with cybernetics when revived, or is this just an aesthetic feature added to emphasize his character?
Answer: The origin of The Illusive Man's eyes is told in the one of the Mass Effect comic books, titled Evolution, the full plot summary of which you can read here on the Mass Effect wikia. It's a 4-issue miniseries, so it's a bit long to completely paste here.
In it, you learn the origins of The Illusive Man and who he was before becoming the leader of Cerberus. I'd highly recommend reading the issues yourself, as it's a nice bit of background information, but I'll write up a quick summary about his eyes.
During the First Contact War, he was part of a mercenary group working for General Williams (Ashley's grandfather). He was exposed to a Prothean relic on Shanxi. Despite the fact that others who were exposed to when it activated ended up basically turning into Husks and losing their higher cognitive abilities, he did not change. However, his eyes were permanently changed and he is able to understand the language that the Husk-like beings now speak. You get to see the more human side of The Illusive Man, what happened to him to engender his pro-humanity stance, and why he believes in it so strongly.
It does not further specify in the comic book series nor in the Mass Effect novels what exactly the impact of this change was, and it is currently part of the mystery of The Illusive Man. The fact that it was a Prothean Relic however, may change your interpretations of his actions and motives.
Comment: @FallenAngelEyes Oh, no not you. I meant the wiki. Yours was much better. :)
Comment: For the record, I am perfectly fine with spoilers on anything.  Though I do want to read these comics as it sounds like they would be a very good read to figure out why Illusive Man is how he is today.
Comment: That plot summary is not written very well at all...
Comment: @Raven It wasn't my intention to do a full recap of the entire miniseries here, I just wanted to give him the basics. The details about Saren and his brother, the temple, the experiments, etc. aren't necessarily directly germane to the question and I figured the OP would get more out of reading the smaller details in the comics themselves. :) Or do you mean the linked one?
Comment: Its not a Prothean Relic but instead a Reaper Artifact.
Answer: the book mass effect:evolution states that the illusive man's eyes were

 changed by secondary reaper indoctrination.


Can I get a country back into XCOM program?

Question: I am playing XCOM - Enemy Unknown on Classic difficulty. In the first month, Australia quit the XCOM program. Due to the lack of money and fitting missions, I could not do too much to decrease the panic level there.
Is there any way to get this country back into the X-COM program, or is it gone for good?
Comment: That's XCOM, baby!
Comment: You just guessing, or you read it somewhere / tried yourself?
Comment: I'm pretty sure you can't
Comment: so far in my game I haven't figured out a way to do so and I'm fairly late into the game
Comment: Okay, but tell me then, is it a great loss to lose a country? Should i restart or just live with it?
Comment: its not too great of a loss, yes you lose some income, and you can't complete the bonus for that continent anymore, but its survivable
Answer: Nope.
Once you lose a country, it's gone for good. And once eight countries leave, your game is over.
There's no way to earn an "Extra Life", so you've got to get that satellite network up and running ASAP if you want to keep XCOM solvent.
Comment: not even with some tools to manipulate save games?


How entity edit URL from within plug-in in MS Dynamics CRM 4.0

Question: I would like to have a workflow create a task, then email the assigned user that they have a new task and include a link to the newly created task in the body of the email. I have client side code that will correctly create the edit URL, using the entities GUID and stores it in a custom attribute. However, when the task is created from within a workflow, the client script isn't run.
So, I think a plug-in should work, but I can't figure out how to determine the URL of the CRM installation. I'm authoring this in a test environment and definitely don't want to have to change things when I move to production. I'm sure I could use a config file, but seems like the plug-in should be able to figure this out at runtime.
Anyone have any ideas how to access the URL of the crm service from within a plug-in? Any other ideas?
Answer: There is no simple way to do this. However, there is one.
The MSCRM_Config is the deployment database that handle physical deployment properties, like the URL from which users are accessing the CRM deployment. The url that you might want is the one stored in "ADWebApplicationRootDomain", in the MSCRM_CONFIG.dbo.DeploymentProperties table. You may need some permission to access this database.
Note that this doesn't work in a deployment that is an Internet Facing Deployment.
Another way could be to query the discovery service to retrieve the same information (in the case that you are on the Online edition of MSCRM4).
Comment: To clarify what you're saying, the URL is in the table but only if I'm NOT using IFD?  I haven't tried IFD yet, but I thought it added internet facing deployment to an onsite deployment. I.e. both worked. Is this incorrect?
Comment: The problem is that if you deploy CRM using IFD, the URL should be http://orgname.dnsprefix.company.com when accessing from the internet. But what will be stored in CRM is http://internalservername and this can't be accessed from the internet...
Comment: OK, so the internal URL would still work, but the URL wouldn't work for IFD users. That makes (unfortunate) sense. Thanks
Answer: What do you mean by "change things"?
If you create a custom workflow assembly, you can give it a server url input.  Once you register it with CRM, you can simply type in the server url when you configure the workflow.  You'll have to update the url for any workflows that use the custom workflow assembly once you move to production, but you'll only have to do that once.
My apologies if this is what you meant you wanted to avoid.
Edit: Sounds like you may be able to use the CustomConfiguration attribute when you register the plugin.  Here's some more info.
http://blogs.msdn.com/crm/archive/2008/10/24/storing-configuration-data-for-microsoft-dynamics-crm-plug-ins.aspx
Comment: This is good to know, but I was using a plug-in, not a custom workflow activity. I need to be able to insert a URL into the body of an email (sendemailactivity) that is a link to a specific entity.
Answer: <code>String Url = ((string)(Registry.LocalMachine.OpenSubKey(
                             "Software\\Microsoft\\MSCRM").GetValue("ServerUrl"))
              ).Replace("MSCRMServices", "");
</code>


How to Run GWT Application in Wicket?

Question: I am new to GWT. i have Wicket application and want to run GWT application in one of the panels.
both are using maven.

should i invoke entry point class from GWT in wicket ?
how to interact with GWT XML configurations ?
Answer: Is it possible to run a regular JavaScript application there?
If yes, then please see a modern GWT as Java to JavaScript compiler. No need to deal with any XML or something, you use annotations instead. The new approach is called JsInterop. It's also the way you deal with J2CL (the GWT successor). The mentioned "modern GWT" is about the version 2.8 and above.
So you simply create a JS application using Java. You can use JavaScript frameworks like React or Vue (eg. https://github.com/VueGWT). Finally you compile this to regular JS application. The difference is that it is strongly optimized, you use Java (strong typing), you get benefits from Java related techniques like DI with Dagger2 and so on.
Some references:

http://www.luigibifulco.it/blog/en/blog/gwt-2-8-0-jsinterop
http://www.gwtproject.org/doc/latest/DevGuideCodingBasicsJsInterop.html
and more and more in Google when search for "JsInterop" in GWT context.
Comment: i change my approach to solve my problem. tnx anyway :)
Comment: ty for your answer. yes we can run js in wicket. if i want to export the hole application and somehow call the js file (that jsinterop creates?!) in wicket, how that will happen?
Comment: the gwt application itself is big project with lot of classes ...
Comment: If about the way of calling JS app, please see the second link I provided. You have there a simple hello world example:
`var aClass = new com.gwt.example.MyClass('World');`
`console.log(aClass.sayHello());`
More details in both suggested articles, and much more in Google Search...
Comment: Your comment suggests it is some legacy application. With the "modern GWT", you use compiler only, not GWT Framework itself. You transpile Java code to JavaScript and that's it. Simple. The JsInterop is a mapping only. Like type declarations (typings) for TypeScript. This modern JsInterop approach would be a recommended way for a new application (and minimal GWT version is 2.8 then).
Please also note that you may use J2CL instead of GWT compiller now. JsInterop is more or less the same for both (J2CL gives more possibilities and is a future solution). What GWT version does your project use?
Comment: So from your answer I'm guessing it is a legacy project created with the "old" GWT version and is using legacy approach. JsInterop will not do any magic if your application wasn't build using this solution. At the moment, probably the only way is to try with HTML Iframe and calling the Entry Point from your Wicket template.

How to Run GWT Application in Wicket?


is it possible to unload the relationship data of sqlalchemy objects once loaded?

Question: I am working in a library that needs to read several objects that have a one-to-many relationship with another class. The following code represents a highly simplified version of the code of my library:
class Plan(Base):
  __tablename__ = 'plan'
  id = Column(Integer, primary_key=True)
  name = Column(String)

  points = relationship('Point')

  def __init__(self,name):
    self.name = name

class Point(Base):
    __tablename__ = 'point'

    id          = Column(Integer, primary_key=True)
    coordinates = Column(String)
    plan_id     = Column(Integer,ForeignKey('plan.id'))

    def __init__(self, coordinates):
        self.coordinates = coordinates

I need to read all the data of the relationship (all the points for the example from above), conduct an operation with all the points, and continue with the next object (an object from the Plan class in the example). Since I cannot load all the data in memory because of the high number of points that each plan has, what I would like to do, is after completing the operation with the points objects related to a plan (which I do not need them after the operation), unload them and continue the process with the next plan. I have tried the following approaches:
plan.points = []

or
for point in plan.points:
  plan.points.remove(point)

But each of these approaches stacks an update or delete query  (depending on how the cascade attribute is set in the relationship) that implies a considerably overhead to the process, incrementing by 2 or 3 the total execution time and stacking a potentially harmful SQL operation if the session is committed.
Is there a way for unloading objects without the generation of these UPDATE/DELETE queries and  the increment of the execution time?
Answer: By default, your objects are only stored in the Session using weak references, meaning that you can simply delete your own references to the objects to clear them from memory.
That said, you are free to call Session.expunge_all() to remove any thing still held by the session. Don't call this if you have changes that need to be committed, issue a Session.flush() first.
You can expunge individual Point objects with the Session.expunge() method too.
See Using the Session for more details.
Comment: Thank you, I have tried it (expunge the involved objects first and then plan.points = []) and it works although I get a warning mentioning that the delete operation will not proceed so I do not know if this is the best method for carrying on this action.


CSS has no effect on dynamic classes

Question: $('fieldset.one label, fieldset.two label').each(function () {
    var className = $(this).text().trim().toLowerCase();
    $(this).addClass('default ' + className);
});

I'm adding classes dynamically to label elements, but when I try to style them, there is no effect. One of them has .sedan class added automatically, I see it in firebug, but the following doesn't have any effect:
.sedan {
  display:none !important;
}

HTML:
<fieldset class="one">
  sedan
  suv
  truck
</fieldset>

<fieldset class="two">
  sedan
  suv
  truck
</fieldset>

Comment: Please include the html being targeted.
Comment: That's not ``.  How about showing the actual HTML?
Answer: Use jQuery's trim method:
var className = $.trim($(this).text()).toLowerCase();

Comment: Not sure why this was down-voted, the original code supplied will only work in recent versions of Firefox that actually implement the Javascript 1.8.1 `String.trim()` method.
Comment: Ah, what was downvoted (by someone) is actually the solution! :)
Comment: Yes, but it was failing in Chrome (mac) and Firefox (mac)
Answer: There's nothing wrong with the code you've posted here. I just tested it locally and it works just fine. Make sure your selectors are correct - and you can check to see whether the styles are being added with firebug.
Comment: There's a space after "default", and jQuery splits on spaces. OP's code should add two different classes to each element.
Comment: OP's code *does* add two classes (given what was posted here).
Answer: Works for me: http://jsbin.com/amovo/edit

CSS has no effect on dynamic classes