Self signed certificates create problems on NGinx/PHP

Question: I just upgraded my Debian 7, Nginx 1.6.2, PHP 5.4.39 to Debian 8, Nginx 1.6.2, PHP 5.6.9.
There is a CRM running on that server where we used to send emails via PHP, EspoCRM and that's using ZendFramwork2 E-Mail (sending via server 2 - sending via Thunderbird works just fine).
That was working just fine until after the upgrade. Now I've got an error saying:
500 unable to connect via tls

So a bit searching didn't bring anything up with the CRM but rather points to the self signed certificate and/or something at the stack above (NGinx/PHP?).
Any idea where to start digging? In my CRM server I don't have anything in the error logs (guess that is swallowed by the CRM).
I don't see anything in the syslog or authlog of the maiml server either.
EDIT: Add info:
phpinfo ()
Registered Stream Socket Transports tcp, udp, unix, udg, ssl, sslv3, tls, tlsv1.0, tlsv1.1, tlsv1.2
curl
SSL     Yes
SSL Version     OpenSSL/1.0.1k
imap
SSL Support     enabled
openssl
OpenSSL support     enabled OpenSSL
Library Version     OpenSSL 1.0.1k 8 Jan 2015 OpenSSL Header Version
OpenSSL 1.0.1k 8 Jan 2015  Directive    Local Value Master Value
openssl.cafile  no value    no value openssl.capath no value    no value
Phar
OpenSSL support     enabled

I used the old config file from Debian 7 (NGinx is the same version - I used a backport on D7).
Servers and Software:
Server A: Mailserver, Debian 6, Postfix, selfsigned certificates
Server B: Debian 8, Nginx, PHP, EspoCRM - I've choosen TLS since it's working in my Thunderbird on my local PC and it was working before the Debian 7 to 8 upgrade.
Local PC: Kubuntu, Thunderbird, Mails can be sent and received via TLS.
Comment: Looks like Nginx is enforcing tls protocols. Can you post the ssl configuration parts of your nginx configs
Comment: I don't understand which program connects to which service via a certain protocol.
Comment: @Drifter104 are the phpinfo outputs sufficient or do you need other information from other parts/config files? (just added more info to the question)
Comment: Oh I see, sorry misunderstood the question.
Answer: As I understand it, PHP 5.6 does not allow accept validate or process self-signed certs.
http://php.net/manual/en/migration56.openssl.php
You have to disable the verifying of peer and peer names
$streamContext = stream_context_create([
            'ssl' => [
                'verify_peer'      => false,
                'verify_peer_name' => false
            ]
        ]);

This is non-trivial if trying to do it within a package (which seems to be by-design), you cannot just set some flags in php.ini or anything simple like that.
Comment: In the context you refer to it never has.
Answer:
500 unable to connect via tls

That's not very helpful in identifying where the problem is - but it must be somewhere in the code which presumably you don't maintain, therefore amending the code to make it work should be a last resort.
It would be useful to know what action triggers this error.
Since the only place in your manifest that mentions a self-signed certificate is the mail server, then I will assume that is what is causing the problem here.
All you need to do is add the self-signed certificate to the accepted authorities on the host where the application resides. Assuming (again) that the MTA is using SMTPS:
openssl s_client -showcerts -connect servera.example.com:465 </dev/null

Will give you the certificate chain. Copy the output into (say) /etc/ssl/certs/lbutlr_local.crt then run update-ca-certificates


dpm does not display form return values

Question: I just enabled the devel module on Drupal 6 and using dpm($form) was showing values for me but  it does not show values any more. What would mostly the issue here? Is there a way to see those values?
Thanks
Comment: This is difficult issue to help you with if you're not providing any code or a specific context.
Answer: In say a validation function, to see both the $form structure and what the user has entered, use a devel debug statement like:
dpm(array('$form' => $form, '$form_state' => $form_state), "Validation debug");

The $form_state['values'] array will contain the raw user entries you can then access and validate.
Answer: Typical cases for why a dpm(...) doesn't show up:

Cache: The dpm() is in some cached code and is not actually being executed.
Access: You are viewing the page with a user that doesn't have access to see the debug messages.
Ajax/etc: Some code clears the messages before they are rendered, in this case you can use dd() to print to a log file instead.
Comment: Also sometimes while putting dpm() in theme part, it may not be executed while kpr() will.

dpm does not display form return values


DataFrame: Convert the columns in a df to list of row in Python dataframe

Question: I have a pandas dataframe like below
id     name     value1   value2    value3     Type
=======================================================
 1     AAA       1.0       1.5       1.8      NEW
 2     BBB       2.0       2.3       2.5      NEW
 3     CCC       3.0       3.6       3.7      NEW

I have convert the above df into something like below so that i can join it to another df based on name (which will be unique in my case)
Type        AAA                     BBB                 CCC
================================================================
NEW    [1.0, 1.5, 1.8]       [2.0, 2.3, 2.5]      [3.0, 3.6, 3.7]

Is there any way to achieve this instead of having too many looping statements.
Any help is much appreciated.
Thanks,
Comment: Please provide the work you've tried so far. You had a nearly identical question answered just a few minutes ago that deals with the list making part. Is this just a swapping rows and columns question? Maybe transpose? https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.T.html
Comment: That seems like an odd transformation to then do for a join. Wouldn't you want to make "name" an index and do the join that way? And why do you need to make a list to do the join?
Answer: A possible solution, which first adds column value containing the list and then uses pivot:
(df.assign(value=df.loc[:, 'value1':'value3'].apply(list, axis=1))
 .pivot(index='Type', columns='name', values='value')
 .rename_axis(None, axis=1).reset_index())

Output:
  Type              AAA              BBB              CCC
0  NEW  [1.0, 1.5, 1.8]  [2.0, 2.3, 2.5]  [3.0, 3.6, 3.7]

Answer: Using melt and pivot_table:
(df.melt(['id', 'name', 'Type'])
   .pivot_table(index='Type', columns='name',
                values='value', aggfunc=list)
   .reset_index().rename_axis(columns=None)
)

Output:
  Type              AAA              BBB              CCC
0  NEW  [1.0, 1.5, 1.8]  [2.0, 2.3, 2.5]  [3.0, 3.6, 3.7]

Answer: You can use melt and groupby_agg:
>>> (df.melt(['id', 'name', 'Type'])
       .groupby(['name', 'Type'])['value']
       .agg(list).unstack('name')
       .reset_index().rename_axis(columns=None))

  Type              AAA              BBB              CCC
0  NEW  [1.0, 1.5, 1.8]  [2.0, 2.3, 2.5]  [3.0, 3.6, 3.7]

Edit: this is almost equivalent to @mozway's answer.
Answer: How do you want to handle the Type column for instances where it is not "NEW"?
Ignoring that for now. You can do something like the following...
df = pd.DataFrame({'name':['AAA','BBB','CCC'],'value1':[1,2,3],'value2':[4,5,6]})
columns = df.name.values
values = df[[i for i in df.columns if 'value' in i]].values
df = pd.Series(dict(zip(columns, values))).to_frame().T


Can I approximate the variance of a ratio to the ratio of two variances?

Question: I've been slowly working my way through problems in Casella and Burger's Statistical Inference and I stumbled upon this problem:

I haven't been able to get past (a). I've tried using the approximation formulas derived from the Delta Method:
$$E[\frac{U}{V}] \approx \frac{E[U]}{E[V]}$$
$$\mathbb{and}$$
$$Var(\frac{U}{V}) \approx (\frac{E[U]}{E[V]})^{2}\cdot(\frac{Var(U)}{E(U)} - \frac{2Cov(U,V)}{E[U]\cdot E[V]} + \frac{Var(V)}{E[V]})$$
where U,V are random variables. Before I go on, observe that
$$\frac{\sum(X_i Y_i)}{\sum X^{2}_i} = \beta + \frac{\sum(X_i \epsilon_i)}{\sum(X^{2}_i)}$$
Approximating our expectation, we obtain
$$E[\beta + \frac{\sum(X_i \epsilon_i)}{\sum(X^{2}_i)}]=\beta$$
since $X_i$ and $\epsilon_i$ are independent of each other and $E[\epsilon_i]=0$. Now, if I proceed the following, I get variance of 0 using the approximation formula I have up top:
$$Var(\beta + \frac{\sum(X_i \epsilon_i)}{\sum(X^{2}_i)})=Var(\frac{\sum(X_i \epsilon_i)}{\sum(X^{2}_i)})\approx 0$$
which seems remarkably unlikely. Thus, I am wondering if it is possible to have the following approximation given the independence of our samples:
$$Var(\frac{\sum(X_i \epsilon_i)}{\sum(X^{2}_i)})\approx\frac{Var(\sum(X_i \epsilon_i))}{Var(\sum(X^{2}_i))}$$
If this is indeed possible, would someone be kind enough to give an explanation as to why?
Answer: $Var( X_i\epsilon_i)= E[(X_i\epsilon_i)^2]-(E[X_i\epsilon_i])^2 =EX_i^2 \times E\epsilon_i^2-0=(\mu^2+\tau^2)\sigma^2$
Corrected formula:
$$Var(\frac{U}{V}) \approx (\frac{E[U]}{E[V]})^{2}\cdot(\frac{Var(U)}{(E(U))^2} - \frac{2Cov(U,V)}{E[U]\cdot E[V]} + \frac{Var(V)}{(E[V])^2})$$
and hence in this case(since $EU=0$):
$$Var(\frac{U}{V}) \approx \frac{Var(U)}{(E(V))^2} = \frac{n(\mu^2+\tau^2)\sigma^2}{(n(\mu^2+\tau^2))^2} = \frac{\sigma^2}{n(\mu^2+\tau^2)}$$
Comment: Oh god. So I was fried and wrote the formula out wrong. -_-
Thank you, rightskewed!


Posson and Binomic distribution

Question: Exercise:
An ecologist wants to examine the deer population in two different areas, area 1 and area 2. He assumes the number of deer, X and Y, in areas 1 and 2, has Poisson distribution.

a.
The ecologist calculates that the expected number of deer is $2$ in area $1$ and $4$ in area $2$. Find $P(X=2)$ and $P(X>=3)$, and find an approximate expression for $P(X = Y)$. Specify the expectation you must use to calculate $P(x = y)$.

I have solved this exercise as written below:
Definition:
A random variable $X$ is said to have Poisson distribution with parameter $\lambda (>0)$ if $p(x)$ of $X$ is given by
\begin{align}\\
& p(x; \lambda) = \frac{e^{-\lambda}{\lambda ^x}}{x!}
\end{align}
For $\lambda_1 = 2$:
\begin{align}\\
& P(X=2)=\frac{e^{-2}{2^2}}{2!}=\frac{2}{e^2}=0,27067\\
& P(X=1)=\frac{e^{-2}{2^1}}{1!}=\frac{2}{e^2}=0,27067\\
& P(X=0)=\frac{e^{-2}{2^0}}{0!}=\frac{1}{e^2}=0,13533\\
\end{align}
For $P(X>=3)$:
\begin{align}\\
& P(X>=3) = 1-P(X<=2) \\
& P(X>=3) = 1-P(X=0)-P(X=1)-P(X=2) \\
& P(X>=3) = 1-0,27067-0,27067-0,13533 \\
& P(X>=3) = 0,32333
\end{align}
I assume this is correct, but please correct me if I got anything wrong.

b.
If a deer is in such an area, the ecologist assumes a probability of 0.4, that it will be observed. If there are actually 5 deer in the area, what is the probability that three of them will be observed? What is the expected number of deer observed?

I assume this is a Binominal distibution, because it satisfies the four axioms. There are two possible outcomes; observed or not observed. And $P(1)=0,4$. But I don't know how to continue. What am I doing wrong?
Comment: You are right that b) case is Binominal. The probability to meet deer number 1 is 0,4, the probability to meet deers 1 and 2 at the same time is 0,4*0,4 (events are independent). To meet deers 1, 2 and 3 is 0,4*0,4*0,4. But , because the  deers which are met is not specified, you have to count all option of choosing 3 deers out of 5 - there are $\frac{5!}{3!2!}$ such options.
Comment: What you've done in part a looks right to me, though I didn't check the arithmetic, but you don't seem to have addressed the part about $\Pr(X=Y)$.  Did you want to make another question about that?
Comment: In the assignment they specify that I only need to focus on area 1 and X. I think they added the two areas to confuse us and see if we can gather the right information from the given text.
Answer: There are $\binom 53=10$ ways to choose the $3$ deer that will be observed.  The probability that they will be observed is $.4^3$ and the probability that the other $2$ will not be seen is $.6^2$  Therefore, the probability is $$10\left(\frac25\right)^3\left(\frac35\right)^2$$

Posson and Binomic distribution


OData query for Azure Graph API?

Question: Could someone help with the OData query for the isMemeberOf API on the Azure GraphAPI
Here is the reference:
https://msdn.microsoft.com/en-us/Library/Azure/Ad/Graph/api/functions-and-actions#isMemberOf
I am looking for a sample oData query to be able to run on the demo
https://graphexplorer.cloudapp.net/Home/Index/DemoCompany
For the below scenarios:
"groupId": "5e624f44-d38d-4943-b07c-2bad078f52ff",
"memberId": "ea59e4d3-a7a1-4b5b-b65f-a25fcc0c0f99"
Wondering if it is possible to query with the group name and the memberId as below
"displayName": "SampleSecurityGroup",
"memberId": "ea59e4d3-a7a1-4b5b-b65f-a25fcc0c0f99"
Thanks in advance.
Answer: After some investigation, realized the IsMemberOf method exposed on the Graph API takes only groupId and memberId. I had to get the memberId using the display name and use it for the IsMemberOf call.

OData query for Azure Graph API?


Finding the key of a song that begins in other key

Question: Most classical musics begin in a key that matches its inital key signature, but some songs doesn't.
For example, Schubert's impromptu no. 4, op. 90 begins in A-flat minor, but its key is A-flat major, according to wikipedia or other classical music dictionaries. It begins in A-flat minor, modulates to C-flat major, then B minor (probably respelled from C-flat minor), then finally A-flat major.
How to find the key of songs like that?
P.S ) His D.774 also begins minor key, despite of major key signature. Is its key A-flat minor?
Comment: This is going to be sullied by my experience reading the sheet music of self-published works that clearly use the wrong key signature (I've even seen such disgusting things as F minor music written with an E minor key signature and too many sharps instead of flats).
Comment: Why does a piece of music have to have a single key? OK, in the classical period it was the rule, but since then anything goes, and the example of Schubert is a good one. By the way, it's not a "song" - there's no singer there!
Answer: The key of most pieces is that posted by the composer. After all, that's what they decided upon. It might well be, as in this case, the piece modulated into the parallel and relative keys, or indeed any other key that the music strayed into. But it's all really academic, and won't make much difference. Or will it? What's to be gained by considering that several bars or even a section is in fact in a different key from that quoted?
Answer: The tonica is "the place", the "save harbor", where the music resolves to, after all kinds of journeys (modulations) and tensions (e.g. dominant, subdominant).
So the end of the piece (or phrase), not the beginning, is where to look at. As you described, it resolved to A major.
The rest can be explained by, e.g.:

curiosity
"fooling" the audience a bit
esthetics
a certain logic followed (or none)
a story told musically
and so on

In terms of degrees, using small letters for minor and capital for major, the overall journey you described is:

i - III - ii - I

which creates its own atmosphere as a musical idea.
Comment: @MS-SPO - Funnily enough, I've seen way more examples of pieces being labelled as the key they begin but not end in (e.g. marches like Sousa's ["The Stars and Stripes Forever"](https://imslp.org/wiki/The_Stars_and_Stripes_Forever_(Sousa,_John_Philip)), sonata-allegros that start in a minor key and end in the tonic major, every pop song ever with a Truck Driver's Gear Change).
Comment: Thanks for your answer. Then in case of D.774, should its key be understood as A-flat minor?
Comment: I don't know D.774, but you wrote, it ends with A major chords. So key A major.
Answer: It's a pretty basic principle of the Classical style that keys are used structurally.  A piece starts in one key, travels through some contrasting keys, but completes with a satisfying return to the original one.   And that idea persists in a lot of today's popular music.   But some songs (and some symphonies) start in one key, end in another.   It's pointless to try to 'determine' the overall key when there isn't one.
But starting in A♭ minor, ending in A♭ major, the parallel major, hardly counts as not ending where it started.  Neither would ending in the relative major.  Think of it more as an extended Tierce de Picardy, the single major chord that often ends a minor-key piece.    Go with Schubert (and with Tchaikovsky in his 5th symphony 'in E minor' but which ends in E major).  Title it for the  key where the bulk of the piece resides.


Proving that two angles have the same bisector in Geometry

Question: Inside a given angle, another angle is constructed such that its sides are parallel to the sides of the given one and are the same distance away from them. Prove that the bisector of the constructed angle lies on the bisector of the given angle.
The section is on quadrilaterals and parallel lines.
We are given two angles (I called them angle ABC and angle KLM). BC is parallel to ML and AB is parallel to KL. We are also given that the sides of the constructed angle are the same distance away from the sides of the given angle.
I do not know how to go about solving this problem. Some properties we learned about parallel lines were the Z, F, and C properties. I'm thinking they may play a role in determining that each angle has the same bisector? Any ideas would be appreciated!
Comment: A diagram would be great here. According to me, construction of an angle "inside another one" with the constructed angle's sides parallel to the first one renders *exactly* the same angle, but perhaps you mean something else.
Comment: You just need to draw the bisector and extend the two inner lines and play around with the angles
Comment: Unfortunately, no picture was given. Ahmed's explanation makes sense to me. I was considering that. I'll give it a go!
Comment: Always start out by drawing such a problem.
Answer: If angle KLM is inside angle ABC, and the distance between AK is the same as the distance between CM, then the point L is equidistant from both sides AB and BC. This is the definition of angle bisector; any point on the bisector is at equal distances from each side of the angle. So point L is on the bisector of angle ABC.
Since any bisector must go through the vertex of the angle, point L lies on the bisector of KLM as well.


delete scheduled tasks fails when task identifier is account:uid

Question: I have an action set as a scheduled task that deletes a user, that seems to be working fine:
<code>{ "rules_delete_unregistered_user" : {
    "LABEL" : "Delete unregistered user",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user" : { "label" : "user", "type" : "user" } },
    "ACTION SET" : [ { "entity_delete" : { "data" : [ "user" ] } } ]
  }
}
</code>
and I also have a rule, that should delete this action set, but it fails:
<code>{ "rules_user_accepted" : {
    "LABEL" : "user_accepted",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "user_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "account:field-accepted" ], "value" : "1" } }
    ],
    "DO" : [
      { "schedule_delete" : {
          "component" : "rules_delete_unregistered_user",
          "task" : [ "account:uid" ]
        }
      }
    ]
  }
}
</code>
now I do not have any idea what should I use as a task identifier to delete that action set.
EDIT:
the rule that schedules the action set:
<code>{ "rules_create_new_user_after_registration_form" : {
    "LABEL" : "create_new_user_after_registration_form",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "new user based on webform" ],
    "REQUIRES" : [ "webform_rules", "rules", "php", "rules_scheduler" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form-id" ],
          "selected_webform" : { "value" : { "webform-client-form-104" : "webform-client-form-104" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_field_lastname" : "[data:lastname1-value-raw]",
            "param_field_firstname" : "[data:firstname-value-raw]",
            "param_name" : "[data:email-value-raw]",
            "param_mail" : "[data:email-value-raw]"
          },
          "PROVIDE" : { "entity_created" : { "new_user_request" : "new_user_request" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "user",
            "property" : "uid",
            "value" : [ "new-user-request:uid" ]
          },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched entity" } }
        }
      },
      { "schedule" : {
          "component" : "rules_delete_unregistered_user",
          "date" : { "select" : "site:current-date", "date_offset" : { "value" : 60 } },
          "param_user" : [ "user-fetched:0" ]
        }
      }
      }
    ]
  }
}
</code>
this actually works fine.
Answer: If you go to /admin/config/workflow/rules/schedule you will see a table of your scheduled components. One of the columns in that table is the task identifier - that's the string you will have to use to delete the scheduled task. You didn't post any details related to the scheduling, so I don't know what you used as a task identifier. The task identifier is necessary because one component may be queued to execute many many times, each time with a different identifier. The component name is not unique. The task identifier is.
Comment: I edited my question with the rule that schedules the action set.
Answer: Anonymus was right I did not provide identifier, so I had to update the rule, and now it is working:
<code>{ "rules_create_new_user_after_registration_form" : {
    "LABEL" : "create_new_user_after_registration_form",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "new user based on webform" ],
    "REQUIRES" : [ "webform_rules", "rules", "php", "rules_scheduler" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : [ "form-id" ],
          "selected_webform" : { "value" : { "webform-client-form-104" : "webform-client-form-104" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_field_lastname" : "[data:lastname1-value-raw]",
            "param_field_firstname" : "[data:firstname-value-raw]",
            "param_name" : "[data:email-value-raw]",
            "param_mail" : "[data:email-value-raw]"
          },
          "PROVIDE" : { "entity_created" : { "new_user_request" : "new_user_request" } }
        }
      },
      { "entity_query" : {
          "USING" : {
            "type" : "user",
            "property" : "uid",
            "value" : [ "new-user-request:uid" ]
          },
          "PROVIDE" : { "entity_fetched" : { "user_fetched" : "Fetched entity" } }
        }
      },
      { "schedule" : {
          "component" : "rules_delete_unregistered_user",
          "date" : { "select" : "site:current-date", "date_offset" : { "value" : 60 } },
          "identifier" : [ "new-user-request:uid" ],
          "param_user" : [ "user-fetched:0" ]
        }
      }
      }
    ]
  }
}
</code>


Is there a simple proof that elements of $\mathbb{Z}_n$ are unit multiples of each other if and only if they have the same gcd with $n$?

Question: That is $b=ua$ with $u\in\mathbb{Z}_n^*$ if and only if $(a,n)=(b,n)$. It is easy enough to prove the forward direction using the Bezout identity, and easy enough to find the requisite unit in practice by solving $ax\equiv b\pmod n$. Dividing out the $\gcd=d$, we can solve $(a/d)x\equiv b/d\pmod{n/d}$ because $a/d$ is a unit modulo $n/d$, and then select a unit modulo $n$ from the $d$ solutions $x=x_0+t\,n/d$ with $t=0,\dots,d-1$. What is hard is to prove that there is always a unit modulo $n$ among them. Not all of them are, $8\equiv2\cdot4$ modulo $12$ does not work, but $8\equiv5\cdot4$ does.
The above construction does show that if $(a,n)=(b,n)$ then $b=xa$ and $a=yb$, so $a$ and $b$ are "associates" in the terminology of Anderson et al., and generate the same ideal in $\mathbb{Z}_n$. However, the only proof I know that they are "strong associates", i.e. $b=ua$ with a unit $u$, is rather involved, see In $\mathbb{Z}/(n)$, does $(a) = (b)$ imply that $a$ and $b$ are associates? It uses the above ideal, reduction to prime powers and Chinese remainder theorem. Is there a proof that uses elementary properties of gcd and modular arithmetic? For example, a direct proof that if $(x_0,m)=1$ then $(x_0+tm,md)=1$ for some $t=0,\dots,d-1$?
Comment: See [here](https://math.stackexchange.com/a/647665/242). $ \ \ $
Answer: Below is a simple proof of the title claim. The idea for the `hard' direction is due to @BillDubuque, see his answer in Prove: If $\gcd(a,b,c)=1$ then there exists $z$ such that $\gcd(az+b,c) = 1$. A key observation, apparently, goes back to Stiltjes: if two numbers split the prime factors of $n$ disjointly then their sum is relatively prime to $n$. Other proofs in that thread, and in Show that if $a$, $b$, and $c$ are integers such that $(a, b) = 1$, then there is an integer $n$ such that $(an + b, c) = 1$, can also be adapted.
Proof: Suppose $b=ua$ with a unit $u$, then $(u,n)=1$. By the Bezout identity twice, $1=xu+yn$ and
$$(a,n)=sa+tn=sa(xu+yn)+tn=(sx)b+(say+t)n.$$
Therefore, any common divisor of $b$ and $n$ divides $(a,n)$, and, in particular, $(b,n)\mid(a,n)$. By a symmetric argument, $(a,n)\mid(b,n)$, so $(a,n)=(b,n)$.
Conversely, suppose $(a,n)=(b,n)=:d$, then $(a/d,n/d)=(b/d,n/d)=1$, and $a/d,\,b/d$ are both units modulo $n/d$. Let $x_0$ be a solution to $(a/d)x\equiv b/d\pmod{n/d}$, for example $x_0=(a/d)^{-1}b/d$. Then $x=x_0+t\,n/d$ are solutions to $ax\equiv b\pmod{n}$. Note that $(x_0,n/d)=1$, as $x_0$ is the product of units modulo $n/d$.
We need to find $t$ such that $(x,n)=1$, then $u=x$ will be the required unit. To do so, choose $t$ to be the product of all prime factors that divide $n$ but not $n/d$ or $x_0$. If there are no such factors choose $t=1$. Since $(x_0,n/d)=1$ and $t$ can only have factors not in both, $(x_0,t\,n/d)=1$. If a prime $p\mid(x,n)$, then, in particular, $p\mid n$. By construction of $t$, we have $p\mid x_0$ or $p\mid t\,n/d=x-x_0$. Since also $p\mid x$ it must divide both, contradiction. Thus, no such $p$ exists and $(x,n)=1$ as required. $\square$
The proof also tells us when $x_0$ would already work. We need $t=d$ for that, and so $d$ must be relatively prime to both $n/d$ and $x_0$. In other words, $d$ must split $n$ into relatively prime divisors and $x_0$ must be relatively prime to $n$.
Comment: You don't need the Bezout theorem for the first implication. Euclid's lemma is enough. That is, if $x\mid yz$ and $\gcd(x,y)=1$, then $x\mid z$.


linq to sql insert when record is already present

Question: I have an object that has a property called ObjectID that maps to the primary key of a table in the DB.
What happens if you do a linq-to-sql insert and attempt to do an insert with an object with an ObjectID already present in the DB?
Thanks.
Comment: You'll get a message like this `Violation of PRIMARY KEY constraint 'PK_some_key'. Cannot insert duplicate key in object 'someTable'. The statement has been terminated.`
Answer: after test:
if the entity you trying to insert new to the datacontext even if the primarykey value already exists it will insert a new entity with new ID
if the entity you trying to insert is pulled from the same datacontext then it will throws this exception Cannot add an entity that already exists.
anyway you can try it by yourself to insure this.


Large Files in File Upload control taking very long time to send the request

Question: I am implementing progress bar functionality to file upload control, I've noticed is that going into any event handler after browsing to a large file, takes a long time, even if the handler's code has nothing to do with the upload. I'm not really sure how the FileUpload control works, but it seems as if some copying is going on before it even gets to my handler.
Can anybody explain me what is happening there and how can i reduce the sending time of post request.
Comment: Can you please explain, what kind of event handler you are talking about ? And copying has nothing to do with uploading !!
Comment: its simple click event, it take long time to post the data, if file selected by fileuploader control is small like 20 kb it take 4-5 sec, and if i select larger file like 2 mb it takes about 1 minutes
Comment: then i guess its an internet speed issue. Its the same for me as well. I do face this issue while uploading 2 MB file.
Answer: You can't use a FileUpload control for what you want to do. When a user POSTs a file, you have to think of it like a querystring parameter. It goes as one Http Request. If you want to do a progress bar you'll want to look into something that can interact with the server asynchronously.
Comment: Thanks for help, why the way it works fine on VS web server and my local IIS, but i think i have to find new way to implement progress bar for file uploader :/
Comment: It's undoubtedly related to network speed or possibly computer speed if the server is slow.
Answer: For large files you have to upload asynchronously. You can use the AJAX control tool kit to do that.
Go to this link and download the toolkit.
 AJAX Control Tool Kit


A continuous function on $S^1$- unit circle .

Question: $$S^1=\{z\in \mathbb C : |z|=1\}$$  be the unit circle. Then which of the following  is  false $?$
Any continuous function  from $S^1$ to $\mathbb R$ is
A. bounded
B. uniformly continuous.
C. has image containing a non empty open subset of $\mathbb R.$
D. has a point $z\in S^1$  such that  $f(z)=f(-z)$
Since $S^1$ is compact any continuous function would be bounded  or  uniformly  continuous so  $A$  and $B$  are  correct.
For $C$, the  constant  function  does not have any open interval in its image. Thus, $C$ is the false statement.
That leaves $D$ to be correct. How can I prove the existence of a point $z$ having properties  like  said  in $D$?
Comment: You can find related results with the Borsuk-Ulam theorem : https://en.wikipedia.org/wiki/Borsuk%E2%80%93Ulam_theorem
Comment: Think about the intermediate value theorem.
Answer: You prove D by the intermediate value theorem, used on the function
$$
g(z)=f(z)-f(-z)
$$
Pick a $z_0\in S^1$, and evaluate $g$ there. If you get $0$, then you're done. If not, then $g(z_0)=-g(-z_0)$, so $g$ changes sign. That means there must be a zero somewhere, and that somewhere is the $z$ you're looking for.
Answer: $S^1$ is compact hence every continuous function on it is bounded and uniformly continuous. Certainly, the image of a constant function consists of one point only. As for the last one, have you heard about the intermediate value theorem?
Answer: $D$ is true.
Proof:
Define the function $g:S^1\rightarrow \mathbb{R} \mid g(x)=f(x)-f(-x)$.
Note that $g(S^1)\subset \mathbb{R}$ is convex, then $\forall x\in S^1,(\frac{1}{2}g(x)+\frac{1}{2}g(-x))\in g(S^1).$ Now $(\frac{1}{2}g(x)+\frac{1}{2}g(-x))=0\in S^1$, then exist $ y\in S^1 \mid g(y)= 0$.


SQL query for many-to-many self-join

Question: I have a database table that has a companion many-to-many self-join table alongside it. The primary table is part and the other table is alternate_part (basically, alternate parts are identical to their main part with different #s). Every record in the alternate_part table is also in the part table. To illustrate:
`part`

| part_id | part_number | description |
|---------|-------------|-------------|
|       1 |    00001    |    wheel    |
|       2 |    00002    |     tire    |
|       3 |    00003    |   window    |
|       4 |    00004    |     seat    |
|       5 |    00005    |    wheel    |
|       6 |    00006    |     tire    |
|       7 |    00007    |   window    |
|       8 |    00008    |     seat    |
|       9 |    00009    |    wheel    |
|      10 |    00010    |     tire    |
|      11 |    00011    |   window    |
|      12 |    00012    |     seat    |

`alternate_part`

| main_part_id | alt_part_id |
|--------------|-------------|
|            1 |           5 | // Wheel
|            5 |           1 | // |
|            5 |           9 | // |
|            9 |           5 | // |
|            2 |           6 | // Tire
|            6 |           2 | // |
|          ... |         ... | // |

I am trying to produce a simple SQL query that will give me a list of all alternates for a main part. The tricky part is: some alternates are only listed as alternates of alternates, it is not guaranteed that every viable alternate for a part is listed as a direct alternate. e.g., if 'Part 3' is an alternate of 'Part 2' which is an alternate of 'Part 1', then Part 3 is an alternate of Part 1 (even if the alternate_part table doesn't list a direct link). The reverse is also true (Part 1 is an alternate of Part 3).
Basically, right now I'm pulling alternates and iterating through them
SELECT p.*, ap.*
FROM part p
INNER JOIN alternate_part ap ON p.part_id = ap.main_part_id

And then going back and doing the same again on those alternates. But, I think there's got to be a better way.
The SQL query I'm looking for will basically give me:
| part_id | alt_part_id |
|---------|-------------|
|       1 |           5 |
|       1 |           9 |

For part_id = 1, even when 1 & 9 are not explicitly linked in the alternates table.
Note: I have no control whatever over the structure of the DB, it is a distributed software solution.
Note 2: It is an Oracle platform, if that affects syntax.
Answer: You have to create hierarchical tree , probably you have to use connect by prior , nocycle query
something like this
select distinct p.part_id,p.part_number,p.description,c.main_part_id
from part p
left join (
            select main_part_id,connect_by_root(main_part_id) real_part_id
            from alternate_part
            connect by NOCYCLE prior main_part_id = alternate_part_id
        ) c
on p.part_id = c.real_part_id and p.part_id != c.main_part_id
order by p.part_id

You can read full documentation about Hierarchical queries at http://docs.oracle.com/cd/B28359_01/server.111/b28286/queries003.htm

SQL query for many-to-many self-join


C# application where to find data source/database tables used in a program with search

Question: I have inherited a C# application that somehow saves/saved data sometime ago. I am fairly new to Visual Studio IDE and C# in general, and I have been given the task of finding where in our database this program saves data to. Any idea on how to proceed as I don't seem to be able to find out how this program interacts and saves data to my database?
Answer: I recommend that you set breakpoints and run the application and walk through the code using the Visual Studio debugger.
There are a lot of resources covering debugging in Visual Studio. You might start with https://msdn.microsoft.com/en-us/library/sc65sadd.aspx
Comment: Thank you for the reply. If i know what DB tables to search for, is there anyway to do a thorough search of the entire project for a table e.g. KX_SUPPORT, since somewhere in the application, it should be referencing a table that it wants to save data to depending on the input from the user.


How can I trace the source of ConfigurationManager.AppSettings?

Question: I have the following code on my AppModel base class:
        public string GetParameter(string key)
        {
            //Allow local config file to override DB setting
            string retval = ConfigurationManager.AppSettings[key];

            if (!string.IsNullOrEmpty(retval))
            {
                Trace.TraceInformation("{0} from ConfigurationManager.AppSettings is '{1}'", key, retval);
                return retval;
            }

            //No setting in config file - check for ProfileParameter from DB
            Parameters.TryGetValue(key, out retval);
            Trace.TraceInformation("{0} from ProfileParameter is '{1}'", key, retval);
            return retval;
        }

I see a parameter value in my Excel Addin is coming from ConfigurationManager.AppSettings but I have no idea where it is finding the parameter - what is the path to the config file that ConfigurationManager is using ? Is there a way to ask ConfigurationManager for the source of its knowledge ?
Comment: When an application is compiled, the app.config becomes .config but I am building an Addin for Excel - should it be EXCEL.exe.config ?
Comment: `ConfigurationManager.AppSettings` refers to the `app.config` which should be present in the root folder of your project (ie, where all the other *.cs files are present)
Comment: To repeat "Is there a way to ask ConfigurationManager for the source of its knowledge ?"
Answer: When a config object value is created in VS (Settings > Add new item), it is assigned a default value (which is equal to the value on creation).
When the config file is not found/not load/etc, that default is used.
Have a look in your Settings.Designer.cs file of your project for the attribute global::System.Configuration.DefaultSettingValueAttribute above your setting.
Example of the settings in a Testing project:
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("This is my default string value")] // << This is what you are looking for
public string TestSetting
{
  get
  {
    return ((string)(this["TestSetting"]));
  }
}

[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("False")]  // << This is what you are looking for
public bool AnotherSetting
{
  get
  {
    return ((bool)(this["AnotherSetting"]));
  }
  set
  {
    this["AnotherSetting"] = value;
  }
}

Comment: There are 2 ways to do configuration out of the box that I am aware of: 'Settings' which you describe are accessed through Properties.Settings.Default which I am not currently using (tracking down the actual config file and having to call Properties.Settings.Default.Upgrade() gives me a headache !); the alternative is creating an App.Config with  elements which is turned into .config when the application is compiled and accessed via ConfigurationManager.AppSettings and is (as far as I know) not subject to the roaming complications


How is $K \subset G_{\alpha_1} \cup \cdots \cup G_{\alpha_n} $, where $G_\alpha$'s are the open subsets of X corresponding to open subsets of $Y$?

Question: Suppose $K\subset Y \subset X$. Then, $K$ is compact relative to X  $\textit{iff}$ $K $ compact relative to Y.
Solution: The proof in the Rudin goes like this:

In this proof, I understand that there exist some $G_{\alpha}$ for each $V_{\alpha}$ but how to reach to the fact that $K$ is subset of finite collection of these $G_{\alpha}$'s and not other open sets in $X$ (or RHS of (22) is the open cover of $K$). Eq. (22)  is what I don't understand.
Problem rephrase (Edit): For a set to be compact, we have to show that every open open cover of $K$ contains finite subcover. i.e. If ${G_{\alpha}}$ is an open cover of $K$ , then there are finitely many indices $\alpha_1,\cdots,\alpha_n$ such that $K \subset G_{\alpha_1} \cup \ldots \cup G_{\alpha_n}$. Now, we have proven that there are some open sets in $X$ correspoding to each $V_{\alpha}$. How do we make sure that these $G_{\alpha}$ form an open cover?
[This the from rudin's book section-2.33]
Answer: It's the definition of compactness relative to $X$ that whenever we have that $K$ is covered by a collection of open sets (relative to $X$), i.e. $K \subset \cup_\alpha G_\alpha$ (see def 2.31), then it is covered by finitely many of them, so as per 2.32 we have finitely many indices $\alpha_1,\ldots,\alpha_n$ such that $K \subset G_{\alpha_1} \cup \ldots \cup G_{\alpha_n}$.
So that step is just applying the definitions that were just given. It's the same formula as in 2.32.
Because we want to show that $K$ is compact relative to $Y$ we start with an open cover of $K$ by open sets relative to $Y$ (and we need a finite subcover of those open sets); these are the $V_\alpha$. Because the assumption on $K$ is compactness relative to $X$ we need to go from the $V_\alpha$ to the corresponding $G_\alpha$ (which are open relative to $X$). Because the open sets are related by $G_\alpha \cap Y = V_\alpha$ we can use the finite cover for the corresponding cover to go back to the original cover $V_\alpha$. If we'd use other open sets we would lose this connection.
We know that $K$ is covered by the finitely many $V_{\alpha_i}$. So if $x \in K$, we know that $x \in V_{\alpha_{i(x)}}$ for some $i(x) \in \{1,\ldots,n\}$. We know by assumption that $x \in Y$, as $K \subset Y$. So $x \in V_{\alpha_{i(x)}} \cap Y = G_{\alpha_{i(x)}}$. As this works for any $x$, $K$ is covered by the $G_{\alpha_1},\ldots,G_{\alpha_n}$ for the same indices that work for the $V_\alpha$.
Comment: That I understand but look at $G_{\alpha} $,  these are obtained from $V_{\alpha} $ and I don't understand why $G_{\alpha} $ should be the open cover and not any other open sets in X. It's not the finiteness but the specific set of $G_{\alpha} $ that's bothering me.
Comment: @MUH added an extra explanation, which I hope helps.
Comment: We have to prove that this condition is necessity (not that we are doing it to maintain the required connection), only then we will be able to prove that $K$ is relatively open in $Y$. I am rephrasing the question again so that you have a better idea of my doubt.
Comment: For a set to be compact, we have to show that every open open cover of $K$ contains finite subcover. i.e. If ${G_{\alpha}}$ is an open cover of $K$ , then there are finitely many indices $\alpha_1,\cdots,\alpha_n$ such that $K \subset G_{\alpha_1} \cup \ldots \cup G_{\alpha_n}$. Now, we have proven that there are some open sets in $X$ correspoding to each $V_{\alpha}$. How do we make sure that these $G_{\alpha}$ form an open cover?
Comment: @MUH added some more explanation why they cover.
Comment: I think this has pretty much cleared my doubts. Cheers


Dimension formula for exact sequence of finite dimensional k-vector space

Question: I have two questions regarding the following problem and the solution to it.

Let $k$ be a field and $0 \to M_0 \to ... \to M_n \to 0$ be an exact sequence of finite dimensional $k$-vector spaces and $k$-linear maps. Prove that $\sum_{i=0}^n (-1)^i \dim_k(M_i)=0$.
Solution: Denote $d_i$ for the map $d_i: M_i \to M_{i+1}$. The long exact sequence splits into short exact sequences $0 \to \ker(d_i) \to M_i \to \operatorname{im}(d_i) \to 0$. By using the dimension formula for linear maps of finite dimensional vector spaces and the fact $\ker(d_{i+1})= \operatorname{im} (d_i)$, we conclude that $\dim(\ker(d_{i+1}))+\dim(\ker(d_{i}))=\dim(M_i).$
Thus, $\sum_{i=0}^n (-1)^i \dim_k(M_i)=\dim(\ker(d_{0}))+\dim(\ker(d_{n+1})=0$.

1.) How do they come to the short exact sequence above in the solution? Shouldn't the short exact sequence be $0 \to \ker(d_{i-1}) \to M_i \to \operatorname{im}(d_i)$?
2.) Why is $\dim(\ker(d_{0}))+\dim(\ker(d_{n+1}))=0$
Everything else I have understood, so far, but I don't get these two points.
It would be great if someone could explain this to me.
Thanks!
Answer: 1) No. It comes from the canonical decomposition of a homomorphism:
$$\begin{matrix}\ker d_i\hookrightarrow M_i&\xrightarrow[\qquad\quad]{d_i}&M_{i+1}\\[-21ex]
&\searrow\qquad\nearrow\\
&\operatorname{im}d_i
\end{matrix}$$
2) Simply because $\ker d_0=\{0\}$, and $d_{n+1}$ doesn't really exist: its domain would be $\{0\}$, hence if we take it to have codomain any vector space, say $\{0\}$ to make it simple, anyway its kernel has dimension $0$.
Comment: Great, thanks for the answer! It helped me a lot :)


Custom Widget revising animation in gridview

Question: I have a custom widget that changes color when tapped inside a gridview. When I scroll to the bottom and scroll back up to the top selected widget its animation is reversed.
I'm pretty sure that it has something to do with the widget being disposed of when out of view but I don't have a solution to overcome it. See my code below:
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Thirty Seconds',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

// Page with the gridview
class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.count(
        crossAxisCount: 2,
        children: List.generate(20, (index) {
          return MyCustomWidget(
            key: GlobalKey(),
            index: index + 1,
          );
        }),
      ),
    );
  }
}

// Custom Widget
class MyCustomWidget extends StatefulWidget {
  const MyCustomWidget({
    super.key,
    required this.index,
  });

  final int index;

  @override
  State<MyCustomWidget> createState() => _MyCustomWidgetState();
}

class _MyCustomWidgetState extends State<MyCustomWidget>
    with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<Color?> _colorAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );
    _colorAnimation = ColorTween(begin: Colors.white, end: Colors.yellow)
        .animate(_animationController)
      ..addListener(() => setState(() {}));
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  void _toggleAnimation() {
    if (_animationController.isCompleted) {
      _animationController.reverse();
    } else {
      _animationController.forward();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        _toggleAnimation();
      },
      child: Container(
        color: _colorAnimation.value,
        child: Center(
          child: Text("Custom Widget ${widget.index}"),
        ),
      ),
    );
  }
}

Answer: GridView dispose the widget that aren't visible on UI. You can use cacheExtent(not suitable for this case) or AutomaticKeepAliveClientMixin on _MyCustomWidgetState.
class _MyCustomWidgetState extends State<MyCustomWidget>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);

You may prefer handing it parent widget and passing a bool to check active state or state-management or project level depends on scenario.


Show that the distance between vectors is even

Question: Consider two vectors $(a_1, \dots, a_n), (b_1, \dots, b_n) \in \{0,1\}^n$ such that they both contain an even amount of ones. Is there an easy way to see that the set
$\{i: a_i \neq b_i\}$ has even order? I.e., the two vectors are different in an even amount of positions.
I proved it by induction, but I'm looking for something simpler and more intuitive. Thanks.
Answer: $\newcommand{\1}{\mathbf{1}}$One possibility: let $\1$ denote the vector where each component is $1$. Note that a binary vector has an even number of $1$'s iff the sum of its elements is even (congruent to $0$ mod $2$). Thus $$\1^T \mathbf{a} \equiv 0\pmod{2}\quad\text{and}\quad \1^T\mathbf{b} \equiv 0\pmod{2}.$$ Hence $$\1^T(\mathbf{a} - \mathbf{b}) \equiv 0\pmod{2},$$ so the vector $\mathbf{a} - \mathbf{b}\in\{0,1\}^n$ (using mod $2$ arithmetic) has an even number of $1$'s. This means that $\mathbf{a}$ and $\mathbf{b}$ differ in an even number of places. (You can show that $a_i - b_i \equiv 1 \pmod{2}$ iff $a_i\ne b_i$, for $a_i,b_i\in\{0,1\}$.)
Comment: Thanks. This answer was very clear!
Answer: Let $A$ be the total number of $1$s between the two vectors, (i.e., $wt(\vec{a}) + wt(\vec{b})$), which is even since both vectors have an even number of ones. The positions where $\vec{a}$ and $\vec{b}$ both have a $1$ consume an even number $B$ of $1$s (one in each vector). So the total number of $1$s in one vector where the other vector has a zero in the corresponding position is $A-B$, which is even. This is exactly the number of positions where the two vectors differ.
Answer: Let $w({\bf a})$ be the weight (number of ones) of the binary vector ${\bf a}$
Then, operating in modulo 2, ${\bf c}={\bf a}+{\bf b}$ has ones in the positions where  ${\bf a}$,${\bf b}$ differ, zero otherwise. We are interested in the parity of $w({\bf c})$.
But $w({\bf a}+{\bf b})=w({\bf a})+w({\bf b}) -2 k$ where $k$ is the number of indexes where $a_i=b_i=1$.
Hence, if both $w({\bf a})$,$w({\bf b})$ are even, so is $w({\bf c})$.


Choosing response and predictors

Question:
Information on the Girth (), Height () and Volume () for 31 cherry trees
yielded the following correlations : $r_{12}$ = 0.519,  $r_{23}$= 0.598 and  $r_{13}$= 0.967. If you were asked to setup a regression choosing a certain characteristic as the response
and the other two as predictors, which characteristic will you choose as the
response? Give your comments.

I think we choose Girth and Height as predictors for the response Volume because the correlation between Girth and Height is the least, so we're looking at how these individually affect the Volume (i.e. the factor with which their correlation is more than that between them).
Is my reasoning correct?
This question was asked in the final examinations of the course on Multivariate Data & Linear Models and it had 10 marks. What more should I write?
Comment: All three answers can be justified: as far as regression modeling is concerned, what aspect of a tree "affects" some other has no meaning.  Indeed, even in the real world it isn't plausible to claim that any of these variables directly affects the others: they are all consequences of the *size* and *shape* of the tree.  But, in practice, which of the three variables do you think might be the most difficult to measure in living trees?
Comment: It is also interesting to note that a routine regression analysis would also consider the interaction term.  When using girth and height as the regressors with an interaction, then (assuming the trees have similar shapes) you will get near-perfect fits for the volume, because that's essentially proportional to the interaction (girth times height).  *Even if your objective is to predict girth or height from the other two variables,* this insight can lead you to a far better model than otherwise.  (It will be either nonlinear or linear in the logarithms.)
Comment: @whuber the volume
Answer: I might argue that it makes sense for volume to be the response, and then you can use direct measurements of how tall and wide a tree is in order to predict the volume (which is probably harder to measure).
However, we use regressions to predict or explain. If we want to predict or explain differences in girth, we would use girth as the response. If we want to predict or explain height, we would use height as the response. If we want to predict or explain volume, we would use volume as the response.
In all three cases, the other two variables are viable predictors.
I do not see the correlations between the marginal variables playing any role. If I wanted to measure volume and girth ($r=0.967$) in order to predict height, I would be totally comfortable doing so. One might argue that it might be worth it to drop one of those correlated predictors in order to have fewer parameters without losing much in terms of predictors (since the volume and girth have such a high correlation). While I understand this stance, it is not so simple.
Answer: Predictors with high correlation are more linearly dependent. So they have a similar effect on the dependent variable. Thus doesn't make sense to use Height as the response. Choosing between Girth and Volume it seems more logical to use Volume. As you mentioned in the answer to @whuber, the volume might be the most difficult to measure in living trees.
Comment: Your logic fails at the first step, because correlated predictors do not necessarily have a "similar effect" on the dependent variable.  For instance, consider three *iid* random variables $(X,Y,Z)$ and set $U=X,$ $V=X+\epsilon Y,$ and $W=Y+\delta Z$ for small numbers $\delta$ and $\epsilon.$ In this case $U$ is *independent* of the response $W$ even though the predictors $U$ and $V$ are arbitrarily highly correlated.
Comment: Unfortunately, that is erroneous: two independent variables cannot be dependent!
Comment: @whuber I'm afraid I don't quite understand. In your example ***U*** and ***V*** have a similar effect on ***W***.
Comment: The point is that $V$ *alone* is associated with $W:$ $U$ has no association with $W$ at all.
Comment: But $U$ is associated with $W$, isn't it? $W$ = $V$/$\epsilon$ - $U$/$\epsilon$ + $\sigma$$Z$
Comment: $U=X$ and $W=Y + \delta Z$ are *independent* in this example.  That's the exact opposite of "associated with"!
Comment: I showed the dependence in my previous comment.
Answer: The data alone does not suggest a model, just a correlation matrix.  What is the purpose of the model, and in what conditions will it be applied?  For example, if the trees are still standing in a grove or forest, it might be useful to estimate their height, based on girth (usually measured at 48" above ground).  Of course, this is an opportunistic dataset collected from a plot of felled cherry trees, so the lumber mill model, volume ~ girth + height may be the one you want.

Choosing response and predictors


Regex to use in HTML source

Question: I need a regex to extract the number 330 on ...163&angleKreludor=330&viewID=.... This number vary from day to day...it could be an Integer with up to 3 digits, but it can be a double number like 127.57 with 2 decimal places ... so I would need to capture anything between angleKreludor= and &viewID.... Here is the complete HTML:
var swf = new SWFObject('http://images.lulaser.com/shenkuu/lunar/shenkuu_calendar_v1.swf?angleNeopia=163&angleKreludor=330&viewID=2&lang=pt', 'flash_36175654223', '550', '500', '6', '#FFFFFF');
swf.addParam('quality', 'high');
swf.addParam('scale', 'exactfit');
swf.addParam('menu', 'false');
swf.addParam('allowScriptAccess', 'always');
swf.addParam('swLiveConnect', 'true');
swf.addParam('bgcolor', 'white');
swf.write();

P.S: This is needed to use in Javascript code in Selenium IDE ... I tried in the past and Selenium IDE does not accept look-aheads nor look-behinds
Comment: Your question doesn't actually contain a single line of HTML. You have what looks like JavaScript (although it might be ActionScript), and what you're trying to parse is URL-encoded data.
Answer: You can search for digits with positive look-behind for the angleKreludor= key
(?<=angleKreludor=)(\d+)

DEMO
For JavaScript use non-captuinrg group
(?:angleKreludor=)(\d+)

var s = 'http://images.lulaser.com/shenkuu/lunar/shenkuu_calendar_v1.swf?angleNeopia=163&angleKreludor=330&viewID=2&lang=pt';
var nr = s.match(/(?:angleKreludor=)(\d+)/);
console.log(nr[1]);

DEMO
Comment: Oh I'm sorry I forgot to mention, I'm using Selenium IDE and its javascript command doest not work with look-aheads and look-behind ... I used the command: javascript{storedVars["search"].search(/(?<=angleKreludor=)(\\d+)/);} and it returned "[error] Unexpected Exception: SyntaxError: illegal character. " -- I updated the question

Regex to use in HTML source


How do you make a Vocaloid do a "hard" pronunciation for "Through"

Question: I'm working on this part of Dance With the Devil (Braking Benjamin)

I can show you that, I can see right through all your empty lies

The vocaloid synthesizer Miku that I'm working with wants to pronounce "through"  th r o-- ("soft" th and r), and I want to make th and r noticeable and have a consonant at the end to cut it off.
So...
"Th R O-- (gh)"
Instead of
"th r O--"
Comment: Is there any dialect or accent in which the _gh_ of through is pronounced?  Which consonant do you want it to have?  _F_ as in _enough?_
Answer: I believe this can be accomplished by creating an unregistered word and then directly editing the phonemes for it.
To create the desired custom pronunciation of "through", you would invent a nonsense word (say, "ZQX") and then specify the phonemes, which would be something like [Dru:] (IPA: ðɹu) plus your consonant of choice to end it.


About basic terminology: experiment, outcome, sample space, is my understanding correct?

Question:
Part 1

We could define
"tossing $1$ coin $1$ time" as an experiment $E_1$, with possible outcomes, aka, the sample space of which is $\{H,T\}$, this set has 2 elements;
"tossing $1$ coins $2$ times" as another experiment $E_2$, the sample space of which is $\{(H,H),(H,T),(T,H),(T,T)\}$, this set has 4 elements;
"tossing $2$ coins $1$ time" as third different experiment $E_3$, the sample space of which is $\{(H,H),(H,T),(T,H),(T,T)\}$, this set has 4 elements;
$E_2$ and $E_3$ are two different experiments, though they have same sample spaces.

Part 2

based on the definition of $E_1$, "tossing $1$ coins $2$ times" could also be viewed as "$2$ repetitions" or "carrying out $2$ times" of $E_1$. in this context, the sample space is $\{H,T\}$ rather than $\{(H,H),(H,T),(T,H),(T,T)\}$
Is my understanding above correct?
Comment: Usually the term "outcome" refers to an element of the sample space.  You seem to be using the term to refer to the number of coins instead, which is not the usual way the terminology is used.  This means that you are miscounting the number of "outcomes" in the usual sense.
Comment: I didn't intervene in your definition of $E_1$, but commented in my answer. You'd better correct it.
Comment: What is the "understanding" to which you refer?  What exactly are you asking respondents to give opinions about?
Answer: You've a typo in the definition of your first experiment, $E_1$. It should be tossing 1 coin 1 time. If corrected like this, the sample space is correct. Samples spaces of $E_2$ and $E_3$ are also correct, and that they are different experiments having the same sample space. If converted into $\{0,1\}$, you can find many other experiments having the same sample space, e.g. two different match scores (win/lose only) of two footballs teams.
For part 2, carrying out $E_1$ two times creates a different event having a different sample space than $E_1$'s. The elements in tuples can be $H,T$ but this doesn't mean the sample space is $\{H,T\}$. Many events can be decomposed into smaller or unit events having smaller sample spaces.
Comment: Thanks for the reminder. the example of two footballs teams makes lots of sense. the repetition in  Part 2 is used to justify a theoretical value, 50% H, for instance. according to "the law of large numbers", a huge number of repetition would produce a close estimation of true value. So, If I carry out $E_1$ billions of trillions of times. I would get nearly 50% head, in this context, the sample space is {H, T}, the probability of H is 50%. correct me please if something goes wrong.
Comment: Still, repetition of $E_1$ billions of times is another event, say $E_B$, and it has a sample space of tuples like $\{(H,T,...), (T, ...), ...\}$ (having a total of $2^B$ elements). You can devise various statistics from $E_B$ to justify that $P(H)$ is indeed $\frac{1}{2}$ with some confidence, but that's not related to the sample space of $E_B$.
Answer: Imagine you have a machine that can produce ham.
You put a pig (sorry for this pig) in this machine, and you get slices of ham.
You can get ham from this machine, but you cannot view this machine as ham.
Now, think of this machine as a function, say
y = f(x) = x^2
you can put a value in this function, x = 3 for instance, and then you get y = 9.
you can get a value from a function, but you cannot view this function as a value.
random variable is NOT a variable, it is a function
Page 72 in the book "Introduction to Probability, 2nd Edition" says:
a random variable is a real-value function of the experimental outcome
based on the above, if you view "tossing 1 coins 2 times" as "2 repetitions" of E_1, you are really tossing the coin in the real world, what you get is value, not a function.
so, the sample space is {,} for E_1.
if you are considering the set {(,),(,),(,),(,)}
you are viewing "2 repetitions" as another Experiment that has a sample space equal to this set.
in conclusion, your Part_1 is clear, your Part_2 is answerd by the paragraph above.


LWJGL 2.9 gluProject 3D to 2D

Question: So I've been playing with LWJGL 3D object coordinates to 2D screen space coordinates using GLU.gluProject, however I'm finding there to be quite a problem when the xyz of the 3D object is behind the camera. The screen space coordinates seem to be on screen twice, once for the actual potion which works fine, but again for when the object is behind, and the positions are somewhat inverted of the objects true position (camera moves left, so do the screen coordinates twice as fast as the camera).
Here's the code I'm using for 3D to 2D:
public static float[] get2DFrom3D(float x, float y, float z) {
    FloatBuffer screen = BufferUtils.createFloatBuffer(3);
    IntBuffer view = BufferUtils.createIntBuffer(16);
    FloatBuffer model = BufferUtils.createFloatBuffer(16);
    FloatBuffer proj = BufferUtils.createFloatBuffer(16);

    GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, model);
    GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, proj);
    GL11.glGetInteger(GL11.GL_VIEWPORT, view);

    boolean res= GLU.gluProject(x, y, z, model, proj, view, screen);

    if (res) {
        return new float[] {screen.get(0), Display.getHeight() - screen.get(1), screen.get(2)};
    }
    return null;
}

Another query is what the screen.get(2) value is used for, as it majorly varies from 0.8 to 1.1, however occasionally reaches -18 or 30 when the position is just below the camera, and the camera pitch is sat just above or below the horizon.
Any help is appreciated.
Answer: Points behins the camera (or on the camera plane) can never be correctly projected. This case can only be handled for primitives like lines or triangles. During rendering, the primitives are clipped against the viewing frustum, so that new vertices (and new primitives) can be generated. But this is impossible to do for a single point, you always need lines or polygon edges to calculate any meaningful intersection point.
Individual points, and this is all what gluProject handles, can either be inside or outside of the frustum. But gluProject does not care abnout that, it just applies the transformations, mirroring points behind the camera in front of the camera. It is the responsibilty of the caller to ensure that the points to project are actually inside of the viewing frustum.

LWJGL 2.9 gluProject 3D to 2D


Mean-value Theorem $f(x)=\sqrt{x+2}; [4,6]$

Question:
Verify that the hypothesis of the mean-value theorem is satisfied for the given function on the indicated interval. Then find a suitable value for $c$ that satisfies the conclusion of the mean-value theorem.

$$f(x)=\sqrt{x+2}; [4,6]$$
So,
$$f'(x) = {1 \over 2} (x+2)^{-{1\over 2}}$$
$f(x)$ is differentiable for all x. Now,
$$f'(c) = {f(b)-f(a)\over b- a} \\
= {f(6) - f(4)\over 6-4} \\
= {2\sqrt{2} - \sqrt{6}\over2}$$
Since $f'(c) = {2\sqrt{2} - \sqrt{6}\over2}$,
$${1\over 2}(c+2)^{-{1\over 2}} = {2\sqrt{2} - \sqrt{6}\over2}$$
Then after, this will give me $c$ right?
I just want to know if I did it right so far. I tried simplifying the last equation, but it wasn't right. Please let me know if there is anything wrong in my steps, if not could anyone help me solve for $c$ at the end? Thank you.
Comment: Minor error: $f(x)$ is differentiable not for all $x$, but for $x\neq -2$.
Comment: you did everything correctly. Now solve for $c$ to get $$c = \frac{3}{2} + 2\sqrt{3} \approx 4.9641$$
Comment: @vadim123 i just assumed the OP means for all $x \in (4,6)$...
Comment: I keep getting wrong answer when I solve for $c$ could you help me out? @gt6989b
Answer: You did everything correctly, let's solve for $c$ together.
You have
$$
\frac{1}{2} (c+2)^{-1/2} = \frac{a}{2}\\
(c+2)^{-1/2} = a \\
\frac{1}{\sqrt{c+2}} = a \\
c+2 = \frac{1}{a^2}
$$
so
$$
\begin{split}
c &= \frac{1}{a^2} - 2 = \frac{1}{\left(2 \sqrt{2} - \sqrt{6}\right)^2} - 2 \\
  &= \frac{1}{8 + 6 - 4\sqrt{2}\sqrt{6}} - 2 \\
  &= \frac{1}{14 - 8\sqrt{3}} - 2 \\
  &= \frac{14 + 8 \sqrt{3}}{14^2 - 3 \cdot 8^2} - 2 \\
  &= \frac{14 + 8 \sqrt{3}}{4} - 2 \\
  &= \frac{7}{2} +2\sqrt{3} - 2 \\
  &= \frac{3}{2} +2\sqrt{3}
\end{split}
$$


Why are some instruments listed 'in F' or 'in B'?

Question: I am looking through scores of pieces that I particularly like.
I can't understand (as this is the first time I have come across it) why here, in the manuscript, some instruments are named as follows:
X in B or X in F (X representing an instrument).

What does the in mean exactly? And why is it written as such? Does this have anything to do with its key?
Why do the kettledrums have a diagram with it too? In F, C, and A?

I have highlighted the sections in the image below.
Comment: Technically, that's not a "manuscript", since it's not written _by hand_. It should be called a "score" (so named because the production process traditionally involved [scoring a metal plate](https://www.youtube.com/watch?v=BvyoKdW-Big)).
Comment: The key signatures for transposing instruments will be different.  The B clarinet (in English written as Bb) instrument as example, could have a written C but will sound B-flat. This "translates" into two fewer B-s in the key signature. By the way, played 2nd bassoon on this symphony a month ago. I believe the trumpet players had C trumpets (definitely not any F trumpets), possibly transposing.
Comment: OK. I'm always willing to see what others think about the subject. It is an important point that beginners in the orchestration field may not get. (Same for lots of notation.)
Comment: Possible duplicate of [What are the practical reasons for still having transposing instruments?](https://music.stackexchange.com/questions/7225/what-are-the-practical-reasons-for-still-having-transposing-instruments)
Comment: I'm more curious why the key signature for the horns and trumpets doesn't match that of the other instruments. Shouldn't they have three flats?
Comment: The convention is that Horns, Trumpets and Timpani are written without key signatures.

You can 'prefer' manuscript all you like, but if it wasn't hand-written, it isn't one!

The original players used trumpets in F.  Modern players (unless in an 'authentic' ensemble) will use their Bb or C Trumpets, transposing accordingly.  Trumpet players are good at transposing at sight. They have to be!
Comment: @LaurencePayne why have you already answered, and yet commented on the question? Your comments here would be much more useful to a larger audience, if they were grouped together.
Comment: Perhaps I will, when all the other comments with either further questions or misleading information are in!
Comment: @cmp - you may prefer "manuscript", but that doesn't change the fact that the example is a published "score". Take the example of books: the copy that the author works on is the "manuscript" regardless of the medium & when it's published it's a "novel" or an "article", etc.
Answer: IN orchestral (and other instrumental) music, the notation like "Clarinet in Bb" (or "Klarinette in B") means that the instrument is a "transposing instrument." When the clarinetist plays what his music shows as a "C." the note comes out as a Bb. The true (or "concert") note is always one whole step below the notation. With instruments with the notation "in F" the meaning is that the concert note is a perfect fifth below the notation.
There are historical reasons for this. The main reasons are that instruments come in groups. There are clarinets in Bb, A, Eb, and C (that I know of). Each has the same fingering for its "nominal" scale. A C is a C is a C for the players even if the sounding notes are A, Bb or Eb.
Tympani (kettledrums) are tuned to the notes shown in the score. When sounded, these drums give off this note. Thus one needs only as many drums as are being played rather than one for each potential note.
Comment: @Dekkadeci - those trumpets are in fact in Bb - it's German music, which calls Bb 'B'. B translates to 'H'. A conductor worth his salt would look at the key sig. written for any possibly transposing instrument, and work out which is appropriate.
Comment: @Tim, but the trumpets in the image are clearly "Trompeten...in **F**".
Comment: Yeah, I think the real answer is in here--there are F and Bb trumpets (and Bb trumpets are so ubiquitous nowadays that I'm surprised those trumpets aren't in Bb), and the Bb and A clarinets are both fairly common. If the score didn't label which transposition of instrument was desired, the conductor could easily assign someone with the wrong instrument and get results in the wrong key.
Comment: @Dekkadeci - F trumpets were the norm in C19, being the valved versions of the old, natural F trumpet with a sounding length of about 7'. As the taste for brighter & higher trumpet parts with more active writing gained momentum, the more familiar B♭ trumpet, & later C trumpet, became more common. As their air-columns are shorter, they can be more responsive in fast passages.
Answer: Some instruments are what we call transposing instruments. For various historical reasons, these instruments are written in keys different than how they sound. A good rule to remember is:

When a transposing instrument plays a written C, it sounds its name.

In other words, when a Horn in F plays a written C, it sounds its name, or F. From this we realize that the Horn in F sounds a perfect fifth lower than it is written. So these horns that start off on a written E♭ are actually sounding the A♭ below it.
The Clarinets in B are actually in B♭. This is because of the German tradition that B is B♭ and H is B♮. But the rule is still the same: when a B♭ Clarinet plays a written C, it sounds a B♭. Since this is a major second lower than written, we know that their written B♭ sounds like an A♭.
So, a little test for you, if you want (put your cursor over the blank answer): if a Trumpet in D plays an E♭, what pitch will it sound like?

 F

When it comes to the timpani (Pauken), each individual drum is just tuned to one of those three pitches. In other words, the head of one drum is stretched such that hitting it produces an F; the other, a C; and the last, an A.
Comment: @supercat - never heard of a guitar,  concert tuned, referred to as 'in E'. Although it does transpose an octave down.
Comment: Orchestral transposing instruments play their name in response to a C note, but some other instruments are described in terms of their lowest note which might not be notated "C".  For example, a concert-pitch tin whistle would be described as being pitched in "D", and a concert-pitch guitar would be tuned in "E".
Comment: @Tim: Being "in E" would be the default, so it would rarely be mentioned explicitly [one would generally say "Standard" rather than "Standard E".  It's not uncommon, however, for guitars to be tuned down while keeping the same relative intervals ("Standard D" would be two frets own from normal); if just their lower string is tuned down while keeping the others at the same pitch, that would be called  "Drop D".  In C-pitch nomenclature, a "D" instrument would be a major second higher than usual, but a guitar tuned to "Standard D" would play a major second lower than usual.
Comment: Would you mind elaborating Richard on what you mean when you say "the drums are tuned to those three pitches"? I don't quite understand.
Comment: @cmp Timpani have pitch, and you can tune them (but only to a single pitch at a time). This is saying what pitches they should have for this piece.
Answer: Some instruments are notated as 'Transposing Instruments'   In this score we have Clarinets in Bb (the Germans use 'B' for 'Bb'), Trumpets and Horns in F.  That means that when the player reads the note C, the pitch actually played is Bb or F.  There are historical and practical reasons for this.  https://en.wikipedia.org/wiki/Transposing_instrument
The Timpani (Pauken) instruction 'F, C, A' is a bit different.  It indicates that three kettles are required, and they are initially to be tuned to F, C and A. (Timpanists call their drums 'kettles'.  It's a nice name, that is worth keeping alive I think.)
Answer: For reasons I don't quite understand, all answers up to now refer to transposing instruments, which seems more like a coincidence than the real cause. While it is true, that one could detect the necessary variant of a non-transposing instrument by analyzing the notated range, this requires detailed knowledge and is still error-prone. Note also, that notation conventions are not permanent, so tympani were once notated transposed, but are no longer today.
Stating the instrument tuning is primarily necessary to designate the required variant since there are several to choose from (in clarinet case in descending order of demand: b flat, a  and e flat). It is a well-established convention to list everything required on page one of the full score (here also instruments are listed, which don't have to play anything at the beginning, similar to a cookbook recipe, where all ingredients are also given before the explanation of how to process them), and this is repeated on the single voices for each instrument, so the player prepares accordingly.
Knowledge of the intended variant of the instrument is also helpful for interpretation, which pitch will sound, but beyond the conductor and the players of the respective instrument you will seldom find non-professionals fluently doing it. That technical advances  (as with French horn, pedal tympani) now allows quicker switching is a different topic.

At composition time of Tchaikovskys fourth symphony the double horn was not yet invented, so mentioning the type is already justified to match the original.
The reference to the possibility of mental transposition ignores the main reason for having transposing instruments at all.

See also this question fore background and note, that different movements may ask for different types (at least chamber music occasionally surprises our clarinet player).
Comment: Quite a lot wrong there I'm afraid @guidot.  A Clarinet is lower than Bb Clarinet, but Eb clarinet is higher.   A 'double' French Horn does indeed consist of a F Horn and a Bb Horn, but no 'set up' is required, the switch is instantaneous with a thumb-operated valve and a player may well choose different 'sides' of the instrument for different notes in a passage of music. There are a few instruments that have a pitch name but DON'T transpose - Eb, F and C Tubas, also Bb Trombones all read concert pitch bass clef (in the orchestra at least) - but most instruments with a pitch name do transpose.
Comment: Wouldn't have thought a clarinettist would give much thought to pitches, beyond using a Bb clarinet when the dots were for that, or an A clarinet when they were written to compensate for that.
Comment: @LaurencePayne Your comment seems to have missed, that I related to clarinet's frequency of use, not sound. I also did not claim, that all named instruments do transpose, but the first paragraph expresses my surprise, that other answers focus on transposing instruments.


Fail to enable mod_rewrite on my apache server

Question: This is how my apache httpd file looks like:
LoadModule rewrite_module modules/mod_rewrite.so

<Directory / >
Options FollowSymLinks
AllowOverride ALL
Order allow,deny
allow from all
</Directory>

Now i try to execute this simple mod rule:
RewriteEngine on

RewriteRule ^product-([0-9]+)\.html$ index.php?id=$1

This rewrite should happen when i press this link:
 Press me

Answer: if you put your rewrite rule in the apache config you will need a leading / after the ^(not needed for htaccess).  Try the rule with out ^ to see if it matches.  I have also had some servers/vhosts where I needed to add RewriteBase rewrite would work.
Comment: If you have time you might want to try playing around with both.  ^ is start of string.  You can try replacing ^ with ^/ to see if that works.
Comment: That has worked. very strange..why did the ^ interfer? or was it the RewriteBAse that did the job


Is there any jackson json strategy (using annotations or another way), that will execute some logic prior and post deserialization of field?

Question: I need to execute some code after each deserialization is done on a POJO's fields. Is there any way I can do this through some jackson annotation (or other) strategy?

One way to go with this is create a custom deserializer for each field type that will implement PostLogicDeserializerInterface or extend some PostLogicDeserializerAbstract. But this will make loads of cluttering code that will be hard to maintain (instead of just using @JsonProperty). So I think this is not a good idea.
I saw that you can use @JsonDeserialize on class level but only for value classes. From the documentation:

When annotating value classes, configuration is used for instances of the value class but can be overridden by more specific annotations (ones that attach to methods or fields).

So I think this won't work, either.

Using some custom logic in the POJOs setter methods is a bad practice! And on the other side, I think jackson uses reflection to set the fields anyway... Not a good strategy, neither.

My goal is to determine the percentage of fields that were set by the deserializer. I would need to have a counter that will increase on each invoked deserialization (populated field). And once the whole class(POJO) deserialization is over, I would need to execute some logic using reflection.
The way I have that implemented now, is

once I have the POJO deserialized by the jackson mapper, I go through each field using reflection
check if it has been set, f.i. if it is null or -1 for primitive numbers (previously initial values). (one conn of this approach is that you can't check a boolean if it was set)
use reflection for some other kind of checking (lets call it logic X)
execute logic that depends on percentage of set fields and logic X.

I would prefer some jackson strategy, since I wouldn't need to check the POJO with reflection. It would rather be done in place (at the time the POJO gets deserialized).
Cheers,
Despot
Answer: There isn't any specific feature to do post- or pre-processing at this point; and this sort of gets close to boundaries of what data binding should do.
If I had to do this for specific fields, I would probably just add it in setter, since that is simple thing to do and works; but requires same logic in all relevant setters.
@JsonDeserialize can also be used for individual properties (field, setter), so you could create a custom deserializer: and since you want post-processing, you could just locate "real" deserializer (ideally by making JsonDeserializer implement either ContextualDeserializer or ResolvableDeserializer -- this may not matter here, but for general case it's done here to avoid problems with cyclic dependencies), delegate to it, and modify value. This assumes it is value you care about more than field.
Finally, there are also ways to modify BeanDeserializer instances (by registering BeanDeserializerModifier) -- you could sub-class relevant components (SettableBeanProperty I think...) to hook in additional handling, or even replace deserializer to use, keeping a reference to the original "default" deserializer.
But in the end, your case sounds like something that may be best handled by something else: for example Bean Validation API (jsr-303) seems like a potentially good match for post-processing logic. Since it is somewhat orthogonal to data binding, it could be a superior alternative since it would be independent of data binding (jackson), reusable, all the good stuff.
Comment: I am not sure if, by using Bean Validation API (jsr-303), it is possible to create logic on each invocation of a setter method (update an instance field like a counter) and on end of deserialization doing some other logic. As far as I could see, this specification only allows (and is intended for) validation purposes. Any other suggestions?
Comment: Correct: can't do it on sets, so re-reading your use case, it wouldn't really work. I think BeanDeserializerModifier might then the way to go -- it does require bit elaborate code on changing SettableBeanProperty instances (which do actual per-field work), but it would be place to add more work, as you know property in question, value being set. But you would be able to reuse existing code for actual data binding.
Answer: Another way is to use @JsonCreator to mark a constructor which will receive the data. Inside the constructor, you have full control over how to assign them to fields.


Move SVN repository without svnadmin dump/load

Question: I have a huge server Subversion repository which I should move to an external mounted partition. Of course there are possibility to make svnadmin load / dump or svnadmin hotcopy, but in my situation it could take a lot of time, because of the size of the repository.
Could I avoid this stage and just to move the whole folder to new partition without to break any internal relations to the system location ?
I would like to do something like :
mv /path/repository /other_path/repository

I like this possibility with local client's repository, and it will help a lot, if such operation could be done with server repository also.
Comment: Yes, exactly. For me it's the same. Changing the absolute location on the filesystem of the server.
Comment: I just wanted to mention that the path changes
Answer: Yes, you can move it if you make sure that nobody accesses the repository while you're moving it.
Keep in mind: this might render existing working copies invalid, users might need to do a svn switch --relocate so that their working copies point to the new location.
Comment: Thanks. Yes, of course, I will stop the vhost of the current repository during copy. Normally, it will be on the same server, so it's the same URL for the user, all the configuration will be changed in Apache's configuration, so normally don't need to relocate.
Comment: Works fine, tested. No relocate need in our case. Thanks again.
Answer: In theory yes, everything related to your SVN repository is contained within the hidden .svn folders.


Can parameters have same name as a global variable and still called inside a function?

Question: #include<stdio.h>
int x = 12;

void foo(int x)
{
  printf("%d\n",x);
}

int main()
{
  foo(3);
  printf("%d\n",x);
  return 0;
}

This gives output
3
12

How can i access global int x inside the function foo()?
Comment: Local variable/parameter shadows the global variable. Just use a different name.  `x` is not the most explanatory name for a global, and 99% of the time you don't want to use a global at all.
Answer: You can, but the parameter shadows it. Just use another name for parameter variable in foo function.
Answer: Yes it works like this as variables of same names are allowed provided that they are in different scopes. "x" is both defined in global scope (global variable) and a local scope (in foo() as a parameter). But they are located in different locations in memory.


A composer configuration file was found at the root of your project but seems uninitialized

Question: Visual Studio Code
I am facing this problem when I open the Visual Studio Code. How to fix this?
Answer: If you are developing a project, execute
composer install

If you are developing a package, just execute
touch composer.lock


Rate limited computed firing twice

Question: I'm trying to create a simple isDirty style Knockout binding. I've seen examples using the toJS conversion but it gets a little complicated using this approach for multiple firing of the observable. As I know the observable I want to subscribe to up-front I thought I'd just do that instead. Here's the code I've currently got:
var isDirty = false;
this.types = ko.observableArray([]);
this.instances = ko.observableArray([]);
this.selection = ko.observable();
this.filters = ko.observableArray([]);

// Some Logging to try and figure out what's going on
this.types.subscribe(function() { console.log("types changed " + new Date().getTime()) });
this.instances.subscribe(function() { console.log("instances changed " + new Date().getTime()) });
this.selection.subscribe(function() { console.log("selection changed " + new Date().getTime()) });
this.filters.subscribe(function() { console.log("filters changed " + new Date().getTime()) });

   // Flag to use to determine if the context property has changed
this.isDirty = ko.computed(function() {
    console.log("isDirty changed " + new Date().getTime());
    let types = self.types();
    let instances = self.instances();
    let selection = self.selection();
    let filters = self.filters();
    return isDirty = !isDirty;
}).extend({ rateLimit: 500 });

 this.isDirty.subscribe(function(changes) {
    console.log("context changed " + new Date().getTime());
});

So my code could be modifying types, instances, selection or filters at any point and I don't really want to have to care about this too much. Realistically there will be several modifications in rapid succession (e.g. a new item is added into types and selection is modified at the same time).
The problem I've got is that even with the rateLimit that I've tried adding, I seem to be getting multiple fires, and I don't understand why. Here's the console output when I make a change:

context.js:59 isDirty changed 1455203776330
  context.js:52 types changed 1455203776331
  context.js:53 instances changed 1455203776333
  context.js:54 selection changed 1455203776333
  context.js:55 filters changed 1455203776333
  context.js:52 types changed 1455203776334
  context.js:53 instances changed 1455203776334
  context.js:54 selection changed 1455203776335
  context.js:52 types changed 1455203776409
  context.js:53 instances changed 1455203776413
  context.js:54 selection changed 1455203776413
  context.js:59 isDirty changed 1455203776832
  context.js:68 context changed 1455203776832
  context.js:59 isDirty changed 1455203776912
  context.js:68 context changed 1455203776913

So I can't figure out why after making all my changes (e.g. selection changes at 1455203776413 is the last change) why isDirty then fires twice afterwards...
I'll add that I'm trying to put together a snippet to reproduce this error, although that doesn't seem to be working at present. I'm just trying to figure out what other parts of my code could be introducing side affects to this.
Answer: There is a lesson here - ensure that you've only got a single item you're tracking. It just so happens that there was a copy of the ViewModel that was being passed around and this was also triggering to the console.

Rate limited computed firing twice


How to bundle more than one with Vue

Question: I have started a project with vue-cli 3, my current directory tree is:
/
  /dist
  /public
    index.html
    favicon.ico
  /src
    /assets
    /components
    /plugins

when I run vue-cli build I get all sources bundled into app.js under /dist.
My goal is to bundle another bundle, say special-app.js from a few scripts either under /public or from a special directory under /src.
I was not able to achieve this in any way using the tsconfig or trying to augment the webpack config via vueconfig.js.
How can I bundle say /src/special/a.ts and /src/special/b.ts -> /dist/special.js?
UPDATE #1
I have tried the solution proposed by @digitaldrifter
config.entryPoints.delete('app');

config
  .entry('app')
    .add(path.resolve(__dirname, './src/widget/main.ts'))
    .end()

config.entry('runner')
    .add(path.resolve(__dirname, './src/donr/donr.ts'))
    .add(path.resolve(__dirname, './src/donr/donr.scss'))
    .end();

result is that there is no runner.js or runner.html at the end
UPDATE #2
The only way I got this to build correctly was to use pages https://cli.vuejs.org/config/#pages
pages: {
  widget: {
    entry: 'src/widget/main.ts',
    template: 'public/index.html',
    filename: 'index.html'
  },
  donr: {
    entry: 'src/runner/donr.ts',
    template: 'public/donr.html',
    filename: 'donr.html'
  }
}

build wise this worked! I got:
File              Size                         Gzipped

dist/widget.js    4723.88 kb                   841.16 kb
dist/app.js       4723.88 kb                   841.16 kb
dist/donr.js      236.48 kb                    56.84 kb
dist/test.js      191.93 kb                    42.07 kb

PROBLEM
when I do vue-cli serve the donr.js is served as an HTML... while when I do build donr.js under /dist is all JS with the webpack header and all that good stuff. I do not understand why and I do not understand how to see the files that dev-server is serving, it is abstracted from me.... any ideas how to solve this?
UPDATE #3
forced dev-server to dump compiled files to disk.
I do not even see donr.js, while i do see it when i just build.
I am slowly coming to the idea that dev-server has a bug somewhere....
Github URL with the issue:
https://github.com/amoldavsky/vue-multi-bundle/tree/master
run npm serve VS npm build
any ideas?
Comment: The webpack dev server utilizes an in memory filesystem, there are no files written to disk when running `vue-cli serve`. It watches for changes being made and updates the page via websocket.
Answer: You need to configure the webpack entry points.
Using chainWebpack option:
chainWebpack: config => {
    // first clear the default app entry point
    config.entryPoints
          .delete('app')

    // add a new entry with the necessary files
    config.entry('special')
          .add('/src/special/a.ts')
          .add('/src/special/b.ts')
          .end()

    // you can split the bundle by entries also
    config.entry('special-a')
          .add('/src/special/a.ts')
          .end()

    config.entry('special-b')
          .add('/src/special/b.ts')
          .end()
}

Comment: it did not quite work but did put me on the right path, take a look at UPDATE #2, not sure how to solve this...

How to bundle more than one with Vue


Solving the IVP $ty''-ty'+y=1$ where $y(0) = 0$ and $y'(0)=2$.

Question:
Solving the IVP
  $$ty''-ty'+y=1$$
  where $y(0) = 0$ and $y'(0)=2$.

I'm struggling to get started. I've solved some problems of similar fashion, but without the t factor on the left hand side.
Comment: the solution containes the exponential integral
Comment: May I ask where this problem comes from?
Comment: It's from an advanced math course exercise at my university.
Answer: $$ty''-ty'+y=1$$
$$-\left(s^2{\cal L}(y)-sy(0)-y'(0)\right)'+\left(s{\cal L}(y)-y(0)\right)'+{\cal L}(y)=\dfrac{1}{s}$$
$$(s-s^2){\cal L}'(y)+(2-2s){\cal L}(y)=\dfrac{1}{s}$$
$${\cal L}'(y)+\dfrac2s{\cal L}(y)=\dfrac{1}{s^2(1-s)}$$
with integrating factor $s^2$ we have
\begin{align}
(s^2{\cal L}(y))'
&= \dfrac{1}{1-s} \\
y&={\cal L}^{-1}\dfrac{-\ln(1-s)}{s^2}+Ct \\
&=\int_0^t\dfrac{e^x}{x}(t-x)dx+Ct \\
&= t\int_0^t\dfrac{e^x}{x}dx-e^t+1+Ct \\
&= t\operatorname{Ei}(t)-e^t+1+Ct
\end{align}


Does a function with these properties exist?

Question: For $x_1, x_2, x_3 \in \mathbb{Z}^+$, does there exist a function $f(\cdot)$ defined on $\mathbb{Z}^+$, not necessarily continuous or differentiable, such that:
$$f(x_1) > f(x_2) \\ f(x_2) > f(x_3) \\ f(x_3) > f(x_1) $$
My immediate thought is that no such function exists, since a function can only be a many-to-one or one-to-one relation, and the above would require a one-to-many relation. If so, is there a more formal way of showing that the above is impossible? Or is it trivial to observe?
If I am wrong and such a function does exist, what is an example of one?
Comment: An interesting aside: https://en.wikipedia.org/wiki/Nontransitive_dice
Answer: A function has exactly one output.
If such a function exists, by transitivity, we would have $f(x_1) > f(x_1)$ which is a contradiction.


When multiplying two or more terms in an integral, can I calculate the terms seperately and then multiply?

Question: For example, say I have an equation that is $\int_0^\infty x g(x)f(x)dx$
Can I calculate each term seperately, say for example my maximum $x$ value is 500.
Is it something like $500\int_0^{500} g(x)\int_0^{500} f(x)dx$?
I could not find a rule for this sort of behavior online, and my background is not in mathematics.
Comment: Unfortunately there is no such rule. We can easily differentiate a product, but not easily integrate it. The most important technique for integrating products is integration by parts.
Comment: It's always a good idea to think of a "dummy" example. Let's say that $g(x) = x$. If integration could be separated at multiplication, you would have
$$
\int x^2 \, dx = \int x \cdot x \, dx = \int x\, dx \cdot \int x\, dx = \frac{1}{2}x^2 \cdot \frac{1}{2}x^2
$$
But everyone knows that $\int x^2 \, dx = \frac{1}{3}x^3$ (I left out the "plus constant" to make this shorter). So just thinking about this for a few seconds, you can see that this is not true.
Answer: You cannot do this. It's easy to see even in very simple case:
$$
2 = \int_0^2 1\times 1 \, dx \neq \left(\int_0^2 1\,dx\right)\left(\int_0^2 1\,dx\right) = 2\times 2
$$
Since an integral is essentially a sum, what you propose is something like:
$$
a_1b_1 + a_2b_2 = (a_1+a_2)(b_1+b_2).
$$
I hope you can see why this doesn't work.


Google Oauth2: Is it possible to retrieve token information from an expired access token?

Question: I have a Google App Engine endpoints projects which is protected by Oauth2. I saw some request has failed due to Invalid token.
Request URL: https://example.appspot.com/_ah/api/mm/v1/list?filter=q%3Dtest&alt=json
Method: example.resource.list
Error Code: 401
Reason: required
Message: Invalid token.
I could log out the token from the HEADER of the request.
The token I get is access token, format like, ya29.vwGg-....
When I tried with
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=
to find out token information, like issue_to, client_id, extra.
It returns back with
{
error: "invalid_token",
error_description: "Invalid Value"
}
I have tested with
https://developers.google.com/oauthplayground
the url returns back the same error if the token has been expired.
My guess for the reason my request has failed is the token used has expired.
But not 100% sure.
Is there way to find token info about expired access token?
Or maybe more widely,
is there any way to find more info about invalid access token, like why it is invalid or anything else?
Comment: what to you mean by "invalid access token"? All access tokens are valid, until they expire.
Comment: It means a token , if querying use https://www.googleapis.com/oauth2/v1/tokeninfo?access_token= and returns back with "invalid_token" error.   Most likely, it's a expired token.
Answer: I remove google account and add google account, then login works.
Google's guide for Google Sign-In for Android on how to Authenticate with a backend server.
A simple way is to check the token, XYZ123 is your token
<code>https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=XYZ123
</code>
Answer: There are many ways to get token information. Generally token will be invalid for various reasons so of the important reasons are Invalid Signature and Token expired. You can use https://jwt.io to decode your token and get the info. Your error description clearly tells the reason about why your token is considered invalid. Try deep diving into the code and see why it says invalid value.