Jquery loop through and get the form field values

Question: I have a form like below:

$('.form').submit(function(e) {

      e.preventDefault();
      $(this).find('.choices li').each(function() {
         var $thisChoice = $(this);
        var choiceLabel = $thisChoice.find('.choice-label').val();
           if( $thisChoice.find('textarea.sub_textarea'))
           {
                $thisChoice.find('textarea.sub_textarea').each(function() {
                    var subChoiceNotes=$(this).val();
                    //var subNotesReqChoice=$(this).next('input.requiredNotes[type=checkbox]').val();
                    var subNotesReqChoice=$(this).next('input.requiredNotes[type=checkbox]:checked').val();
                    alert('NoteLabel:'+subChoiceNotes+'&reqNote:'+subNotesReqChoice);
                });
          }

    });

});
<form class="form">

Add Choice: <input type="text" value="Choice1" class="choice-label">

          <textarea  name="choice_notes" class="sub_textarea" >note1</textarea>
          <input type="checkbox" class="requiredNotes" value="1"  checked>Required?

          <textarea style="display:inline-block; vertical-align:middle;" name="choice_notes" class="sub_textarea" >note2</textarea>
          <input type="checkbox" class="requiredNotes" value="0">Required?

Add Choice: <input type="text" value="Choice2" class="choice-label">

          <textarea name="choice_notes" class="sub_textarea" >note3</textarea>
          <input type="checkbox" class="requiredNotes" value="1" checked>Required?

          <textarea name="choice_notes" class="sub_textarea" >note4</textarea>
          <input type="checkbox" class="requiredNotes" value="0">Required?

            <textarea  name="choice_notes" class="sub_textarea" >note5</textarea>
          <input type="checkbox" class="requiredNotes" value="1" checked>Required?

     <input type='submit' class='update' value='submit' />

</form>

<form class="form">

Add Choice: <input type="text" value="Choice1" class="choice-label">

          <textarea  name="choice_notes" class="sub_textarea" >note1</textarea>
          <input type="checkbox" class="requiredNotes" value="1"  checked>Required?

          <textarea style="display:inline-block; vertical-align:middle;" name="choice_notes" class="sub_textarea" >note2</textarea>
          <input type="checkbox" class="requiredNotes" value="0">Required?

Add Choice: <input type="text" value="Choice2" class="choice-label">

          <textarea name="choice_notes" class="sub_textarea" >note3</textarea>
          <input type="checkbox" class="requiredNotes" value="1" checked>Required?

          <textarea name="choice_notes" class="sub_textarea" >note4</textarea>
           <input type="checkbox" class="requiredNotes" value="0">Required?

            <textarea  name="choice_notes" class="sub_textarea" >note5</textarea>
          <input type="checkbox" class="requiredNotes" value="1" checked>Required?

     <input type='submit' class='update' value='submit' />

</form>

When the form submits, I want to loop through all the choices in the li tag and store the values in a variable.
I am getting the text area values when loop through the li tag. I want to get the value of checkbox with the  text area values. The checkbox value should be the value of checkbox near the text area.
Any help would be appreciated!
Answer: Add name attributes to your checkboxes and then use var subNotesReqChoice=$(this).next('input.requiredNotes[type=checkbox]').val(); to get the checkboxes regardless of them been selected or not.

$('.form').submit(function(e) {

      e.preventDefault();
      $(this).find('.choices li').each(function() {
         var $thisChoice = $(this);
        var choiceLabel = $thisChoice.find('.choice-label').val();
            alert('FOR CHOICE:'+choiceLabel);
           if( $thisChoice.find('textarea.sub_textarea'))
           {
                $thisChoice.find('textarea.sub_textarea').each(function() {
                    var subChoiceNotes=$(this).val();
                    var subNotesReqChoice=$(this).next('input.requiredNotes[type=checkbox]').val();
                    alert('NoteLabel:'+subChoiceNotes+'&reqNote:'+subNotesReqChoice);
                });
          }

    });

});
<form class="form">

Add Choice: <input type="text" value="Choice1" class="choice-label">

          <textarea  name="choice_notes" class="sub_textarea" >note1</textarea>
          <input type="checkbox" name="requiredNotes" class="requiredNotes" value="1"  checked>Required?

          <textarea style="display:inline-block; vertical-align:middle;" name="choice_notes" class="sub_textarea" >note2</textarea>
          <input type="checkbox" name="requiredNotes" class="requiredNotes" value="0">Required?

Add Choice: <input type="text" value="Choice2" class="choice-label">

          <textarea name="choice_notes" class="sub_textarea" >note3</textarea>
          <input type="checkbox" name="requiredNotes" class="requiredNotes" value="1" checked>Required?

          <textarea name="choice_notes" class="sub_textarea" >note4</textarea>
          <input type="checkbox" name="requiredNotes" class="requiredNotes" value="0">Required?

            <textarea  name="choice_notes" class="sub_textarea" >note5</textarea>
          <input type="checkbox" name="requiredNotes" class="requiredNotes" value="1" checked>Required?

     <input type='submit' class='update' value='submit' />

</form>

<form class="form">

Add Choice: <input type="text" value="Choice1" class="choice-label">

          <textarea  name="choice_notes" class="sub_textarea" >note1</textarea>
          <input type="checkbox" name="requiredNotes" class="requiredNotes" value="1"  checked>Required?

          <textarea name="choice_notes" class="sub_textarea" >note2</textarea>
          <input type="checkbox" name="requiredNotes" class="requiredNotes" value="0">Required?

Add Choice: <input type="text" value="Choice2" class="choice-label">

          <textarea name="choice_notes" class="sub_textarea" >note3</textarea>
          <input type="checkbox" name="requiredNotes" class="requiredNotes" value="1" checked>Required?

          <textarea name="choice_notes" class="sub_textarea" >note4</textarea>
          <input type="checkbox" name="requiredNotes" class="requiredNotes" value="0">Required?

            <textarea  name="choice_notes" class="sub_textarea" >note5</textarea>
          <input type="checkbox" name="requiredNotes" class="requiredNotes" value="1" checked>Required?

     <input type='submit' class='update' value='submit' />

</form>
Comment: Thank you for the answer. I have Required?. So that I am getting undefined value after using next()
Comment: Required? should give you value 1 since it was checked. Do you want to get the value of the unchecked checkboxes also? See var subNotesReqChoice=$(this).next('input.requiredNotes[type=checkbox]:checked').val();
Comment: Could you please check my code in the question? I am getting undefined after using next()
Comment: yes because you still have it as ```var subNotesReqChoice=$(this).next('input.requiredNotes[type=checkbox]').val();``` instead of ```var subNotesReqChoice=$(this).next('input.requiredNotes[type=checkbox]:checked').val();```
Comment: I have updated the code, but still get the undefined value for checkbox
Comment: I did something like .next('label').find('input.requiredNotes[type=checkbox]') and it works now. Thank you for the help
Comment: Sorry @Zendie, network went off. That's fine. You could as well add name attributes to the checkboxes like i did in the edited code and it'll work also


Limit of an integral.

Question: $$\lim_{n\to\infty}   \int_{-\infty}^{\infty} \frac{1}{(1+x^2)^n}\,dx $$
Mathematica tells me the answer is 0, but how can I go about actually proving it mathematically?
Comment: Have you learned [dominated convergence theorem](http://en.wikipedia.org/wiki/Dominated_convergence_theorem)?
Answer: Simply use this inequality
$$0\leq\int_0^\infty\frac{1}{(1+x^2)^n}\,dx\leq \int_0^\infty\frac{1}{1+nx^2}\,dx=\frac{1}{\sqrt{n}}\int_0^\infty\frac{dt}{1+t^2}=\frac{\pi}{2\sqrt{n}}$$
Comment: I like [Bernoulli's Inequality](http://en.wikipedia.org/wiki/Bernoulli%27s_inequality); it is very simple, but quite useful. (+1)
Answer: Hint: Apply Dominated Convergence.

Dominated Convergence: Suppose $|f_n(x)|\le g(x)$ where $f_n$ is measurable and $g(x)$ is a non-negative integrable function. If $\lim\limits_{n\to\infty}f_n(x)=f(x)$ ($f$ is the pointwise limit of $f_n\,$), then
  $$
\lim_{n\to\infty}\int f_n\,\mathrm{d}x=\int f\,\mathrm{d}x
$$
Answer: You can also compute $\displaystyle \int_{-\infty}^{\infty}\dfrac{dx}{(1+x^2)^n}$ exactly and argue out what the limit is.
Let $x = \tan(t)$. We then get that
$$I_n = \int_{-\infty}^{\infty}\dfrac{dx}{(1+x^2)^n} = \int_{-\pi/2}^{\pi/2} \dfrac{\sec^2(t) dt}{\sec^{2n}(t)} = \int_{-\pi/2}^{\pi/2} \cos^{2n-2}(t) dt = \pi \times \prod_{k=1}^{n-1} \left(1-\dfrac1{2k}\right)$$
Now we have
$$\sum_{k=1}^{\infty} \dfrac1{2k}$$ diverges and hence from here, we have $I_n$ ...
Answer: Use integration by substitution. Let $x=\tan\theta$. Then
$$ \int_{-\infty}^\infty\frac{1}{(1+x^2)^n}dx=\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\cos^{2(n-1)}\theta d\theta. $$
Now it is not hard to verify
$$\lim_{n\to\infty}\int_{-\frac{\pi}{2}}^{\frac{\pi}{2}}\cos^{2(n-1)}\theta d\theta=0.$$
Comment: $25$ seconds before you :)

Limit of an integral.


create app ShortCut on home screen when it installed and open last screen of it

Question: i am trying to create ShortCut when app installed . i am using following code
Intent shortcutintent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
    shortcutintent.putExtra("duplicate", false);
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.iconname));
    Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.appicon);
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
    shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext(), DashActivity.class));
    sendBroadcast(shortcutintent);enter code here

but in this it always open DashActivity . let say i am using app and app is in c Activity and its running in bacgkground  now when i click on shortcut it is opening DashActivity not the opening which where active ie c
Answer: The correct way is to listen for a shortcut request from the home screen-- with an intent filter like so in your manifest:
<activity android:name=".ShortCutActivity" android:label="@string/shortcut_label">
  <intent-filter>
    <action android:name="android.intent.action.CREATE_SHORTCUT" />
    <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
</activity>

Then in the activity that receives the intent, you create an intent for your shortcut and return it as the activity result.
// create shortcut if requested
ShortcutIconResource icon =
    Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);

Intent intent = new Intent();

Intent launchIntent = new Intent(this,ActivityToLaunch.class);

intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, someNickname());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

setResult(RESULT_OK, intent);

Answer: it is opening DashActivity becoz in this line it is provided to open this.
 shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext(), DashActivity.class));
change the name of this Activity with your own Activity which u want to open.
hope this Helps.
Comment: i want it should open last act
Comment: get current activity by Following code.                                                                        **Activity  currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity():**                           then pass this current activity instead of DashActivity.                                       Hope this Slove your problem
Answer: From shortcutintent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext(), DashActivity.class));
 remove the DashActivity.class and provide your applications launcher activity name...so that it will work as you expected.
Comment: DashActivity is launcher activity , android:launchMode="singleTask"
Comment: Remove the launch mode from the activity...It will works
Comment: but i cant other way ?
Comment: What you mean by "i cant other way ?"?
Comment: sorry i mean i cant remove mode as its using for different purpose . any alternative for this?


Difference between google_project_iam_binding and google_project_iam_member

Question: Hi terraform mates out there
I want to automate the role assignments process for service accounts and users on the Google Cloud Platform. I am actually thinking of creating IAM custom roles to get fine-grained roles terraform resources for different services, and assign that role to the users or service account I want to.
Checking the way to associate which members will get what roles, I am actually wondering what is the difference between use  google_project_iam_binding and use google_project_iam_member resources.
My current understanding could fall on in using google_project_iam_binding to grant roles to service accounts and google_project_iam_member to user accounts, but I am not sure since in the documentation they use both to associate user accounts.
I also found this interesting article https://binx.io/nl/2021/12/16/how-to-name-your-google-project-iam-resources-in-terraform/

As you know, Google IAM resources in Terraform come in three flavors:

google_project_iam_policy to define a complete policy for the project.
google_project_iam_binding to define all the members of a single role.
google_project_iam_member to define a single role binding for a single principal.

I didn't know the previous sentence and I would like to deep dive in the way I can use policies, and IAM roles in a better way for my purpose.
Answer: As the documentation states:

google_project_iam_binding: Authoritative for a given role. Updates the IAM policy to grant a role to a list of members. Other
roles within the IAM policy for the project are preserved.
google_project_iam_member: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for
the project are preserved.

This means that google_project_iam_binding will grant a role to a list of members, and revokes it from any other member.
So if your project had two users e.g: firstname.lastname@example.com and firstname.lastname@example.com who both have roles/editor on the project. Running the following Terraform snippet will revoke roles/editor from firstname.lastname@example.com as it's not present in the member list of google_project_iam_binding
resource "google_project_iam_binding" "project" {
  project = "your-project-id"
  role    = "roles/editor"

  members = [
    "user:email@example.com",
  ]
}

However, if you have for example email@example.com and firstname.lastname@example.com who both have roles/editor on the project. If you want to add a new editor (firstname.lastname@example.com) without affecting the other roles/users, you can use google_project_iam_member
resource "google_project_iam_member" "project" {
  project = "your-project-id"
  role    = "roles/editor"
  member  = "user:firstname.lastname@example.com"
}

Notes from the documentation:

google_project_iam_policy cannot be used in conjunction with
google_project_iam_binding, google_project_iam_member, or
google_project_iam_audit_config or they will fight over what your
policy should be.

google_project_iam_binding resources can be used in conjunction with
google_project_iam_member resources only if they do not grant
privilege to the same role.

See:

Terraform google_project_iam_binding deletes GCP compute engine default service account from IAM principals
https://discuss.hashicorp.com/t/difference-between-google-project-iam-binding-and-google-project-iam-member/49645/2
https://github.com/hashicorp/terraform-provider-google/issues/8354
Comment: no, `iam_binding` will grant a role to a list of member, and **revokes** it from any other member. And `iam_member` adds one, or a list of members: https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/google_project_iam.html#member/members
Comment: Wow!  Your explanation is so much better than the documentation.  Thanks! :)
Comment: So is the conclusion here iam_member means adding just one person and iam_binding means adding a list of people?


What would a 5 point 2nd order central finite difference formula look like?

Question: I am aware of the usual 2nd order central difference formula that uses 3 points with error $O(h^2)$
$$ \frac{u_{j-1}-2u_j + u_{j+1}}{h^2}$$
But what would a 5 point central difference formula look like and what would its error term be?
Answer: Take a look at https://math.stackexchange.com/a/2064829/331661
They use (up to second order)$$\begin{align}u_{j-1}&=u_j-u'_j h+\frac 12 u''_j h^2\\u_{j+1}&=u_j+u'_j h+\frac 12 u''_j h^2\end{align}$$
We can write the next positions, $j-2$ and $j+2$ as $$\begin{align}u_{j-2}&=u_j-u'_j (2h)+\frac 12 u''_j (2h)^2\\u_{j+2}&=u_j+u'_j (2h)+\frac 12 u''_j (2h)^2\end{align}$$
If you add all these equations together you get $$u_{j-2}+u_{j-1}+u_{j+1}+u_{j+2}=4u_j+\frac 12 u''_jh^2(2^2+1^2+1^2+2^2)=4u_j+5u''_jh^2$$
I can then get $$u''_j=\frac{u_{j-2}+u_{j-1}-4u_j+u_{j+1}+u_{j+2}}{5h^2}$$


IIS6 SMTP server retrying too fast (after 451 greylist)

Question: I have my IIS6 SMTP server with default retry settings of 15 min, 30 min, etc. but under some circumstances it keeps retrying every minute (or less).  How can I fix this?
I have seen it retry correctly (15 mins) after a
451+Temporary+Policy+Rejection+-+Please+try+later 0

But it looks like these puppies cause the problem:
2013-03-12 22:17:19 - - 451+Greylisted,+please+try+again+in+300+seconds 0

I did read somewhere that too-fast retries can be caused by DNS problems on the receiving end.
Excerpt from logs:
2013-03-12 22:17:19 RCPT - TO:<firstname.lastname@example.com> 0
2013-03-12 22:17:19 - - 451+Greylisted,+please+try+again+in+300+seconds 0
...
2013-03-12 22:18:20 RCPT - TO:<firstname.lastname@example.com> 0
2013-03-12 22:18:20 - - 451+Greylisted,+please+try+again+in+239+seconds 0
...
2013-03-12 22:18:47 RCPT - TO:<email@example.com> 0
2013-03-12 22:18:47 - - 451+Greylisted,+please+try+again+in+211+seconds 0
...
2013-03-12 22:19:49 RCPT - TO:<firstname.lastname@example.com> 0
2013-03-12 22:19:49 - - 451+Greylisted,+please+try+again+in+150+seconds 0

Comment: Are there multiple emails being sent to that address?
Comment: @MichaelHampton - That would be my question as well. If these are seperate messages the retry interval is per message and would explain what the OP is seeing.
Comment: If somebody put their email into a web site and didn't get their confirmation right away, they might have tried again or hit the resend button. They might not even know they're impacted by greylisting, which is one reason why [I don't recommend use of greylisting](http://serverfault.com/a/419475/126632).
Answer: I may be giving a answer you don't want, but IIS SMTP is very simple and limited... you may be hitting a bug. I would smarthost all emails to a more complete SMTP server, like postfix or qmail (both linux based), where they are queued to deliver to the internet. The IIS SMTP would be used as a simple localhost relay, bypassing most of it problems.
As the your problem... are you sure that they are the same email? maybe there are several emails outgoing to the same email and generating that apparent bad retry pattern.
Either way, that 300s in the logs is just a user level comment, the SMTP will not read it, nor try to obey to it. Also, the receiving end have no influence whatever on the retry time of the sender, only the response code (451 in this case) can trigger different reactions on the sender side... but that reaction would be consistent always.


Local uniqueness of Cauchy Problem, but can it split into branches?

Question: The problem I've been struggling is exemplified here:
Is local Lipschitz continuity sufficient for an ODE to have a unique solution?
The problem that they solve is
\begin{align*}
x'(t) = x^2,\quad x(0) = x_0
\end{align*}
which in the other thread is said to have a unique solution given by
\begin{align*}
x(t) = \frac{1}{x_0^{-1}-t}.
\end{align*}
This function is not continuous at $t = x_0^{-1}$ bu they claim in the other thread that it is unique in $(-\infty,x_0^{-1})$, supposing $x_0>0$. Since $f(x,t) = x^2$ the function is only locally Lipschitz and therefore we are only guaranteed a unique solution locally? How can one in general be sure that it does not split into separate branches outside of some small interval?
Answer: Local uniqueness already garantuees uniqueness on the whole intervall of existence. Let me give a short proof:
Let $u_1$ and $u_2$ solve the same initial value problem. Let us also assume there exists a $t\in\mathbb{R}$ such that for every $\varepsilon>0$ we find an $\tilde{t}\in(t,t+\varepsilon)$ such that $u_1(\tilde{t})\neq u_2(\tilde{t})$ and $u_1(t)=u_2(t)$. This means $u_1$ and $u_2$ are equal up to $t$, but after that $t$, they may differ. Local uniqueness now gives us a small open neighborhood of $t$ in which $u_1$ equals $u_2$. Hence we find an $\tilde{\varepsilon}>0$ such that for every $x\in(t,t+\tilde{\varepsilon})$ we have $u_1(x)=u_2(x)$. If you choose you $\varepsilon$ now to be smaller than $\tilde{\varepsilon}$ you obtain a contradiction.
Your example is also unique up to the point of existence. Please note, that your $x(t)$ tends to $\infty$ if $t\uparrow x_0$. Hence your solution cannot be extended further and therefore it cannot branch. (See also https://en.wikipedia.org/wiki/Ordinary_differential_equation#Global_uniqueness_and_maximum_domain_of_solution)
Comment: Ok I understand your reasoning, but don't we need equality on a closed set? Altough I guess that this also follows since if $u_1(t) = u_2(t)$ on $(a,b)$ then due to continuity $u_1(b) = u_2(b)$. Thank you very much for your help.


how to perform Post request in robot framework(requests library) with nested(complex) JSON (JSON example provided below)

Question: Need to send this json through POST to a service,but don't know how to create it in Robot Framework:
{
      "id": "123456",
      "contactinfo": [
        {
            "contactid": "email@example.com,",
            "typeOfcontact": "email"
        },
        {
            "contactid": "123543523Y",
            "typeOfcontact": "Phonenumber"
        }
      ],
      "subscriptionid":"132456"
    }

The following is my work:
*** Settings ***

Library    RequestsLibrary
Library    JSONLibrary

*** Variables ***
${Base_URL}    http://example.com
** Test Cases ***

MyFirstTest
   Create Session    Update_Subscription    ${Base_URL}
   ${headers}=    Create Dictionary    Content-Type    application/json    Authorization    Token 1w121
   &{data}=    Create Dictionary    driverId=AZL123456    subscriptionId=SBS132456
  ${response}=  Post Request    Update_Subscription      ocpi/api/v1/user-enrollment/update-subscription    headers=${headers}   json=${data}

   ${json_response}=  Convert To String    ${response.status_code}

   Log To Console    ${response.content}
   Should Be Equal    ${json_response}    200

Comment: Please show your work
Comment: Hi @Ruturaj, I have edited my description with my work, I wanted to know what is the format to input nested json similar to how i have created dictionary with simple json( &{data}=    Create Dictionary    driverId=AZL123456    subscriptionId=SBS132456). Appreciate your help!
Answer: contactinfo is a list of dictionaries, so you just need to create this structure, and add it to the data dictionary:
${entry 1}=    Create Dictionary    contactid    email@example.com
${entry 2}=    Create Dictionary    123543523Y
 Phonenumber
${contactinfo}=    Create List     ${entry 1}    ${entry 2}
&{data}=    Create Dictionary    driverId=AZL123456    subscriptionId=SBS132456    contactinfo=${contactinfo}

Comment: Thank you, your solution seems to work @Todor


Disjunction of conjunction in linear programming

Question: I'm trying to get my model working with less variable/constraints possible. I want the binary variable $R$ to store the result of this Boolean expression:
R = (a1 and b1) or (a2 and b2) or (a3 and b3) ... or (aN and bN)
I'm perfectly aware of the solution which consists in having $N$ helpers binary variables, each of one store the result of one and.
$ c_k \leq (a_k+b_k) / 2    \quad k = 0,\ldots,N$
and then maximize the value of $R$ subject to the constraint
$R \leq \sum_{k=1}^N c_k$
This approach introduces $N$ extra variables and $N$ extra constraints. Does exist any better solution in terms of number of variables/constraints? If not, anyone could help me to understand why?
I'm writing the model in AMPL, but I believe that this problem is not language dependent. Thank you very much!
Answer: I think that in a more general setting, i.e. in which you want your variables/constraints to be part of a more complex model, your approach is limiting. So you can start with
$$ (a_k + b_k)-1 \leq R \quad \forall k=1,\ldots,N$$
that force $R$ to be one if any of the clauses are true. Then you need to force $R$ to zero when all are false. You cannot reduce the number of variables because you must model two different things: the OR and the AND. They are basically independent.I would avoid playing with rounding. You first model the OR
$$R\leq \sum_{k=1}^N c_k$$
and then you define what is $c_k$:
$$ 2c_k \leq a_k+b_k \quad \forall k=1,\ldots,N$$
you cannot do much better without loosing information. Note also that $c_k$ does not actually model AND: if two clauses are true, say $i,j$, $R$ is $1$ but only one among $i,j$ is required to be one itself. For instance $c_i=0,c_j=1$ is feasible for $R=1$ and $a_i=a_j=b_j=b_i=1$.
Answer: A tighter formulation is
\begin{align}
R &\ge a_k+b_k-1 &\text{for all $k$}\\
R &\le \sum_k c_k\\
c_k &\le a_k&\text{for all $k$}\\
c_k &\le b_k&\text{for all $k$}
\end{align}
You can alternatively get by with only the original $2N+1$ variables at the expense of an exponential number ($2^N+N$) of constraints:
\begin{align}
R &\ge a_k+b_k-1 &\text{for all $k$}\\
R &\le \sum_k \left\{{a_k \atop b_k}\right\}
\end{align}
where $\left\{{a_k \atop b_k}\right\}$ means that either $a_k$ or $b_k$ appears.  For example, if $N=5$, one of these constraints is
$$R \le a_1 + a_2 + b_3 + a_4 + b_5$$


My regex does not remove the dash between numbers in java

Question: I have tried to use regex in JAVA for replacing any funny character in a string for mobile numbers, however, it doesnt seems to be able to remove the '-' between the numbers
here is my code,
// Remove all (,),-,.,[,],<,>,{,} from string

myMobileNumber.replaceAll("[^\\d]", "");

example 65-12345678
it will still allows the - to go through without deleting it away. =(
Answer: You should reassign the result. A String is an immutable object, and all methods including .replaceAll won't modify it.
myMobileNumber = myMobileNumber.replaceAll("[^\\d]", "");

(BTW, the pattern "\\D" is equivalent to "[^\\d]".)


Limitar quantidade de páginas em paginação PHP MYSQL

Question: Tenho uma paginação em PHP e MYSQLI, e gostaria de que os link das páginas em baixo fosse limitado, por exemplo:
Paginas: 1 2 3 4 5 (vai até 100), apareça somente as primeira 5, se eu tiver na página 10, me mostra 8 9 10 11 12, não sei se me entenderam, mas o que me acontece é que tenho bastante itens adiconados no banco e o que acontece é que aparece mais de 200 paginas, e eu quero que mostra os links de pelo menos 5. Segue o código:
<?php
            $pagina = (isset($_GET['pagina']))? $_GET['pagina'] : 1;

            $banco = mysqli_query($conecta, "SELECT * FROM produtos WHERE empresa='1' AND ativo='1'");

            $total = mysqli_num_rows($banco);

            $registros = 10;

            $numPaginas = ceil($total/$registros);

            $inicio = ($registros*$pagina)-$registros;

            $banco = mysqli_query($conecta, "SELECT * FROM produtos WHERE empresa='1' AND ativo='1' LIMIT $inicio,$registros");
            $total = mysqli_num_rows($banco);

            while($exibe_pecas = mysqli_fetch_array($banco)) {
        ?>

<?php echo $exibe_pecas['codigo']; ?>

<?php echo $exibe_pecas['nome']; ?>

<?php echo $exibe_pecas['qtde_estoque']; ?>

R$ <?php echo $exibe_pecas['prc_venda']; ?>

#

        <?php } ?>
        <?php
            if($pagina > 1) {
                echo "« anterior";
            }

            for($i = 1; $i < $numPaginas; $i++) {
                $ativo = ($i == $pagina) ? 'numativo' : '';
                echo " ".$i." ";
            }

            if($pagina < $numPaginas) {
                echo "proximo »";
            }
        ?>

Answer: Você precisa limitar isso no for:
$margemDireita = 2;
$margemEsquerda = ($pagina > 2) ? 2 : 0;

for ($i = $pagina - $margemEsquerda; $i < $pagina + $margemDireita; $i++) {
   $ativo = ($i == $pagina) ? 'numativo' : '';
   echo " ".$i." ";
}

Entendendo a lógica: Foram criadas variáveis para setar quantas páginas pra esquerdas, e quantas pra direita. Então o for se limita a começar o $i a 2 números antes da página atual, e finalizar o for 2 números depois da página atual.
Ex: página atual é 5, o for iniciaria em 3 (5-2=3) e acabaria em 7 (5+2=7), resultado: 3 4 5 6 7


Paired test for comparing boolean data

Question: I have $n$ individuals, and for each individual, I have two measurements using two devices (device X and device Y).  I know the ground truth for the correct measurement, and I can classify each measurement as accurate or inaccurate.  Thus, for each individual I effectively have a boolean value that indicates whether device X was correct or not (say $x_i$) and a boolean value that indicates whether device Y was correct or not (say $y_i$).
Is there a good statistical test to use to compare the accuracy rate of the two devices?
In particular, suppose I notice that device X's accuracy rate appears to be higher than device Y's accuracy rate, based upon the $n$ observations (i.e., $(x_1+\dots+x_n)/n > (y_1+\dots+y_n)/n$, where $x_i,y_i = 1$ means it was correct and $0$ means it was incorrect).  Now I'd like to test whether the difference in observed accuracy rate is statistically significant.  Can I compute a $p$-value for the null hypothesis that their underlying accuracy rate is actually the same?
Should I use the Wilcoxon signed-rank test?  A paired Student's t-test?  Some sort of paired Welch t-test (does such a thing even exist)?  None of those seems like an obvious fit to me: I know the data isn't normally distributed (it presumably has a Bernoulli distribution), so a t-test isn't perfect (on the other hand I've read that in practice the t-test is fairly robust to deviations from normality so maybe it is OK?); and I can't tell whether a Wilcoxon signed-rank test takes into account the prior knowledge that the data is Bernoulli distributed.  Anyway, what would be the most appropriate methodology?
Comment: Sounds like you probably want [McNemar's test](http://en.wikipedia.org/wiki/McNemar%27s_test)
Comment: see also [here](http://stats.stackexchange.com/questions/73576/paired-t-test-for-binary-data?rq=1)
Answer: McNemar's test solves this problem.  (Thanks to Glen_b for mentioning this!)  It is intended for paired data, where the observations are boolean -- a perfect fit.  It is also easy to compute, which is convenient.
See also Paired t-test for binary data for another instance of a closely related statistical hypothesis testing problem.

Paired test for comparing boolean data


what is the appropriate one-class classifier for sequenced categorical data?

Question: Can someone suggest an algorithm for an outlier detection system?
My requirements are:

it supposed to be a one class classifier, where on training phase,
it only fed 'normal' data
however the normal class can have multiple sub-class. (we can see it
as multi-class classification with an 'other' class, where this
'other' class is never learned)
all features are categorical
features have sequence relation, so I need it analysed in sequence.
I need a lighter algorithm for real time application
optionally - I need an on-line learning capability

I have tried HMM. However it still very heavy to my liking. Furthermore it required me to create different model for each sub-normal-class.
Next I tried one-class-svm (with one hot encoder). It was light enough. However results was incorrect. I'm guessing it was because this approach is not appropriate for sequence analysis?
Now I am in the middle of Neural Network trial. I read that Autoencoder is an approach for one-class-classification. My results so far is not satisfying in term of learning time and detection results.
Can someone suggest a better (machine learning algorithm) approach?
Answer: A solution could be to determine a set of representative sequences (using for instance the TraMineR R package). Outliers would then be sequences that lie at more than a given threshold distance from any representative. See Gabadinho and Ritschard (2013) for details on representative sequences and Studer and Ritschard (2016) for a discussion on the distances that could be used.
An alternative is to fit probabilistic suffix trees on the sequences with the PST R package, and then to consider the likelihood of the additional sequences for the fitted tree. Unlikely sequences would be outliers.
Hope this helps.


How is the memory allocated when I declare a pointer of a structure in C

Question: I want to know how the memory is allocated when I'm using a pointer to declare my structure.
struct car{
    int id;
    int age;
};

So if I'm right, for most the compilers, the structure size is 8 bytes because int(4B) x 2 = 8B.
Now the point I don't understand.
//1
struct car *ptr = malloc(sizeof(struct car));
//2
char buffer[4090];
struct car *ptr = buffer;
//3
struct car *ptr = malloc(1);

In these 3 cases the size of the *ptr is 8 sizeof(*ptr). Why?
And how is it represented in the memory?
Comment: To me it seems like you sizeof a pointer in all `sizeof`'s, which will obviously always have the same size on the same system.
Comment: Thank you for your answer, yes you'r right it's 8B each time, but i don't understand how memory allocation works. I mean how it is represented.
Comment: Try `sizeof(struct car)` and after that add another int to the struct and rerun the program. also don't remove the `sizeof(*ptr)` while doing this, it should show different results.
Comment: case 2 is constraint violation (compiler must report a problem)
Answer: sizeof(something) is nothing represented in memory. It is determined at compile time.
Since ptr is declared as a car*, sizeof(*ptr) is for the compiler the size of the car structure.
This does not depend on the value of ptr or where it is pointing at, even if it is null.
On the other hand, sizeof(ptr) (without the star) is the size of a pointer, which depends on the system (i.e. 8 Bytes on a Win 64-bit). In this case, the type of the pointee does not matter.
Comment: @MeikVtune read this please in the OP: "In these 3 cases the size of the *ptr is 8, WHY?". I think you will then see that the answer is pertinent, especially to that big "WHY".
Comment: @MeikVtune try it with some big structure, you will see.
Comment: @MeikVtune `sizeof(*anything)` will certainly not always output 8, unless `anything` is a pointer to a datatype 8 bytes long. `char * anything; printf("%zu\n", sizeof(*anything));` will output `1`, for example. In any case, there's nothing that requires all pointers to be the same size.
Comment: His `sizeof` is the size of a pointer, it doesn't matter what the pointer points to, so it has nothing to do with his struct. the mere point is that he asks for the size of a pointer.
Comment: `sizeof(*a)` will always output the size of a pointer, which depends on the system. `sizeof(struct car)` in this example would also output 8, since an int will output 4. that still does not change that a pointer is 8. if he was to put in a 3rd int, `sizeof(struct car)` should output 16.
Comment: I did try it. `sizeof(*anything)` will always output 8, while a struct with 3 ints, where `sizeof(struct anything)` outputs 24. Go and try it yourself if you just keep saying you are right.
Comment: Can't edit my previous comment, a struct with 3 int's will output 12, not 24. My example struct was a pointer and 3 int's.
Answer: The type of the expression *ptr is struct car, which is 8 by your own reckoning.
As to why all three cases say the size is 8 for the sizeof(*ptr): in all three cases, C thinks of your ptr variable as a pointer to a car struct, declared so by you. So it cannot treat those 3 different ptr variables differently, and neither will it treat *ptr differently. It does not matter whether it's a single car item (1 case), or one of many in an array (2nd case), or indeed a completely broken bit of one byte long memory which is not even full car struct (3rd case).
C trusts the programmer to make sure that whatever is pointed at is actually there.
Comment: I did. In the question `ptr` is not a type, but a variable. So the type of epxression `*ptr` is `car`. And if you mean by 'where a is anything' that 'a is any type' then please consider that `sizeof(*a)` is not even correct syntax. `sizeof(a*)` is and that would indeed mean a pointer type, but I don't see how that was relevant to the question.
Comment: Please try `sizeof(int)` and `sizeof(*a)` where a is anything.
Comment: Ok thank you all for your answers. So if I understand there is no way to check the size of the allocated memory.


Passing query parameters to LiveData/Viewmodel in Android app

Question: Since I'm new to programming Android apps I followed a tutorial on how to use the Android Architecture Components and Firebase for implementing the MVVM (using LiveData, ViewModel, etc.).
The tutorial I followed can be found here:

Part 1
Part 2
Part 3

I'm now left with what I think is a decent implementation of the MVVM, but I can not wrap my head around how I am supposed to pass query parameters to it. Right now I need to hardcode the ID of the document I want to retrieve:
public class AlarmDAO {

    private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();

    public AlarmLiveData getFirestoreLiveData() {
        DocumentReference documentReference = firebaseFirestore.collection(Collection.ALARMS.name).document("5RxJNuNyhDJlz49wpBkw");

        return new AlarmLiveData(documentReference);
    }

}

That then gets called by a class extending ViewModel.
public class AlarmViewModel extends ViewModel {

    private AlarmDAO DAO = new AlarmDAO();
    private AlarmLiveData liveData = null;

    public LiveData<Alarm> getAlarmLiveData() {
        liveData = DAO.getFirestoreLiveData();
        return liveData;
    }

    public LiveData<Alarm> getAlarm() {
        return liveData.alarm;
    }

}

And then I observe that data in my activity:
model.getAlarmLiveData().observe(this, Observable -> {});
model.getAlarm().observe(this, alarm -> {
   if (alarm != null) {
      alarmTextView.setText(alarm.getTest());
   else {
      Log.d(TAG, "Waiting for data");
   }
});

My problem is that I do not see a way of querying for a specific alarm. For instance model.getAlarm("someId"). I am under the impression that it should be done in the DAO and/or the ViewModel, but I can't figure out how. Another thing I do not understand is why I need to observe both model.getAlarmLiveData() and model.getAlarm() in my activity, as using only one does not work. The answer to both of those questions is most likely very simple, but thus far I haven't been able to figure it out.
For completeness: the Alarm class is nothing besides a getter and setter for two strings, and the AlarmLiveData class is below.
public class AlarmLiveData extends LiveData<Alarm> implements EventListener<DocumentSnapshot> {

    private static final String TAG = AlarmLiveData.class.getSimpleName();

    private Alarm alarmTemp = new Alarm();
    private DocumentReference documentReference;
    private ListenerRegistration listenerRegistration = () -> {};

    public MutableLiveData<Alarm> alarm = new MutableLiveData<>();

    public AlarmLiveData(DocumentReference documentReference) {
        this.documentReference = documentReference;
    }

    @Override
    protected void onActive() {
        listenerRegistration = documentReference.addSnapshotListener(this);
        super.onActive();
    }

    @Override
    protected void onInactive() {
        listenerRegistration.remove();
        super.onInactive();
    }

    @Override
    public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
        if (documentSnapshot != null && documentSnapshot.exists()) {
            alarmTemp = new Alarm();
            alarmTemp.setId(documentSnapshot.getId());
            alarmTemp.setTest(documentSnapshot.get("test").toString());
            alarm.setValue(alarmTemp);
        } else {
            Log.d(TAG, "ERROR");
        }
    }
}

Thank you for reading, I'm looking forward to the answer(s)!
Answer: The reason you have to use both model.getAlarmLiveData() and model.getAlarm() looks to be that your AlarmLiveData class extends LiveData but sets a value for the contained MutableLiveData member variable instead of setting its own class value.
Inside your AlarmLiveData class:
// Comment out/Remove your 'public MutableLiveData<alarm> alarm' member variable from the top.
// You're going to want to set the value of the AlarmLiveData class itself instead.

// ...

// Then inside of your onEvent callback
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
    if (documentSnapshot != null && documentSnapshot.exists()) {
        alarmTemp = new Alarm();
        alarmTemp.setId(documentSnapshot.getId());
        alarmTemp.setTest(documentSnapshot.get("test").toString());

        // Set the value for the AlarmLiveData class directly
        setValue(alarmTemp);
    } else {
        Log.d(TAG, "ERROR");
    }
}

I'm not sure why you're creating a DAO class and I would most likely move that code directly into the AlarmViewModel class.
But, here is how you can alter your current DAO class if you don't want to remove it:
// Pass in the document id you want to create a document reference for
public AlarmLiveData getFirestoreLiveData(String documentId) {
    DocumentReference documentReference = firebaseFirestore.collection(Collection.ALARMS.name).document(documentId);

    return new AlarmLiveData(documentReference);
}

Your AlarmViewModel class would look something like this:
public class AlarmViewModel extends ViewModel {

    private AlarmDAO DAO = new AlarmDAO();
    private AlarmLiveData liveData = null;

    // Make sure to take in the document id so you can create the corresponding LiveData
    public LiveData<Alarm> getAlarmLiveData(String documentId) {
        // Only create a new LiveData instance if the current one is null.
        // This is helpful if you intend to use this as a Shared ViewModel.
        if(liveData == null){
            liveData = DAO.getFirestoreLiveData(documentId);
        }

        return liveData;
    }
}

Finally, in your Activity:
// Pass in the document id and observe the ViewModel
model.getAlarmLiveData("MY_DOCUMENT_ID").observe(this, alarm -> {
   if (alarm != null) {
      alarmTextView.setText(alarm.getTest());
   }else{
      Log.d(TAG, "Waiting for data");
   }
});


When will eigenvalues of a matrix be positive?

Question: This may be very general question, Are there any set of conditions that if some arbitrary matrix say A fulfils we can say that A will have eigenvalues such that all of them are non negative. In other words what are conditions for a matrix to be positive semi definite.
Regards
Ahsan
Comment: There is also [Silvester's criterion](http://en.wikipedia.org/wiki/Sylvester%27s_criterion).
Comment: @AlexR That is what the link is pointing to.
Comment: @Pp.. Sorry, I overlooked the last sentence in the article.
Answer: A matrix $A\in\mathbb C^{n\times n}$ is positive semidefinite (All eigenvalues have nonnegative real part) iff

$x^H A x \ge 0 \qquad \forall x\in\mathbb  C^n$
If all principal minor determinants are $\ge 0$. Principal minors are the Matrices $M_I = (a_{ij})_{i,j\in I}, \ I\subset \{1,\ldots,n\}$ where some rows and columns with the same index are removed.
If the ODE $\dot x= -Ax, x(0) = x_0$ satisfies $\lim\limits_{t\to\infty} x(t) = 0$ for all $x_0 \in \mathbb C^n$
The system is called stable in this case.

If $A\in\mathbb R^{n\times n}$ is symmetric ($A=A^T$), it only has real eigenvalues and we can weaken condition 1 to $x^T A x \ge 0 \ \forall x\in\mathbb R^n$
Note that $A\succeq 0$ (positive semidefinite) is not equivalent to all eigenvalues being nonnegative! A real matrix can have complex eigenvalues if it's not symmetric. In this case you need to require $\Re (\lambda_i) \ge 0$ (the real part). For symmetric matrices, this coincides.
Comment: @Omnomnomnom I'm unsure about this...
Comment: @Omnomnomnom $A$ has eigenvalues $1 \pm i$... Where's the problem?
Comment: This definition of positive semidefinite does not imply positive eigenvalues.  We must either impose symmetry or allow $x \in \Bbb C^n$.
Comment: Err, should there be a minus sign on the ODE example? Consider the 1D example $\dot{f}(t) = a f(t)$ with 1-by-1 "matrix" $a$.
Comment: @NickAlger Yes indeed, thanks for pointing out.
Comment: @AlexR counterexample:
$$
A = \pmatrix{1&-1\\1&1}
$$
Note that for all $x \in \Bbb R^n$, $x^TAx = x^Tx$.
Comment: Oh, I see... I interpreted "positive" as "real and positive" rather than "with positive real part".  I'm not sure if there's an issue, then.
Comment: @Omnomnomnom That's an issue with the OP's thought that $\mathrm{eig}(A) \ge 0 \Leftrightarrow A \succeq 0$^^
Comment: Well, that makes sense for the $\Bbb C^n$ definition of positive semidefinite.
Comment: @Omnomnomnom You can define positive semidefiniteness in a much more general context and even restricted to cones. The universal definition for a bilinear form $A$ to be psd on a cone $K$ is
$$A[x,x] \ge 0 \quad \forall x\in K\setminus\{0\}$$
Comment: Found a counterexample:
$$
A = \pmatrix{1&-1\\1&0}
$$
has eigenvalues $\frac{-1 \pm i\sqrt{3}}{2}$, but $x^TAx = |x_1|^2$.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/20842/discussion-between-alexr-and-omnomnomnom).
Answer: Start with the equation $Ax = ax$ for eigenvalue $a$ and eigenvector $x$ of a matrix $A$. Then multiply by the left with $x^T$. Other hint: $x^T x > 0$.


JkWorkersFile: Can't find the workers file specified

Question: I am trying to set up a simple horizonatal Tomcat clustering in windows XP.
Have created a workers.properties file in conf/ directory next to httpd.conf file. However, when trying to start apache using httpd.exe, I am getting the below error.
JkWorkersFile: Can't find the workers file specified
httpd.conf has below entry:
LoadModule jk_module modules/mod_jk.so
JkLogFile "logs/mod_jk.log"
JkLogLevel error
JkMount /TestProject loadbalancer
JkMount /TestProject/* loadbalancer
JkWorkersFile conf/workers.properties

I tried specifying the absoluate path as well
i.e.
    JkWorkersFile "C:/Program Files/Apache Software Foundation/Apache2.2/conf/workers.properties"
But still ended up with the same problem.
Below are the entries from workers.properties
    workers.tomcat_home=$TOMCAT_HOME
    workers.java_home=$JAVA_HOME
    ps=/
    worker.list=tomcatA,tomcatB,tomcatC,loadbalancer
worker.tomcatA.port=8109
worker.tomcatA.host=localhost
worker.tomcatA.type=ajp13
worker.tomcatA.lbfactor=1

worker.tomcatB.port=8209
worker.tomcatB.host=localhost
worker.tomcatB.type=ajp13
worker.tomcatB.lbfactor=1

worker.tomcatC.port=8309
worker.tomcatC.host=localhost
worker.tomcatC.type=ajp13
worker.tomcatC.lbfactor=1

worker.loadbalancer.type=lb
worker.loadbalancer.balanced_workers=tomcatA,tomcatB,tomcatC
worker.loadbalancer.sticky_session=1

Can anyone help me to resolve this please ?
Answer: Check permissions (ACLs), depending on how you start Apache, it might not be able to access that file you newly created.
Answer: I saw this same issue today, although with Win7, not WinXP. For me, the issue was that my workers.properties file had accidentally been saved as a text (.txt) file instead of as a PROPERTIES file. I re-created it, then when saving, chose all file types instead of "text files" to make sure it saved as a .properties file.
When I restarted Apache, all was well. I know the post is old, but maybe this will help someone out looking for the same thing.
Answer: Can you please try to add the worker.properties file under the line of jk module
LoadModule jk_module modules/mod_jk.so
JkWorkersFile conf/workers.properties

After adding please restart the apache web server


Duvidas quanto ao padrão Repository - Modelo Anemico - MVC

Question: Vejo muitas criticas ao modelo anemico de aplicação, por isso decidi tirar essa duvida.
Tenho duas aplicações ASP.NET MVC que poderiam compartilhar os mesmos Models (farão uso das mesmas propriedades e metodos)
Pensando em não reescrever ou copiar e colar toda essa galera, estive lendo sobre o padrão Repository nos links do Macoratti (são 3 artigos http://www.macoratti.net/15/11/net_repo1.htm), e vi que há uma separação entre a regra de negocio e as propriedades, deixando o modelo mais proximo do modelo anemico.

Aparentemente resolveira meu problema inicial, pois eu criaria um camada de dominio (Models), e um repositorio onde colocaria minhas classes BLL, com regras de negocio e acesso a banco, e poderia reaproveitar essas DLL's no meu outro site
Alguem poderia me mostrar quais seriam os pontos ruins disso? Bem como se eu não estou me confundindo sobre o padrão Repository? Ou se existe uma outra saida para que eu não precise reescrever todas essas classes?
Answer: O entendimento sobre o que é o padrão repositório e a afirmação de que o padrão Repository deixaria sua entidade anêmica ou mais anêmica é um equívoco.
A questão é a separação de responsabilidades.
Lembre-se, tudo é relativo e depende. Então estou presumindo que você queira usar um modelo rico. E portanto o resto da resposta vai se pautar em falar sobre esse objetivo.
Sua entidade deve saber o momento se persistir-se. No entanto, ela não deve saber como. Esse é o ponto. Como persistir é algo que revela tecnologias de acesso a dados, ORM's, ou serviços remotos, não importa qual seja a natureza da persistência.
O repositório sabe lidar com a persistência, com a parte de comunicação e integração com tecnologias que são específicas de acesso a dados. Isso não deve ser comportamento ou responsabilidade da sua entidade. Nem sob essa perspectiva, e só me recordo de active record como padrão que prevê algo parecido.
Então fica assim, sua entidade, sabe lidar com as regras de negócio que competem a ela, seu repositório sabe lidar com persistência.


Why do you need to invoke an anonymous function on the same line?

Question: I was reading some posts about closures and saw this everywhere, but there is no clear explanation how it works - everytime I was just told to use it...:
// Create a new anonymous function, to use as a wrapper
(function(){
    // The variable that would, normally, be global
    var msg = "Thanks for visiting!";

    // Binding a new function to a global object
    window.onunload = function(){
        // Which uses the 'hidden' variable
        alert( msg );
    };
// Close off the anonymous function and execute it
})();

Ok I see that we will create new anonymous function and then execute it. So after that this simple code should work (and it does):
(function (msg){alert(msg)})('SO');

My question is what kind of magic happens here? I thought that when I wrote:
(function (msg){alert(msg)})

then a new unnamed function would be created like function ""(msg) ...
but then why doesn't this work?
(function (msg){alert(msg)});
('SO');

Why does it need to be in the same line?
Could you please point me some posts or give me an explanation?
Comment: You have a ; in the first line
Comment: In other languages these are called Function Pointers or Delegates, if you want to look into the lower-level structures involved.
Comment: The line `(function (msg){alert(msg)})('SO');` works completely on its own. It has nothing to do with the other anonymous function you posted before it. Those are two completely seperate anonymous functions. You have to invoke an anonymous function immediately because it has no name and can't be referenced afterwards.
Comment: Now that you know how it works... Don't use it. We should [stop writing anonymous functions](http://stijndewitt.wordpress.com/2013/12/02/stop-writing-anonymous-functions/). With just a few more characters we can give our functions a real name and make debugging Javascript code so much more easy!
Answer: Drop the semicolon after the function definition.
(function (msg){alert(msg)})
('SO');

Above should work.
DEMO Page: https://jsfiddle.net/e7ooeq6m/
I have discussed this kind of pattern in this post:
jQuery and $ questions
EDIT:
If you look at ECMA script specification, there are 3 ways you can define a function. (Page 98, Section 13 Function Definition)
1. Using Function constructor
var sum = new Function('a','b', 'return a + b;');
alert(sum(10, 20)); //alerts 30

2. Using Function declaration.
function sum(a, b)
{
    return a + b;
}

alert(sum(10, 10)); //Alerts 20;

3. Function Expression
var sum = function(a, b) { return a + b; }

alert(sum(5, 5)); // alerts 10

So you may ask, what's the difference between declaration and expression?
From ECMA Script specification:

FunctionDeclaration :
      function Identifier ( FormalParameterListopt ){ FunctionBody
  }
FunctionExpression :
      function Identifieropt ( FormalParameterListopt ){ FunctionBody
  }

If you notice, 'identifier' is optional for function expression. And when you don't give an identifier, you create an anonymous function. It doesn't mean that you can't specify an identifier.
This means following is valid.
var sum = function mySum(a, b) { return a + b; }

Important point to note is that you can use 'mySum' only inside the mySum function body, not outside. See following example:
var test1 = function test2() { alert(typeof test2); }

alert(typeof(test2)); //alerts 'undefined', surprise!

test1(); //alerts 'function' because test2 is a function.

Live Demo
Compare this to
 function test1() { alert(typeof test1) };

 alert(typeof test1); //alerts 'function'

 test1(); //alerts 'function'

Armed with this knowledge, let's try to analyze your code.
When you have code like,
    function(msg) { alert(msg); }

You created a function expression. And you can execute this function expression by wrapping it inside parenthesis.
    (function(msg) { alert(msg); })('SO'); //alerts SO.

Comment: As I wrote, the semi-colon terminated the anonymous function definition. Because it has no name (it's anonymous duh!), you won't be able to call it anymore. If you don't put semicolon then function could still be executed.
Comment: Yeah, but why? Why it need to be as an inline? No matter how many white space I will use.
Comment: Nosredna, JS behaves little arbitarily when it comes to adding semi colons. Read this detailed article: http://blog.boyet.com/blog/javascriptlessons/javascript-for-c-programmers-magic-semicolons/
Comment: I thought that automatic semicolon insertion would put a semicolon in in this case, but it doesn't. So you're right.
Comment: Yes I see that (function (msg){alert(msg)})('SO'); works. I was just asking why does it work. Where this is specified or what kind of JS feature this is. So once I just call: (function (msg){alert(msg)}) what will happen with the function? It will be GC'ed?
Comment: I would like to think that it will be GCed as and when browser decides. But you do lose the ability to use the function.
Comment: palig, I updated my answer with more details about JS function. Hope that helps.
Comment: `alert(typeof test1); //alerts 'test1'` No it doesn't.  `typeof test1 == "function"`
Comment: That's a typo, will correct it. I hope you got the main message though. :)
Comment: Ok great update! Here is now all I need to know on the one place.Many thanks!
Comment: I may be mistaken, but I'm pretty sure IE treats named function expressions as function declarations as well, so you can call the function by name outside of the function itself. So in your example, `mySum` would be defined even outside the function block. I'm not positive about that, but either way, IE has some weird bugs with function declarations. :)
Comment: Douglas Crockford often points out the misinterpretable situations one can inadvertently create by not using semicolons.  Personally, I think it's a best practice to use them all the time--it's easier than remembering the times when it's really important and just putting it in then.  Per [Crockford's code conventions](http://javascript.crockford.com/code.html):  "Put a ; (semicolon) at the end of every simple statement....JavaScript allows any expression to be used as a statement. This can mask some errors, particularly in the presence of [implicit] semicolon insertion."
Comment: What about `alert(function(a,b) {return a+b;})` ? What kind of function is that and how would you input `a` and `b`? I've seen this a lot in jQuery like, `$('.class').addClass(function() {return 'asdf';});`
Comment: There is another way to call anonymous function:  (function(msg) { alert(msg); }('SO')); //alerts SO.
Comment: @chharvey: Passing a function expression to `alert` does not have so much value. But in the case of jQuery there are many situations where this is useful. Your example with `addClass` does not make much sense to me, but the function `on` accepts a listener, which is a callback function. `on` 'knows' it will be getting a function and it will call this at just the right time. Callback functions are mostly used for asynchronous actions (e.g. an ajax request) or for event handling.
Comment: @SolutionYogi Thanks so much! I've been wondering this for a while too, being a novice programmer, and it makes sense now!
Answer: It's called a self-invoked function.
What you are doing when you call (function(){}) is returning a function object.  When you append () to it, it is invoked and anything in the body is executed.  The ; denotes the end of the statement, that's why the 2nd invocation fails.
Comment: Personally, I don't even like the term 'self invoking function'. It's not that function is invoking itself. The programmer wrote those parenthesis to invoke it.
Comment: nice link to article . It notes why someone would use this quoted :"In an effort to protect the global object, all JavaScript applications should be written within a self-invoking
function. This will create an application scope in which variables can be created without the fear of them
colliding with other applications." And also noted "Once the
function terminates, the variables are discarded and the global object remains unchanged."
Comment: Ah ok I see,  so it's just some special JS' syntax, right?

Like this explanation the most! Simple and short :)
Comment: I think it's incorrect to say that the body will be 'evaled'. It executes just like any other function. Because it is anonymous, either you to save the reference somewhere OR execute it right away.
Comment: It's not "special syntax" more than anything else is special.  Actually, the "function name (args) { BLOCK }" form is much more "special".  It is actually unnecessary sugar; this, though, is what actually makes things happen.
Comment: jrockway why is that other code block special? Care to elaborate?
Comment: The link referenced in the answer is broken.
Comment: Also you can pass a function into the self-invoking function, this is really neat, not only variable arguments. The ; tells to JS that execute (ends) the anonymous function.
Comment: This is a great answer that helped me understand anonymous functions after going through a few SO posts
Answer: One thing I found confusing is that the "()" are grouping operators.
Here is your basic declared function.
Ex. 1:
var message = 'SO';

function foo(msg) {
    alert(msg);
}

foo(message);

Functions are objects, and can be grouped. So let's throw parens around the function.
Ex. 2:
var message = 'SO';

function foo(msg) {  //declares foo
    alert(msg);
}

(foo)(message);     // calls foo

Now instead of declaring and right-away calling the same function, we can use basic substitution to declare it as we call it.
Ex. 3.
var message = 'SO';

(function foo(msg) {
    alert(msg);
})(message);          // declares & calls foo

Finally, we don't have a need for that extra foo because we're not using the name to call it! Functions can be anonymous.
Ex. 4.
var message = 'SO';

(function (msg) {   // remove unnecessary reference to foo
    alert(msg);
})(message);

To answer your question, refer back to Example 2. Your first line declares some nameless function and groups it, but does not call it. The second line groups a string. Both do nothing. (Vincent's first example.)
(function (msg){alert(msg)});
('SO');                       // nothing.

(foo);
(msg); //Still nothing.

But
(foo)
(msg); //works

Comment: Thanks.  Your examples were quite clear.  I was unaware that parentheses in JavaScript could change the meaning of the code in this way.  I come from a Java background, so I learn something new (and often unexpected) about JavaScript almost every day I use it.
Comment: Thanks for doing it step by step, this is far better than any other explanation I've seen. +1
Comment: Major AHA moment here- and thank you for illustrating with substitution. +100
Comment: One of the best explanations I've read about anonymous functions. Thanks a lot!
Answer: An anonymous function is not a function with the name "". It is simply a function without a name.
Like any other value in JavaScript, a function does not need a name to be created. Though it is far more useful to actually bind it to a name just like any other value.
But like any other value, you sometimes want to use it without binding it to a name. That's the self-invoking pattern.
Here is a function and a number, not bound, they do nothing and can never be used:
function(){ alert("plop"); }
2;

So we have to store them in a variable to be able to use them, just like any other value:
var f = function(){ alert("plop"); }
var n = 2;

You can also use syntatic sugar to bind the function to a variable:
function f(){ alert("plop"); }
var n = 2;

But if naming them is not required and would lead to more confusion and less readability, you could just use them right away.
(function(){ alert("plop"); })(); // will display "plop"
alert(2 + 3); // will display 5

Here, my function and my numbers are not bound to a variable, but they can still be used.
Said like this, it looks like self-invoking function have no real value. But you have to keep in mind that JavaScript scope delimiter is the function and not the block ({}).
So a self-invoking function actually has the same meaning as a C++, C# or Java block. Which means that variable created inside will not "leak" outside the scope. This is very useful in JavaScript in order not to pollute the global scope.
Comment: The function(){ alert("plop"); } instruction just allocates the function but does not execute it nor binds it to a variable. Since the created function is not bound to any variable, it will be quickly GCed.
Comment: Nice post. What will then happen with the 'function(){ alert("plop"); }' when I did execute it? It will be GC'ed?
Comment: [This SO thread](http://stackoverflow.com/questions/881515/javascript-namespace-declaration) goes beyond the scope of what we're talking about here, but it explains ways of separating JavaScript namespaces--and includes examples that use self-invoking functions.
Answer: It's just how JavaScript works. You can declare a named function:
function foo(msg){
   alert(msg);
}

And call it:
foo("Hi!");

Or, you can declare an anonymous function:
var foo = function (msg) {
    alert(msg);
}

And call that:
foo("Hi!");

Or, you can just never bind the function to a name:
(function(msg){
   alert(msg);
 })("Hi!");

Functions can also return functions:
function make_foo() {
    return function(msg){ alert(msg) };
}

(make_foo())("Hi!");

It's worth nothing that any variables defined with "var" in the body of make_foo will be closed over by each function returned by make_foo.  This is a closure, and it means that the any change made to the value by one function will be visible by another.
This lets you encapsulate information, if you desire:
function make_greeter(msg){
    return function() { alert(msg) };
}

var hello = make_greeter("Hello!");

hello();

It's just how nearly every programming language but Java works.
Answer: The code you show,
(function (msg){alert(msg)});
('SO');

consist of two statements. The first is an expression which yields a function object (which will then be garbage collected because it is not saved). The second is an expression which yields a string. To apply the function to the string, you either need to pass the string as an argument to the function when it is created (which you also show above), or you will need to actually store the function in a variable, so that you can apply it at a later time, at your leisure. Like so:
var f = (function (msg){alert(msg)});
f('SO');

Note that by storing an anonymous function (a lambda function) in a variable, your are effectively giving it a name. Hence you may just as well define a regular function:
function f(msg) {alert(msg)};
f('SO');

Answer: In summary of the previous comments:
function() {
  alert("hello");
}();

when not assigned to a variable, yields a syntax error.  The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect.  Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in
(function() {
  alert("hello");
})();

This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared.  This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.
There is a good SO discussion JavaScript function syntax.
Answer: My understanding of the asker's question is such that:
How does this magic work:
(function(){}) ('input')   // Used in his example

I may be wrong. However, the usual practice that people are familiar with is:
(function(){}('input') )

The reason is such that JavaScript parentheses AKA (), can't contain statements and when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
Source: blog post Immediately-Invoked Function Expression (IIFE)
Answer: examples without brackets:
void function (msg) { alert(msg); }
('SO');

(this is the only real use of void, afaik)
or
var a = function (msg) { alert(msg); }
('SO');

or
!function (msg) { alert(msg); }
('SO');

work as well. the void is causing the expression to evaluate, as well as the assignment and the bang. the last one works with ~, +, -, delete, typeof, some of the unary operators (void is one as well). not working are of couse ++, -- because of the requirement of a variable.
the line break is not necessary.
Comment: @Bergi on ie11 `delete` works. even with `'use strict';`. this works, too: `delete (3 + 4);`
Comment: Ooops, my mistake. "*2) If Type(ref) is not Reference, return true.*" It only throws errors for actual references that are unresolvable.
Answer: This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:
alert(
    {foo: "I am foo", bar: "I am bar"}.foo
); // alerts "I am foo"

Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:
Function.prototype.foo = function () {
    return function () {
        alert("foo");
    };
};

var bar = (function () {}).foo();

bar(); // alerts foo

And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.
var x = function () {} (); // this function is executed but does nothing

function () {} (); // syntax error

One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:
var obj = new function () {
    this.foo = "bar";
};

var obj = {
    foo : "bar"
};

Answer: There is one more property JavaScript function has. If you want to call same anonymous function recursively.
(function forInternalOnly(){

  //you can use forInternalOnly to call this anonymous function
  /// forInternalOnly can be used inside function only, like
  var result = forInternalOnly();
})();

//this will not work
forInternalOnly();// no such a method exist

Comment: +1 Added a small sample so that it's clearer :-) The first time I read it I had to reread 4 times.
Answer: It is a self-executing anonymous function. The first set of brackets contain the expressions to be executed, and the second set of brackets executes those expressions.
(function () {
    return ( 10 + 20 );
})();

Peter Michaux discusses the difference in An Important Pair of Parentheses.
It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.
See:

Closure (computer science)
JavaScript Namespacing
Important Pair of Javascript Parentheses
Answer: Another point of view
First, you can declare an anonymous function:
var foo = function(msg){
 alert(msg);
}

Then you call it:
foo ('Few');

Because foo = function(msg){alert(msg);} so you can replace foo as:
function(msg){
 alert(msg);
} ('Few');

But you should wrap your entire anonymous function inside pair of braces to avoid syntax error of declaring function when parsing. Then we have,
(function(msg){
 alert(msg);
}) ('Few');

By this way, It's easy understand for me.
Answer: The simple reason why it doesn't work is not because of the ; indicating the end of the anonymous function. It is because without the () on the end of a function call, it is not a function call. That is,
function help() {return true;}

If you call result = help(); this is a call to a function and will return true.
If you call result = help; this is not a call. It is an assignment where help is treated like data to be assigned to result.
What you did was declaring/instantiating an anonymous function by adding the semicolon,
(function (msg) { /* Code here */ });

and then tried to call it in another statement by using just parentheses... Obviously because the function has no name, but this will not work:
('SO');

The interpreter sees the parentheses on the second line as a new instruction/statement, and thus it does not work, even if you did it like this:
(function (msg){/*code here*/});('SO');

It still doesn't work, but it works when you remove the semicolon because the interpreter ignores white spaces and carriages and sees the complete code as one statement.
(function (msg){/*code here*/})        // This space is ignored by the interpreter
('SO');

Conclusion: a function call is not a function call without the () on the end unless under specific conditions such as being invoked by another function, that is, onload='help' would execute the help function even though the parentheses were not included. I believe setTimeout and setInterval also allow this type of function call too, and I also believe that the interpreter adds the parentheses behind the scenes anyhow which brings us back to "a function call is not a function call without the parentheses".
Comment: I don't understand why this received so many downvotes. I think it is an acceptable answer? :/
Answer: When you did:
(function (msg){alert(msg)});
('SO');

You ended the function before ('SO') because of the semicolon. If you just write:
(function (msg){alert(msg)})
('SO');

It will work.
Working example: http://jsfiddle.net/oliverni/dbVjg/
Answer: (function (msg){alert(msg)})
('SO');

This is a common method of using an anonymous function as a closure which many JavaScript frameworks use.
This function called is automatically when the code is compiled.
If placing ; at the first line, the compiler treated it as two different lines. So you can't get the same results as above.
This can also be written as:
(function (msg){alert(msg)}('SO'));

For more details, look into JavaScript/Anonymous Functions.
Comment: As far as I know, JavaScript doesn't "compile"
Answer: Anonymous functions are functions that are dynamically declared at
runtime. They're called anonymous functions because they aren't
given a name in the same way as normal functions.
Anonymous functions are declared using the function operator instead
of the function declaration. You can use the function operator to
create a new function wherever it's valid to put an expression. For
example, you could declare a new function as a parameter to a
function call or to assign a property of another object.
Here's a typical example of a named function:
function flyToTheMoon() {
    alert("Zoom! Zoom! Zoom!");
}

flyToTheMoon();

Here's the same example created as an anonymous function:
var flyToTheMoon = function() {
   alert("Zoom! Zoom! Zoom!");
}

flyToTheMoon();

For details please read  http://helephant.com/2008/08/23/javascript-anonymous-functions/
Answer: The IIFE simply compartmentalizes the function and hides the msg variable so as to not "pollute" the global namespace. In reality, just keep it simple and do like below unless you are building a billion dollar website.
var msg = "later dude";
window.onunload = function(msg){
  alert( msg );
};

You could namespace your msg property using a Revealing Module Pattern like:
var myScript = (function() {
    var pub = {};
    //myscript.msg
    pub.msg = "later dude";
    window.onunload = function(msg) {
        alert(msg);
    };
    //API
    return pub;
}());

Answer: Anonymous functions are meant to be one-shot deal where you define a function on the fly so that it generates an output from you from an input that you are providing. Except that you did not provide the input. Instead, you wrote something on the second line ('SO'); - an independent statement that has nothing to do with the function. What did you expect? :)
Comment: Not 100% correct. This is an anonymous function as well and is meant to be reused: `var foo = function() {};`. Everything else is fine though.


Custom objects in ParseKit Actions

Question: I am very intrigued by the ability to add actions to ParseKit grammars. There is surprisingly little documentation on what is available in those actions. Say I have two rules like:
databaseName        = Word;
createTableStmt     ='CREATE' ('TEMP'| 'TEMPORARY')? 'TABLE' 'IF NOT EXISTS'? databaseName;

This obviously isn't a whole grammar but will serve as an example. When parsing i'd like to "return" a CreateTableStmt object that has certain properties. If I understand the tool correctly i'd add an action to the rule, do stuff then push it on the assembly which will carry it around for the next rule to deal with or use.
So for example it would look like:
createTableStmt     ='CREATE' ('TEMP'| 'TEMPORARY')? 'TABLE' 'IF NOT EXISTS'? databaseName;
{
    AnotherObj* dbName = Pop(); //gives me the top most object
    CreateTableStmt* createTable = [[CreateTableStmt alloc] initWith:dbName];
    //set if it was temporary
    // set 'IF NOT EXISTS'
    PUSH(createTable);//push back on stack for next rule to use
}

Then when everything is parsed I can just get that root object off the stack and it is a fully instantiated custom representation of the grammar. Somewhat like building an AST if i remember correctly. I can then do stuff with that representation much easier than with the passed in string.
My question is how can I see if it matched ('TEMP' | 'TEMPORARY') so I can set the value. Are those tokens on the stack? Is there a better way than to pop back to the 'CREATE' and see if we passed it. Should I be popping back to the bottom of the stack anyway on each match?
Also if my rule was instead
qualifiedTableName  = (databaseName '.')? tableName (('INDEXED' 'BY' indexName) | ('NOT' 'INDEXED'))?;

Is it correct to assume that the action would not be called until the rule had been matched? So in this case when the action is called to the stack could look like:
possibly:
|'INDEXED'
|'NOT'
or:
|indexName (A custom object possibly)
|'BY'
|'INDEXED

|tableName (for sure will be here)

and possibly these
|'.'            (if this is here I know the database name must be here) if not push last one on?
|databaseName
--------------(perhaps more things from other rules)

Are these correct assessments? Is there any other documentation on actions? I know it is heavily based on Antlr but its the subtle differences that can really get you in trouble.
Answer: Creator of ParseKit here. A few items:
ParseKit deprecation:
Just this week, I have forked ParseKit to a cleaner/smaller/faster library called PEGKit. ParseKit should be considered deprecated, and PEGKit should be used for all new development. Please move to PEGKit.
PEGKit is nearly identical to the grammar and code-gen features of ParseKit, and your ParseKit grammars are usable with PEGKit with a few small changes. In fact, all of the examples in your question here are usable with no changes in PEGKit.
See the Deprecation Notice in the ParseKit README.
And this tutorial on PEGKit.
Syntax errors in your grammar:
I spot 3 syntax errors in your grammar samples above (this applies equally to both ParseKit and PEGKit).

This line:
createTableStmt     ='CREATE' ('TEMP'| 'TEMPORARY')? 'TABLE' 'IF NOT EXISTS'? databaseName;
Should be:
createTableStmt     ='CREATE' ('TEMP'| 'TEMPORARY')? 'TABLE' ('IF' 'NOT' 'EXISTS')? databaseName;
Notice the break up of the invalid 'IF NOT EXISTS' construct into individual literal tokens. This is not only necessary, but also desireable so that variable whitespace between the words is allowed.

The POP() macro should be all upper case.

Your createTableStmt rule is missing a semicolon at the very end (after the action's closing }).

Before Answering:
Make sure you are using v0.3.1 PEGKit or later (HEAD of master). I fixed an important bug while finding the answer to your question, and my solutions below require this fix.
Answer to your first question:

My question is how can I see if it matched ('TEMP' | 'TEMPORARY') so I can set the value?

Good question! You basically have the right idea in your further comments above.
Specficially, I would probably break up the createTableStmt rule into 4 rules  like this:
createTableStmt = 'CREATE'! tempOpt 'TABLE'! existsOpt databaseName ';'!;

databaseName = QuotedString;

tempOpt
    = ('TEMP'! | 'TEMPORARY'!)
    | Empty
    ;

existsOpt
    = ('IF'! 'NOT'! 'EXISTS'!)
    | Empty
    ;

Notice all of the vital ! discard directives for discarding unneeded literal tokens.

Also Notice that I've changed the last two rules to use | Empty rather than ?. This is so I can add Actions to the Empty alternatives (you'll see that in a sec).

Then you can either add Actions to your grammar, or use ObjC parser delegate callbacks if you prefer to work in pure code.
If you use Actions in your grammar, something like the following will work:
createTableStmt = 'CREATE'! tempOpt 'TABLE'! existsOpt databaseName ';'!
{
    NSString *dbName = POP();
    BOOL ifNotExists = POP_BOOL();
    BOOL isTemp = POP_BOOL();
    NSLog(@"create table: %@, %d, %d", dbName, ifNotExists, isTemp);
    // go to town
    // myCreateTable(dbName, ifNotExists, isTemp);
};

databaseName = QuotedString
{
    // pop the string value of the `PKToken` on the top of the stack
    NSString *dbName = POP_STR();
    // trim quotes
    dbName = [dbName substringWithRange:NSMakeRange(1, [dbName length]-2)];
    // leave it on the stack for later
    PUSH(dbName);
};

tempOpt
    = ('TEMP'! | 'TEMPORARY'!) { PUSH(@YES); }
    | Empty { PUSH(@NO); }
    ;

existsOpt
    = ('IF'! 'NOT'! 'EXISTS'!) { PUSH(@YES); }
    | Empty { PUSH(@NO); }
    ;

I've added this Grammar and a test case to the PEGKit project.
As for your second question, please break it out as a new SO question, and tag it ParseKit and PEGKit and I will get to it ASAP.
Comment: Wow, this just blew my parsing mind. Just starting out watching someone well versed in grammar creation is really cool. Thanks for the exhaustive, clear answer. Awesome tool. Picked the perfect time to start diving in with the update. Any chance you'll port over your demo app or create an ANTLR like grammar editor?

Custom objects in ParseKit Actions


Regarding Transformation on Uniformly Distributed Unit Disk

Question: $(X,Y)$ is distributed uniformly on the unit disk.
The transformations are:

$$
Z = {X + Y \over \sqrt{2}}\,,\qquad
W = {X - Y \over \sqrt{2}}
$$

I solved these equations in terms of $X$ and $Y$ and got:

$X$ = $(Z+W)/\sqrt(2)$
$Y$ = $(Z-W)/\sqrt(2)$

which has Jacobian equal to 1. Joint distribution of $Z$ and $W$ should be
$f(z, w)$ = $1/2\pi$ but with range -$\sqrt(2)$ $<$ $z$ $<$ $\sqrt(2)$. I'm not sure how to restrict the range of W.
The questions of interest are:
(a) What is the distribution of Z? Find $E[Z]$ and $Var[Z]%|$.

It seems fairly easy to see that $E[Z] = 0$ since the expectation of $X$ and $Y$ are both zero (both random variables are centered around zero). However, how would we compute $E[X^2]$ in order to compute the variance?

(b) Are Z and W uncorrelated? And are they independent?

I think that they are uncorrelated, but that they are not independent. I think this part might get easier after figuring out the exact range of the joint distribution.

(c) What is the distribution of $X/Y$ (the ratio of X and Y)?

Making the transformation $U$ = $X/Y$ and $V$ = $Y$ we have Jacobian 1. I'm confused as to what the range of joint distribution should be.

(d) What is the distribution of $Z/W$?

I'd imagine this part would get easier after figuring out part (c)
Comment: First things first: why do you think the range of $(Z,W)$ is the square $\{(z,w)\mid-\sqrt2\lt z,w\lt\sqrt2\}$? Even before that, I do not see the density of $(X,Y)$ in your question, did you write it down?
Comment: Sorry! I was really sleepy when I wrote the question. I didn't think range of (Z,W) was a square. I meant that one of the variables range from $-\sqrt(2)$ to $\sqrt(2)$ and I was having trouble getting the range of the other variable. Also the density of (X,Y) is $1/\pi$ and their marginals should be Y|X ~ Uniform from $(-\sqrt(1-x^2), \sqrt(1-x^2))$ and X|Y also uniform based on symmetricity.
Comment: The density of $(X,Y)$ is not $1/\pi$ since the function $1/\pi$ is not integrable on $\mathbb R^2$. I believe the most useful thing you can do here is to write down correctly the density of $(X,Y)$, so... what is this density?
Comment: Thank you for your reply. Why wouldn't the joint density be $1/\pi$? The area of region should be just the area of circle which is $\pi$, is that not right?
Comment: No, if you say the density is $1/\pi$ then the density is $1/\pi$ everywhere, and that is impossible. Or you mean that the density is $1/\pi$ somewhere and $0$ elsewhere--and then the density is not $1/\pi$ but...
Comment: Well the density of (X,Y) would be $1/\pi$ inside the unit disk and 0 outside it. I thought that was obvious from saying that (X,Y) is uniform on the unit disk, but probably still better to be clearer.
Comment: Right, $f_{X,Y}(x,y)=(1/\pi)\mathbf 1_{x^2+y^2\leqslant1}$ for every $(x,y)$. Now, $(Z,W)$ is what you know. Does this yield the density $f_{Z,W}$?
Answer: The transformation you have chosen is a rotation of coordinates, and so the joint density of $W$ and $Z$ is the same as the joint density of $X$ and $Y$, that is,
having value $\pi^{-1}$ inside the unit disc and value $0$ outside.  While it is
true that the maximum values of $X$ and $Y$ are $1$, they cannot take on value
$1$ simultaneously and so your range $(-\sqrt{2}, \sqrt{2})$ is incorrect.
(a) To find $\displaystyle E[X^2] = \int_{-\infty}^\infty \int_{-\infty}^\infty
x^2 f_{X,Y}(x,y)\,\mathrm dx\,\mathrm dy$, change to polar coordinates. You will also need $\operatorname{cov}(X,Y)$ which can also be found by computing $E[XY]$
via the change to polar coordinates.
(b) Uncorrelated is easy to do since $E[ZW] = \frac{1}{2}E[X^2-Y^2] = 0$. Why?
They are not independent for the same reason that $X$ and $Y$ are not
independent: the support of the joint density is not a product set and
so the joint density does not factor into the product of the marginal
densities over the entire plane.
(c) Don't use Jacobians here, just ask yourself how you might compute
$P\{Y/X \leq \alpha\}$ directly. Drawing a picture will help tremendously
here. But if not, look at this answer.
(d) Since the joint density of $Z$ and $W$ is the same as the joint
density of $X$ and $Y$, ....


Equation for tangent line for $f(x) = 1/\sqrt{x}$ at $x=a$

Question: first time math stack-exchange-er here.
I'm self-teaching single variable calculus using MIT's free online courses and I think I found a typo in the homework solution set (problem 1C-4 part d).  I'm not confident enough in my own abilities to know for sure if this is a mistake vs. my poor math skills.
Could anyone tell me if the following equation is correct?
The problem is as follows:
Write an equation for the tangent line for the following functions:
$$f(x) = \frac1{\sqrt{x}}\ \text{ at } x=a$$
I did the following.  First I found the derivative of $f(x)$:
$$f'(x) = -\frac12 x^{-\frac32}\ $$
Then I plugged in a to get $f(a)$ and $f'(a)$ and used the point-slope method to find the equation for the tangent line:
$$y-a^{-\frac12} = -\frac12 a^{-\frac32}(x-a)\ $$
Which I then simplified to:
$$y=-\frac12a^{-\frac32}x  + \frac32 a^{-\frac12}\ $$
However, the solution set says the answer is:
$$y=-a^{-\frac32}x  + \frac32 a^{-\frac12}\ $$
Is the solution set correct?  If so, where did the $-\frac12$ go?
Thank you!
Comment: Don't forget: the answers to problems are often supplied by underpaid and overworked graduate students. And it would be unheard of for them to be checked by the author(s) of the text.
Comment: I get the same answer as you did, seems solution set answer is wrong.
Comment: Welcome to Math.SE! A very excellently asked first question.
Comment: You are right ... there is a mistake in their solutions.
Comment: Also, notice another typo in it: the minus sign in $a^{3/2}$ is omitted.
Comment: ok whew!  I thought I was going crazy.  Thank you all for the quick responses!
Answer: Just to reiterate what was said in the comments and to remove this question from the unanswered queue, your solution is correct and the one provided by the book is wrong.


How to create multiple objects from a class with different variables?

Question: I have a class called Rain. It has a constructor in it and various methods. In my program I want to be able to generate say 50 objects, but I want them to have different values along the x-axis. I have 2 objects done and they slide down the area but I want to be able to create 50 plus of these so I can achieve the effect of rain. Basically here is my code and my constructors.
Rain Program:
Rain rain;
Rain rain2;

void setup()
{
    size (400,400);
    noStroke();
    rain = new Rain(20,random(0,10),3,15);
    rain2 = new Rain(random(15,35), random(70,110),3,15);
}

void draw()
{
    background(0);
    rain.colour(125,155,100);
    rain.display();
    rain2.colour(125,155,100);
    rain2.display();
}

And here is the class itself:
class Rain
{
    float wCoord, xCoord, yCoord, zCoord;
    int red, green, blue, gray;

    Rain()
    {
    }

    Rain(float wCoord, float xCoord, float yCoord, float zCoord)
    {
        this.wCoord = wCoord;
        this.xCoord = xCoord;
        this.yCoord = yCoord;
        this.zCoord= zCoord;
    }

    void display()
    {
        rect(20,xCoord, yCoord, zCoord);
        xCoord+=3;
        if(xCoord>height-5)
            {
                xCoord=random(0,15);
            }
    }

    void colour(int red, int green, int blue)
    {
        this.red = red;
        this.green = green;
        this.blue = blue;
        fill (red, green, blue);
    }

    void colour(int gray){
        this.gray = gray;
        fill (this.gray);
    }
}

Comment: Can you indent your code sensibly please?
Comment: what do you do with Rain() ?  It just seems useless.
Comment: Your [other question](http://stackoverflow.com/questions/34025881/how-to-create-array-from-a-class-constuctor) already includes explanations on how to create multiple instances using an `array` or `ArrayList`. What exactly are you confused about? Can you post an image showing the effect you're going for?
Comment: where come your random() from ?
Comment: @guillaumegirod-vitouchkina `random()` is a method provideded by [Processing](http://processing.org)'s API
Answer: I made some changes in the code.
see the comments
//an array of Rains... shouldn't it be called Drop
Rain[] drops = new Rain [1000];

void setup()
{
  size (400, 400);

  // initialize all Rains
  // the constructor gets no parmeters
  // and random initialization is handled
  // at class itself
  for (int i = 0; i < drops.length; i++) {
    drops[i] = new Rain();
  }
}

void draw()
{
  background(0);

  // just diaplay them
  for (Rain r : drops) {
    r.display();
  }
}

//any key to demosntrate colour() method
void keyPressed() {
  for (Rain r : drops) {
    r.colour(255);
  }
}

// and the overload version
void keyReleased() {
  for (Rain r : drops) {
    r.colour(125, 155, 100);
  }
}

class Rain
{
  // you never used wcoord... got rid
  // renamed some vars to make code easier to read
  // like now the coord used to y position is
  // yCoord instead of xCoord... :)
  // variables with meaningfull names rules

  float xCoord, yCoord, w, h, speed;

  // a default color
  color c = color(125, 155, 100);

  final static int MIN_Y      = -200, MAX_Y = 0;
  final static int MIN_WIDTH  = 2, MAX_WIDTH = 4;
  final static int MIN_HEIGHT = 5, MAX_HEIGHT = 13;
  final static int MIN_SPEED  = 2, MAX_SPEED = 6;

  Rain()
  {
    //Get new random values
    initialize();
  }

  void initialize() {
    yCoord = random(MIN_Y, MAX_Y);
    xCoord = random(width);
    w      = random(MIN_WIDTH, MAX_WIDTH);
    h      = random(MIN_HEIGHT, MAX_HEIGHT);
    speed  = random(MIN_SPEED, MAX_SPEED);
  }

  void display()
  {
    noStroke();
    fill(c);
    rect(xCoord, yCoord, w, h);

    yCoord+=speed;

    if (yCoord > height-5)
    {
      initialize();
    }
  }

  void colour(int red, int green, int blue)
  {

    c = color (red, green, blue);
  }

  void colour(color gray) {
    c = color (gray);
  }
}


change bootstrap tooltip position

Question: I have following code snippet to change the bootstrap tooltip position.
But I am not sure what is meant by "my" , "at" and left+15 etc.
Please explain so that I can change the values to position my tooltip.
   $( "#btn1" ).tooltip({ position: { my: "left+15 center", at: "right center" } });

Answer: .position() is specific to jQuery UI.
The option my defines which position on the element being positioned to align with the target element horizontally. A single value such as "right" will be normalized to "right center", "top" will be normalized to "center top" (following CSS convention). The acceptable horizontal values are "left", "center", "right". The acceptable vertical values are "top", "center" and "bottom". Each dimension can also contain offsets, in pixels or percent. For example, "right+10 top-25%". Percentage offsets are relative to the element being positioned.
The option at defines which position on the target element to align the positioned element against horizontally. Percentage offsets are relative to the target element.
The default for both options is "center".
You can find more information about .position() here.
Answer: The bootstrap plugin methods take a single argument, not two. This method call:
$('#keterangan').attr('title', 'Keterangan wajib disi!').tooltip('show', {
    placement: 'right'
});

is incorrect. Instead, you should keep the on change function the way you had it, and call:
$('#keterangan').tooltip({ placement: 'right' });

earlier to set up the tooltip options (such as when the document is ready).
The other, possibly simpler, alternative would be to add data-position="right" to the element that the pop-up is being shown on.
Answer: The code is from jqueryui, not bootstrap.
Complete explanation of your code sample is in the next links
Tooltip widget position: http://api.jqueryui.com/tooltip/#option-position
Parameters for position: http://api.jqueryui.com/position/

change bootstrap tooltip position


SQL In and having-clause, why do they produce different results?

Question: Considering the following relation movie {country,major_genre,production_year, run_time, title, I'd like to list all countries except Spain, the movies produced in that country, provided there are at least two of them.
I wrote two queries and they somehow produced different results. It seems that the first one is correct, but it seems to me that they are equal. I am learning SQL. Can someone please help to explain the differences? Thanks for your help!
The first one:
SELECT m1.country, m1.production_year, m1.title
FROM movie m1
WHERE m1.country <> "Spain"
AND m1.country
IN (
    SELECT m2.country
    FROM movie m2
    GROUP BY m2.country        //select only the ones with at least 2 movies
    HAVING COUNT( * ) >=2
 )
ORDER BY m1.country ASC , m1.production_year DESC

And the second one:
SELECT m1.country, m1.production_year, m1.title
FROM movie m1
WHERE m1.country <> "Spain"
GROUP BY m1.country
HAVING COUNT( * ) >=2  //the country selected should have count of at least 2 rows
ORDER BY m1.country ASC , m1.production_year DESC

Comment: Looks like a MySQL query which is relaxed about the rules related to the GROUP BY clause. FYI, the second query is not correct, as you must list all the columns in the GROUP BY clause that are in the SELECT list
Comment: My very first question is , Did the second query work ?
Comment: I am seeing  "m1.country, m1.production_year, m1.title" in the select statement but whereas in the group by you have only  m1.country
Comment: yes the second one worked..
Comment: But after adding "m1.country, m1.production_year, m1.title" to group by, it is still not correct
Comment: The general GROUP BY rule is:
If a GROUP BY clause is specified, each column reference in the SELECT list must either identify a grouping column or be the argument of a set function.
Answer: The problem is that the second query uses GROUP BY on a single column, but returns 3 columns. So each country with > 1 movie comes out once, with a "random" value for year and movie (may not actually be random).
You can also do it without the GROUP BY:
SELECT m1.country, m1.production_year, m1.title
FROM movie m1
WHERE m1.country <> "Spain"
AND 1 < (
    SELECT count(*)
    FROM movie m2
    WHERE m2.country = m1.country
  )
ORDER BY m1.country ASC , m1.production_year DESC

Here is a fiddle: http://sqlfiddle.com/#!9/e2ddc/2
Comment: Because the `COUNT(*)` applies to all the columns in the `GROUP BY`. So, in your original 2nd query, you are asking _summarize by country and only keep the countries with > 1 in the group_ then add year and title from somewhere. Which is why it doesn't quite work. You have already summarised rows down to one per country so you can't go back to having multiple per country.
Comment: If you ask to `GROUP BY` more columns, the `COUNT(*)` will no longer be what you want, because you are counting years and titles. You can't both group (by country) and include the things (year, title) you are ignoring for the group in a single step.
Comment: Thanks! But I am trying to understand why the second one doesnt work. Even after I add `m1.country, m1.production_year, m1.title` to the GROUP BY, it is still incorrect.