Axes Rotation Problem

Question: Given $$x^2 - 4xy + 5(\sqrt5y) + 4y^2 + 1 = 0$$
rotate the axes to eliminate the $xy$-term in the equation, then write the equation is standard form.
Comment: See [here](https://en.wikipedia.org/wiki/Rotation_of_axes). You will find many details on how to eliminate the xy term for conic sections.
Comment: https://en.wikipedia.org/wiki/Rotation_of_axes
Answer: Suppose your new coordinates are
$$
\begin{bmatrix}
X\\
Y
\end{bmatrix}=\begin{bmatrix}
\cos\phi&\sin\phi\\
-\sin\phi&\cos\phi
\end{bmatrix}\begin{bmatrix}
x\\
y
\end{bmatrix}
$$
Let $c=\cos\phi,s=\sin\phi$. Your new equation is
$$
(Xc-Ys)^2-4(Xc-Ys)(Xs+Yc)+5\sqrt5(Xs+Yc)+4(Xs+Yc)^2+1=0\\
$$
As there's no $XY$ term we have
$$
6sc=4(c^2-s^2)\implies \tan2\phi={4\over3}\implies \phi={1\over2}\arctan({4\over3})\\
\implies c={2\over\sqrt5},s={1\over\sqrt5}
$$
The new equation becomes
$$
Y^2+X+2Y+0.2=0
$$
So you have to rotate your axes by $\phi$ radian counter-clockwise.
Comment: Can you please explain how you got 6sc and 4(c^2-s^2)
Comment: Coefficient of $XY$ from the 1st term is $-2cs$, from the 2nd term is $4(c^2-s^2)$, from the penultimate term is $8sc$. Add them up and equate to $0$ and you get $6sc=4(c^2-s^2)$.
Comment: Okay, thank you. So to figure out the new equation, do I just substitute s and c back into the long equation then simplify?
Comment: Why did you divide the final equation by 5? Because I got 5Y^2+5X+10Y+1=0
Comment: Because I'm lazy and it's easier to write...
Comment: Ok, but wouldn't that change the graph of the parabola?
Answer: $$Ax^2+Bxy+Cy^2+Dx+Ey+F=0$$
Then
$$\tan(2\theta)=\dfrac{B}{A–C}$$
For $x^2−4xy+5(\sqrt{5}y)+4y^2+1=0$, $\tan(2\theta)=\dfrac{4}{3}$
imply $2\theta=53.1301^\circ$ and the angle of rotation is $\theta=26.56505^\circ$

Axes Rotation Problem


starting jetty 9 faild ubuntu 12.04

Question: i installed jetty (distribution-9.0.2) on ubuntu server 12.04
from these links step by step
http://degreesofzero.com/article/19
http://pietervogelaar.nl/ubuntu-12-04-install-jetty-9/
at last when i start jetty with the following command:
sudo /etc/init.d/jetty start

or
sudo service jetty start

i get the following error
Starting Jetty: grep: /var/run/jetty.state: No such file or directory

Answer: I've tested this thoroughly with the latest release of jetty and it's working fine. There's been some changes recently in the jetty.sh script. However the changes look good to me and it's working fine for me with the latest release.
Evgenly is right, that JETTY_PORT is deprecated (see comments in jetty.sh for details), however it also works fine for me using JETTY_PORT instead of JETTY_ARGS to define a non standard port.
Please try the latest release from here in case you didn't do already:
http://download.eclipse.org/jetty/
If jetty.sh reports that the start failed, you'll usually find the reason in stderrout.log inside the JETTY_HOME/logs directory (unless you've changed the logging config).
Answer: I'm facing with the same problem but on Debian 6 server. Workaround for this problem and articles above, from my perspective, is:

use JETTY_ARGS=jetty.port=8080 instead JETTY_PORT
Add property to /etc/init.d/jetty: JETTY_PID=/opt/jetty/jetty.state

Please, let me know if you have any questions
Comment: tanQ evgeniy,i add jetty_pid but i get another error just telling start fails,,but then i run this bash [bash --debugger ./jetty start] and jetty starts with no error,,after that [jetty start] works fine

starting jetty 9 faild ubuntu 12.04


Prove that $\frac{a^3}{b} + \frac{b^3}{a} \geqslant a^2 + b^2$

Question:
Prove that $$\frac{a^3}{b} + \frac{b^3}{a} \geqslant a^2 + b^2$$
for $a,b \in \mathbb{R}^+$. Establish when the equality holds.

My approach was to use AM-GM however trying both sides individually assert to $\geqslant 2ab.$ RHS is baby AM-GM if considered.
Edit:
From L.H.S -
$\dfrac{\frac{a^3}{b} + \frac{b^3}{a}}{2} \geqslant ab \implies \dfrac{a^3}{b} + \dfrac{b^3}{a} \geqslant 2ab$
Comment: Since you have chosen this line of proof, your next step would be to determine if $a^2+b^2\le2ab$ holds. Does it?
Comment: Try using [Titus-Lemma](https://brilliant.org/discussions/thread/titus-lemma-part-1/). Then AM-GM.
Comment: You need to show some of your work.
Answer: Bring all terms to LHS$$\frac{a^3}b-\frac{a^3}a+\frac{b^3}a-\frac{b^3}b=(a^3-b^3)(1/b-1/a)$$
Now if $a\ge b$, both factors are $\ge0$. When $a<b$, both are negative. Can you see when the equality holds?
Comment: [fyi](https://math.meta.stackexchange.com/questions/33508/enforcement-of-quality-standards).
Answer: Reduce to this:
$(a-b)(a^3-b^3)\ge 0$
Do you see why it is always satisfied?
Comment: Yes, I can show that this always holds since a^3 - b^3 nicely factors and proving the other  factor (a^2 + ab + b^2) $\geqslant$ 0 is trivial enough. Thank you.
Answer: Here is a trick, using only AM-GM, twice.
$$a^2+b^2\geq 2ab \Rightarrow \\
\frac{a^3}{b}+\color{red}{a^2}+\frac{b^3}{a}+\color{red}{b^2} \geq
\frac{a^3}{b}+\color{red}{ab}+\frac{b^3}{a}+\color{red}{ab}\geq\\
2\sqrt{\frac{a^3}{b}\cdot ab} + 2\sqrt{\frac{b^3}{a}\cdot ab}=2a^2+2b^2$$
Or
$$\frac{a^3}{b}+\color{blue}{a^2}+\frac{b^3}{a}+\color{blue}{b^2} \geq 2(\color{blue}{a^2+b^2})$$
and the result follows.


Weird Javascript Array Syncing Trick?

Question: I found a weird JS behavior :
var myArray = [ [1] , [2] , [3] ];

var myArrayCopy = [];

myArrayCopy.push( myArray[1] );

alert( myArrayCopy ); // 2, as expected.

myArrayCopy[0][0] = 'foo';

alert( myArrayCopy ); // 'foo', as expected.

alert( myArray ); // 1, foo, 3  =  WTF ? :)

See the Demo.
Note that this doesn't work if we push directly values instead of arrays.
To me, it looks like pushing arrays into an array, translates somehow as if we pushed only references to those arrays, rather than copies, (which is not the behavior one would expect, please correct if I'm wrong).
Can someone explain why ?
Comment: array are passed byRef, its not as if you're editing a ref, you are editing a ref. you can use .slice() to get a new container with the same values (a shallow copy)
Comment: @dandavis - You're comment is conceptually correct, but inaccurate. There's no such thing as *byRef* in JavaScript, but passing an object (which an array *is*) causes the effect you're describing.
Comment: @dandavis No that's not true. Again, *ByRef* is VB. (It's similar to `void f(int &v);` in c++, and `void f(ref int v);` in c#), but this causes the reference of (address of) the variable used during the call to the function to be "passed in", and actually lets the function mutate that external variable. What JavaScript does is more like `void f(int v)` or `void f(obj *v)`, where in the 2nd function the address of an object is used and mutating the object is visible from outside.
Comment: without arguing over semantics, in js, it aligns with what's mutable/immutable: numbers, strings, booleans are immutable and thus passed by value whereas mutables, aka objects, are passed as object references. to be pedantic, objs are not technically passed by ref, it's a pointer to the ref that gets passed by value, but that's just confusing, and the effect is of passing "byRef"...
Comment: I guess the OP is not actually interested in a flame about how js works under the hood and what it resembles. By looking at his problem, it looks that he is still scratching the surface of the language. :-)
Comment: VB? yikes! bad coincidence, i should have said "by reference". I'm not sure how useful your comments are to the OP, or what i said was untrue, but let's not get sidetracked further; you can "be right" if it helps.
Answer: Aliasing.
You are putting in myArrayCopy a reference to an existent object (an array) that is contained in myArray. Because of that, when you modify that array, you are modifying the actual object referred from both the above mentioned arrays.
Please, note that when you pass around objects in JavaScript they are not copied, instead you are passing around a reference to an instance and modify it in the scope of the receiver will result in a modified object in the scope of the caller as well.
There are some noticeable exceptions to this rule (as an example primitive types for they are not objects, or strings for they actually copied on write, and so on), but let's concentrate on your problem.
Considering that an array is an object, it happens the same in the following example, but it is far clearer from my point of view:
var o = { "foo": " bar" };
myArray[0] = o;
myArrayCopy[0] = myArray[0];
o.foo = "nolongerbar";

What does it return myArrayCopy[0].foo? And what myArray[0].foo?
That's called aliasing in most of the OO languages, anyway it's a common error when you deal with objects' references.
EDIT
Oh, it is not a syncing trick in any case, it's usually the reason behind annoying bugs. :-)
Comment: Thank you for your complete answer. Especially for pointing out the term of "aliasing" !
Comment: You are welcome. That's a term widely used, even though it's not common to find it mentioned in discussions about JavaScript. I don't know why, maybe there exists a term that has the same mean, but I find that *aliasing* is the most meaningful (at least to me, of course).
Answer: The value of myArray[1] is an array ([2]). When you push that into myArrayCopy in myArrayCopy.push( myArray[1] );, you push the array, not it's contents ([2] and not 2).
When you later mutate this array (myArrayCopy[0][0] = 'foo';), it obviously has an effect everywhere this array is used.
Comment: I was aware of pushing an array and not it's content, my question was how is that "obvious" that when I change the value myArrayCopy[0][0] it has an effect on the first array as well ! But I think the other answers may have answered it : )
Comment: @lapin - It's the same array. That's what I tried to address in my answer: *you push the array, not it's contents* and *When you later mutate this array*. It's the same array all along.
Answer: Yes, That is make sense action, because myArray1 And myArrayCopy[0] has same memory address. You can check below debugging capture

After passing through line number 9, those has been changed at same time myArray and myArraycopy's value to 'foo'
Answer: This is perfectly right.
Since arrays acts as an object, it stores the memory address
instead of storing the values itself.
var myArray = [ [1] , [2] , [3] ];

myArray will store the address of the Array created (say addr-1).
Since the elements of the array is itself an array, it will now have three addresses corresponding to array [1], [2], [3] say addr-2, addr-3, addr-4 respectively.
so finally we have:
addr-1 = [addr-2,addr-3,addr-4]

var myArrayCopy = [];

This will store a new address say addr-5 = []:
myArrayCopy.push(myArray[1]);

since you pushed the first element of myArray to myArrayCopy. It will store the address addr-3. like thisaddr-5 = [addr-3]:
`alert( myArrayCopy ); // 2, as expected

So of course this works fine as addr-3 = [2]:
myArrayCopy[0][0] = 'foo';

here you are modifying the value of zeroth element of zeroth element of myArrayCopy, i.e you change the first element at addr-3 to foo
alert( myArrayCopy ); // 'foo', as expected

So it works as well:
alert( myArray ); // 1, foo, 3

myArray now has addr-1 = [addr-2, addr-3, addr-4], where addr-2 = [1]
, addr-3 = ["foo"] and addr-4 = [3].
Comment: Does your answer look to you like it's formatted as it should? (Look around, it's ***very*** odd in the crowd)
Comment: i know its not, i was answering for the first time, so i was just playing around.

Weird Javascript Array Syncing Trick?


Radius of convergence, power series

Question: So I'm stuck with the question: Find the radius of convergence for the power series:
$$f(z) = \sum^{ \infty}_{j=0} 2^{j} z^{j^2}$$
My issue is that there are two solutions depending if the $a_{n}$ is a perfect square or not, how should I approach this problem? Thanks in advance!
Answer: Precisely for cases like this one is that Cauchy-Hadamard is used. Observe the coefficients sequence is
$$a_n=\begin{cases}2^n,&n\;\text{ is a perfect square}\\{}\\0,&\text{otherwise}\end{cases}$$
and then
$$\lim\sup_{n\to\infty}\sqrt[n]{a_n}=2\implies R=\frac12\;\text{is the convergence radius, by Cauchy Hadamard Formula}$$
Comment: How do you conclude the first thing, that $a_n$ is either 2^{n} or 0, that's the part I dont get
Comment: Look at the powers of $\;z\;$ . They are $\;0,\,1,\,4,\,9,\,16,\,...$ etc. So for this series to be considered a **power series** (i.e., with **consecutive** powers of $\;z\;$ ), we must write it , and consider it, as $$1+2z+0\cdot z^2+0\cdot z^3+4z^4+0\cdot z+\ldots+0\cdot z^8+8z^9+\ldots$$
Comment: I'm very grateful that you are willing to help me, but for what n would $a_n$ become 0?
Comment: ahh, I think I get it, thanks for the help!
Comment: @Stratbomber Any time. Tricks like this one are something that not very often is taught in school. One must struggle with this.

Radius of convergence, power series


How do I block a user/cancel a user account in Simpletest?

Question: I'm trying to write some tests for a module for situations in which a user is blocked.  I know I can use drupalCreateUser() to make new users, but how do I block a user I have created in Simpletest?
Answer: Once you've got the user object back from drupalCreateUser() you can use standard API methods to make changes (in this case user_save()):
user_save($user, array('status' => 0));


Erro ao acessar "Java Build Path" no Eclipse

Question: Quando tento acessar MEU_PROJETO_ANDROID - Properties - Java Build Path, aparece a seguinte mensagem:

the currently displayed page contains invalid values

O arquivo AndroidManifest.xml está assim:
<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="21" />

E não consigo importar nenhum projeto Android para o Eclipse, sempre aparece a seguinte:

Invalid project description

Alguém tem alguma ideia de onde pode ser o problema?
Comment: Vê se essas 2 perguntas do SOen te ajudam: http://stackoverflow.com/questions/5784652/eclipse-invalid-project-description-when-creating-new-project-from-existing-so e http://stackoverflow.com/questions/3311474/problem-importing-android-project-archives-into-eclipse.
Comment: Quando tentei importar novamente, com outro nome, tive o mesmo erro... E o mesmo erro persiste em todas as outras tentativas também.
Comment: PS.: Tenho uma certa dificuldade com tópicos em inglês.. Demoro para traduzir e muita das vezes perco informações importantes no translate da Google.
Eu até pesquisei em muitos tópicos, em inglês, que continham o erro "the currently displayed page contains invalid values", mas ainda nada.
Answer: Tenta iniciar o Eclipse pelo cmd/terminal com a opção -clean
No Windows:
 Eclipse.exe -clean

No Linux:
./eclipse -clean

ou se Eclipse está na sua PATH
eclipse -clean

Isto irá limpar o cache de plug-ins, talvez ele resolve o problema.
Fonte: StackOverFlow EUA


Why do characters of groups have modulus $1$?

Question: This is a fairly simple question, and it is supposed to be a definition-level question. But it really bothers me as I couldn't see the reason. Let $f$ be a character of an (arbitrary) group $G$, then
$$f(ab)=f(a)f(b)$$
and $f:G\to\mathbb{C}$. Apostol in his book Introduction to Number Theory mentions that for all group elements $|f(a)|=1$. The only proof of this statement I can come up with is that if $G$ is a finite abelian group, then for all $g\in G$, there exists an integer $n$ such that $g^n=1_G$. Therefore, we have
$$f(g^n)=f(g)^n=f(1_G)=1$$
Thus $|f(g)|=|1|^{1/n}=1$. However, this result is restricted to only finite abelian groups. So I'm wondering if this is a general truth or it is just for finite abelian groups?
Comment: This might be a duplicate. Thanks in advance if you found a suitable one.
Comment: The characters that Apostol uses may actually be [Dirichlet characters](https://en.wikipedia.org/wiki/Dirichlet_character). In which case your proof is good.
Comment: @Somos No he actually introduces Dirichlef characters after this. This is a note he writes to find the multiplicative inverse of an arbitrary character.
Answer: It's a general result for compact groups since in that case, the image of $G$ under $f$ must be compact and every compact sub-group of $\mathbb{C}^{\times}$ is contained in $S^1$.
To see this, note that if $H$ is a sub-group of $\mathbb{C}^{\times}$ and $z\in H$ satisfies $|z|\neq 1$ ,then, $|z^n|$ tends to either $0$ or $\infty$. However, this means that either $H$ is unbounded or has $0$ as an accumulation point (in fact, considering $z^{-1}$, both of these statements must be true). Hence, $H$ cannot be compact.
To see that it's not true in general, simply take $G=\mathbb{C}^{\times}$ and $f(z)=z$. It's clearly a character and its image is not contained in $S^1$.
Comment: Great answer, though really topological. I'm learning number theory. But the idea is essentially the same. I will accept this after the time limit.
Comment: In other words, compact is as good as finite (once again)
Comment: Note that there is no general statement for non-compact groups. If $G$ is the sub-group of $S^1$ generated by $e^{i \frac{p}{q}\pi}$ for $p\in \mathbb{Z}$, $q\in \mathbb{N}$, then Yourong's argument shows you that every homomorphism  from $G$ into $\mathbb{C}^{\times}$ (the characters on $G$ in the discrete topology) still has image in the circle.
Comment: @YourongZang: After a while, you will begin to see that it is not so easy to disentangle number theory from topology. Topology is applied to understand number theory (e.g. using algebraic geometry), and number theory is applied to understand topology (e.g. in algebraic topology).
Comment: Well, compact groups and continuous homomorphisms (or are the homomorphisms automatically continuous when the group is assumed compact?)
Comment: @LeeMosher I will try my best to see that.
Comment: @TobiasKildetoft If someone were to write "character", I would assume that it's continuous yeah, and then assume that the group is discrete if the group doesn't carry any other natural topology.
Comment: Sure, but I wanted to make sure this was explicit in this context, since the original context had no topology in the picture (at least none specified), and it does happen that one needs to consider non-continuous characters (though I would agree that it is very rare).


Variable selection for regression when $X$ is a sum of different independent variables

Question: Let's say we have an independent variable X such that
$X=\sum_i^n x_i$
and then we have a covariate matrix $C$
So we will have the following regression model:
$Y=X\beta_1+C\beta_2+\epsilon$
However, what we really want to do is to find $k$ such that for
$X_k=\sum_i^k x_i$
we can get the highest r-square out from
$Y=X_k\beta_1+C\beta_2+\epsilon$
Currently we perform a sequential test such we calculate the r-square for $X_1, X_2,...,X_n$ and then identify the model with the highest r-square.
Are there any better method for this selection process?
Edit: Thank you all for your comments
First, the reason why we use $X=\sum_i^n x_i$ instead of individual $x_i$ in our model is that there can be a huge number of $x_i$. So in some situation, it might not be possible for us to solve the equation with that many $x_i$.
Here, in our settings, $X$ is considered as an aggregated score where we have the basic assumption that the amount of information in $x_1>x_2>...>x_n$, where we assume for any $x_i$ from $k+1$ to $n$ contains mostly noise.
From what we understand at the moment, our method of finding the largest r-square is less than optimum and might lead to overfitting. However, it is the only thing that we can figure out at the moment. Therefore if there is any analytical way for us to find $k$ for the best predictive power, it might benefit us tremendously
Comment: This type of selection of predictors, based on r-squared values from a particular data sample, has many problems. See the [`feature-selection`](http://stats.stackexchange.com/questions/tagged/feature-selection) tag on this site. Providing more information on what you are trying to accomplish with your model might lead to suggestions for better approaches.
Comment: Why do you want to use $X_k = \sum^k_{i=1} X_i$ rather then individual $X_i$'s?
Comment: Is the indexing of the $x_i$ meaningful or are there some (assumed) relationships among the $x_i$?  If not, it might be of interest to observe that your question amounts to a limited form of model selection process in which the variables $C$ will be included and *exactly one* of the $\{X_1,X_2,\ldots,X_n\}$ will be included with them. By first regressing $Y$ and each of the $X_k$ on $C$ and retaining the residuals, this is equivalent to the same situation with $C$ removed: in other words, you seek the best one out of $k$ possible variables to model $Y=\beta X_k+\epsilon$.
Comment: **NB**: your test does not appear to be a "sequential test" as commonly understood.  It's a search of all possible solutions.  A sequential test would take the $X_i$ in the order given and apply some criterion to determine when to stop testing.  It therefore might not ever consider including $X_n$, for instance, if it stopped early.
Comment: When you say "there can be a huge number of $x_i$," do you mean that different observations can have different values of $n$, or something else (perhaps, different observations have different numbers of non-zero values of $x_i$)? And approximately how huge is "huge" relative to the numbers of observations?
Comment: Different observation does have different numbers of non-zero values of $x_i$. If we go use the absolute biggest possible sets, we can achieve something like 1,000,000+ $n$ with only around 500,000 observation. Which will be impossible to solve.
So what we did is kinda similar to what histogram plotting does, instead of looking at individual $x_i$, we aggregate them by summing them into $\hat{x_i}$ such that we reduce the dimension of our problem. So in theory, $X$ should in fact be $\sum_i\hat{x_i}$ where $\hat{x_i}=\sum_jx_j$
Answer: With a set of $x_i$ ordered according to their assumed amount of information, you might be able to get what you need with the LASSO, using the $x_i$ rather than their running sums $X_k$ as the candidate predictor variables. This is a standard approach when the number of candidate predictors greatly exceeds the number of observations. It's explained, for example, in Chapter 6 of An Introduction to Statistical Learning, with a worked exercise using the glmnet function from the package of the same name in R.
With large numbers of predictors LASSO sets coefficients of most to zero, with the number of retained coefficients determined by a penalty value. The penalty value is typically determined by cross-validation, for example choosing the penalty that minimizes cross-validated prediction error. There is, however, no "analytic" way to determine the number of retained predictors.
If the $x_i$ are more or less in the same order of assumed importance among all your observations, then the LASSO should maintain only the most important $x_i$ in the model. The coefficients of the individual $x_i$ will generally differ, so this is not the same as the running sums $X_k$ as you are presently using. If you need to use running sums instead of individual $x_i$ there might be a way to force all the maintained $x_i$ to have the same coefficient (and thus effectively use a sum of maintained $x_i$ as the predictor), but that's outside my experience or knowledge.
If you do try LASSO be careful about how it's implemented. Usually the predictor variables are pre-standardized so that they all are considered in comparable scales. Consider whether that's what you want here (standardize argument to glmnet). Also, it seems that you want to maintain all of the predictors in your covariate matrix $C$. If so, you can work with the residuals after accounting for $C$, as suggested in a comment from @whuber, or specify that the variables in $C$ are maintained without penalty (penalty.factor argument to glmnet).


How to Compute the Reconstruction error in Principal Component Analysis at lower dimensions

Question: I have m examples and d features where m<<d. So I managed to compute the eigen value and corresponding its eigen vector ... I want to compute the reconstruction error for various value of principal components  , lets say n principal componets (n eigen vector corresponsing to first max n eigen values)
So My original dataset has shape
<code>(m, d)
</code>
If I take n principle components where n < d, the transformed matrix matrix would have shape
<code>(m, n)
</code>
So Since the shapes mismatch I really wasnt able to find any way to compute the reconstruction error
Answer: Like you said, you cannot compute the error in that fashion because the dimensional space is not the same, you would need first to 'reconstruct' your new-reduced space to the old-bigger dimensional space and there you can compute the error as you said.
For the dimensionality reduction we do:
$T = XP$
for the reconstruction we do:
$\hat{X} = TP^{'}$
where $X$ is the original data, $T$ is the reduced space (formally called scores), $P$ are the loadings (PCs) and $\hat{X}$ is the reconstructed space.
Finally, we commonly express the error as:
$Error = (X - \hat{X})^{2}$

Edit:
How do we interpret Error:
Before, first we denoted $X$ as our matrix of original data $\mathbb{R}^{nxk}$ ($n$ data points with $k$ dimensions each), and then we moved to the reduced space $\hat{X} \in \mathbb{R}^{nxp}: p<k$
When we compute the error, we are computing the distance (norm) between the original ($p$ dimensional) and the proyected ($k$ dimensional) observation.
Comment: Specifically you want either the Frobenius norm $||\cdot||_F$ or (less likely but still correct) the spectral norm $||\cdot||_2$. Either will do here; see http://people.tamu.edu/~sji/classes/PCA.pdf.
Comment: $X$ and $\hat{X}$ are both matrices. What operation do you mean when you write $(X-\hat{X})^2$? Perhaps you're referring to some type of matrix norm?
Comment: Yes!, I edited my answer


query on group theory

Question: Is the set (G)$G_n(\mathbb R) =\{a_{ij}=a\neq 0\,\forall\, i,j\}$ a group under matrix multiplication ? I think it is not as it's identity should be the identity matrix which has 0 and 0 can't be there in any element of G. Is is right?
Comment: Unfortunately, this argument does not work, since it is possible to have other elements act like an identity for a subset of the set of all matrices without actually being the identity matrix. This is for example the case here (try working out explicitly the $2\times 2$ case).
Comment: You must be knowing that the group $GL_n(\Bbb R)$ is totally a different group. So you change the name you have given to your group.
Answer: Let $$A = \begin{pmatrix} a & a \\ a & a\end{pmatrix}$$ and $$B = \begin{pmatrix} b & b \\ b & b\end{pmatrix}$$
Then, we have that:
$$AB = \begin{pmatrix} 2ab & 2ab \\ 2ab & 2ab\end{pmatrix}$$
So, the matrix:
$$A = \begin{pmatrix} 1/2 & 1/2 \\ 1/2 & 1/2\end{pmatrix}$$
clearly acts as the identity.
I've explicitly found the identity and inverse for the $n\times n$ case below:

 We can generalize this to show that in the $n\times n$ case that $[AB]_{ij} = \sum_{k = 1}^na_{ik}b_{kj} = na_{ij}b_{ij}$, so the "identity" matrix on this group is the matrix having $\frac{1}{n}$ as it's "value".

 Finally, given $B$ with "value" $b$, we have that $B^{-1}B$ has "value" $nb^{-1}b$, so for this to be equal to $\frac{1}{n}$ (the identity), we have that $b^{-1} = \frac{1}{bn^2}$.

 So, we've found the identity and inverse of this group, and the multiplication is clearly associative, so it's a group.
Answer: Let $A$ be the all-entries-1 matrix. Then $G$ contains all non-zero multiples $cA$, $c\in\Bbb R\setminus\{0\}$. See if you can figure out what $cA\cdot c'A$ is ...
(However, for $n>1$ this is not a subgroup of $GL_n(\Bbb R)$ for another trivial reason, if that's your real question).
Comment: Forget the multiples; what is the _inverse_ of all-1 matrix?
Comment: 1 . Ok so it need not have 0 in its identity
Comment: @IvanNeretin The OP question was about the identity element - that we do have. In fact, it turns out that $G$ is a group and there are inverses. Those are just not inverses within $GL_n(\Bbb R$), simply because we do not start from within GL_n$ in the first place (that was the "trivial reason" I alluded to)
Comment: Oh, I see. So it's a group, but not a subgroup of $GL_n$. Well, that should be expected: it is not even a _subset_ of $GL_n$.

query on group theory


Seeding for Round 1 in NCAA basketball tournament

Question: In the "field of 65" style tournament bracket, there were two 16-seeds (presumably the weakest teams) that had a play-in game in order to play the overall #1 seed.  When they expanded to 68, it's now 4 play-in games between 16-16 seeds, 13-13 seeds, 11-11 seeds and 16-16 seeds.  Why didn't they just do it between all 16 seeds?  Was there specific reasoning?  Is it the same seeds in each region every year or is there a mechanism for selecting which teams will play in Round 1.
(I know it can  be debated that playing in such a game can be a good warm-up for lower seeds, but I don't think that was the official reason.)
Comment: Note that the 11 and 16 seeds are playing into the first round of the Midwest bracket...and the South bracket with no seeds playing into the first round.
Comment: That's true.  The Midwest is the bracket with the overall #1, so perhaps a "bonus" for them?  Basketball should just get a BCS system, it would solve all these problems. ;P
Answer: The stated methodology for teams selected to play in the "First Four" is a) the four lowest seeded automatic-bid qualifiers (i.e. the four lowest-rated conference tournament winners), and b) the four lowest seeded at-large bid qualifiers. It is the b) category that gets us "11 vs 11", "12 vs 12", "13 vs 13", etc. games. Where these play-in winners wind up in the four regional brackets is not consistent from year to year. Each year, I believe, one of the regional brackets has had 2 of these play-in teams, while another regional had none.
The NCAA is likely trying to maintain the established balance between automatic-bid and at-large bid teams in the Div-1 tournament.
Comment: Note that this year, the 11 vs. 11 game is *not* between the third and fourth lowest-rated at-large teams; California, seeded 12, is the third lowest, but due to logistics the committee placed them in a normal game.


Does converging in probability require $X_n$ and $X$ to be defined on the same space?

Question: I read this passage regarding converging in distribution and it claims it is not necessary that $X_n$ and $X$ are defined on the same space (probability space). I read some examples and understood why that would be the case, by the way, I am not very advanced on measure theory.
Now I am wondering if the idea of converging in probability needs to be in the same space. I am particularly concerned in this question because if it doesn't stand then I can construct an example showing converging in distribution does not imply converging in probability by simply constructing random variables that are not on the same space.
I feel like converging in probability has to happen on the same probability space since we are exploring the idea od $\mathbb{P}(|X_n-X|\leq \epsilon).$ In particular, the probability measure has to be the same. However, I am not sure on this and if $(\Omega, F)$ need to be same, too. Could someone please explain to me in the easiest language as I am not looking for an advanced answer. Much thanks!
Comment: Regarding your concern: note that this implication indeed is not true, and none of the implications between modes of convergence is threatened by that: https://en.wikipedia.org/wiki/Convergence_of_random_variables#Properties_4
Answer: Yes, they have to be defined on the same probability space. The definition of convergence in probability is that for every $\epsilon>0$ we have $\mathbb{P}(|X_n-X|>\epsilon)\to 0$ when $n\to\infty$. The expression $\mathbb{P}(|X_n-X|>\epsilon)$ alone requires them to be defined on the same probability space, otherwise it makes no sense.
Convergence in distribution is different, it is all about the distributions of the variables without any meaning to their actual values. So when we define this type of convergence we can indeed let the random variables be from different probability spaces, the only thing that matters here is their CDF.


Moving PayPal Payment iFrame to Checkout page

Question: The Problem
Hi, I'm trying to move the payment iframe from its own page to the main checkout page so that I just have a one page form for checkout. I followed the directions here but wasn't able to get it to work (ie. I moved the 'review' section to 'disabled' and move the 'payment' section to 'checkout' in configuration).
The Current Status of My Situation
I'm using the Drupal Payflow Link module, and I have all my items in my checkout pane in store configuration. However, when a user goes to the checkout page they fill out all their information and also choose what payment method they want to use, but the actual entering of the payment information (credit card for example) still happens on the 'next' page. I want everything on ONE page.
Question
Anyone know how to make this happen with PayPal Advanced Payments/PayFlow Link so that entering the credit card details also appears on the main checkout page?
Answer: This actually just isn't possible. The iframe depends on having a completed order object, which you can't possibly have (or know for certain) if it's on the same page as fields placed to collect user input to complete that order. The same is true for all redirect, tokenized, or iframe based payment solutions.
Comment: hehehe, yeah, some things are quiet a challenge. The only *potential* way for something like this to work would be to use Ajax to update the order object in the background and refresh the iframe once you were assured the order wouldn't be changing any more. But my guess is that'd be more fragile than it's worth.
Comment: Ok, thanks for the answer. I guess you can't do ANYTHING you want with the code in Drupal after all.


pip install seems to be ignoring dependency links

Question: I have a Python application that depends on several packages.  One of those packages, unfortunately, isn't in PyPi so I have to install it directly from the git repo.
I've been trying to add it into my setup.py like so:
setup(
..,
..,
dependency_links = [
                 'https://github.com/marcuz/libpynexmo.git#egg=nexmomessage'
    ],
install_requires=[
    ..,
    'nexmomessage'
],
packages=['localpackage']

However it fails: No distributions at all found for nexmomessage
I see where it creates the dependency links list: writing dependency_links to common.egg-info/dependency_links.txt - and when I look at that file the URL is correct.
If I run it at command line: pip install -e git+https://github.com/marcuz/libpynexmo.git#egg=nexmomessage
It installs without an issue.
Thoughts?
Comment: What version of `pip` are you using?
Comment: pip 1.5.6 from /Library/Python/2.7/site-packages (python 2.7)
Answer: As of pip 1.5, dependency links are deprecated. Currently pip can still be forced to be used them with the --process-dependency-links flag. You might also have to use --allow-external packagename or --allow-unverified packagename, where packagename actually specifies whichever dependency  you want to install that's not in an official repository
Note that since it's deprecated functionality, the --process-dependency-links flag will be completely removed soon. I believe the preferred approach is to supply a requirements.txt file.
Comment: According to the 1.5 release-notes, dependency links are not "deprecated" - it is the `--process-dependency-links` that is needed to process them.  Additionally, since 8.0.0, you may add this option in a new line in requirements-file, so that the user does not have to type it in the command-line (see [pip#1274](https://github.com/pypa/pip/issues/1274).
Comment: Indeed, this was the conclusion I came to in September as well.  Though it was odd that it was able to run from command line without the flags, but not in the setup.py.  In the end I contacted the author and made a heartfelt plea he get his packages up to pypi to make life easier :)
Answer: And as of pip 7 they are enabled again. This means you can now use dependency_links using pip:
pip install -e /path/to/python/module --process-dependency-links --allow-all-external
If you'r using your distros system pip you might need to upgrade pip:
pip install pip --upgrade
Appears to have happened in pull request #1519
Comment: Aand in pip `pip 9.0.1` when I do this I get `DEPRECATION: --allow-all-external has been deprecated and will be removed in the future. Due to changes in the repository protocol, it no longer has any effect.` and `DEPRECATION: Dependency Links processing has been deprecated and will be removed in a future release.`


Error in delete object with DbContext in c#?

Question: I have this delete method:
     public void Delete(DBS.BankAccount entity)
    {
        try
        {
            if (_nahidContext.Entry(entity).State == System.Data.Entity.EntityState.Detached)
            {
                _nahidContext.BankAccounts.Attach(entity);
            }
            _nahidContext.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
            //or
            //_nahidContext.BankAccounts.Remove(entity);
            _nahidContext.SaveChanges();
        }
        catch (Exception ex)
        {
            throw new ArgumentException(ex.Message);
        }
    }

when I click that delete button, I get this error:

The object cannot be deleted because it was not found in the
  ObjectStateManager.

or sometimes gave me the following error:

An entity object cannot be referenced by multiple instances of
  IEntityChangeTracker.

How can I fix this and delete an object from Context DbSet?[Thanks]
Answer: Well, your second exception suggests that entity (or a related entity) is attached to another context (maybe the context where you get your BankAcount entity haven't still disposed, you should check that).
I don't know how are your getting your entities, but to avoid those exceptions you can try the following:
var entityToDelete=new BankAccount(){Id=entity.Id};//Create a new instance of BankAccount with only the Id
_nahidContext.BankAccounts.Attach(entityToDelete);
_nahidContext.BankAccounts.Remove(entityToDelete);
_nahidContext.SaveChanges();

Or just:
var entityToDelete=new BankAccount(){Id=entity.Id};//Create a new instance of BankAccount with only the Id
_nahidContext.Entry(entityToDelete).State = System.Data.Entity.EntityState.Deleted;
_nahidContext.SaveChanges();


If string contains substring get that substring

Question: Im getting a string like this from a barcode reader how can I check to see if the string has a substring say for example DCS and store that substring into a var?
something like
if string contains "DCS"
   let tmpString = substring["DCS"]
DCBNONE
DCDNONE
DBA02172021
DCSPHANFIELD
DACMIKE
DADJOE
DBB09171988
Answer: Your question is really unclear. I think what you meant was "if the barcode has a word that contains the string DSC, get that word". If so, split the barcode string by space:
let barcode = "DCBNONE DCDNONE DBA02172021 DCSPHANFIELD DACMIKE DADJOE DBB09171988"

// This is an array containing all words that has "DCS" inside it
let words = barcode.components(separatedBy: " ").filter { $0.contains("DCS") }

Answer: something like so
   let x = "adfsads"
    if x.contains("adf"){
        var y = x
        print(y)
    }


Data Binding to a LinkedList?

Question: What Works:

Web service that manipulates an in-memory LinkedList (of strings).
Clients can insert/add/remove/query the contents of the LinkedList.
Web service is started from the command line (no UI).

What I Would Like to Do:

Change the command line app to a WPF app.
From the WPF app display the current state of the LinkedList.
Data bind the UI control so any client actions are reflected in the display.

Speed is not a huge issue, as the WPF app is read-only and more informational.  I chose a LinkedList to support the needed client functionality.
I am having difficulty finding any tutorials and/or examples that can help.  Any suggestions on how I should approach this would be great.
Comment: Just curious: if speed is not an issue, why a LinkedList and not an `ObservableCollection`?
Comment: I have taken your advice and switched to an ObservableCollection, and so far, so good.  As I mentioned in a comment below, if I later need the performance and/or speed of the LinkedList solution, I will switch back.  Thanks!
Comment: Nice to hear that it's working but it wasn't advice; it was a question...
Answer:
Create a new class called ObservableLinkedList and implement INotifyCollectionChanged.
Give same methods in that class as LinkedList and internally forward all the methods to the contained linkedlist,
but also fire INotifyCollectionChanged events so WPF can know that your linked list changed.

For WPF to know that a bound collection has changed; it has to implement INotifyCollectionChanged
OR
Just trigger collectionview to be refreshed everytime you update the linkedlist like the following
<code>CollectionViewSource.GetDefaultView(ViewModel.TheCollectionProperty).Refresh();
</code>
Comment: +1: implementing a LinkedList that also implements INotifyCollectionChanged was how I was thinking of doing this one too.
Comment: This is what I was looking for (took a while to learn/implement).  Thanks!  BTW, though this works, I am going to simplify my solution to use the ObservableCollecton that Erno suggested and switch to this if performance and/or functionality becomes an issue.

Data Binding to a LinkedList?


$\int_0^{2\pi} \left(a\cos x+\sqrt{1-a^2\sin^2(x)}\right)^{2k} dt=2\pi\sum_{m=1}^k \binom{k}{m} \binom{k-1}{m-1}a^{2(k-m)}$

Question: I would like to know if there is a higher-level perspective to explain this result (or a simple way to prove it)? Thanks for help.
$$\int_0^{2\pi} \left(a\cos x+\sqrt{1-a^2\sin^2(x)}\right)^{2k} dt=2\pi\sum_{m=1}^k \binom{k}{m} \binom{k-1}{m-1}a^{2(k-m)}.$$
Comment: The RHS can be written as a convolution, and such convolution can be transformed into the LHS through the residue theorem. Related: http://mathworld.wolfram.com/FibonacciPolynomial.html
Comment: If $a > 1$ this integral is not defined
Comment: If you want you can only consider the case of 0<a<1
Answer: Here's my progress toward a (very long-winded and messy) solution. I think it's mostly complete; there's just one binomial sum at the end that I haven't figured out how to evaluate.
The first thing we'll do is manipulate the left-hand side to get rid of the square root, since it's probably the most annoying part of the expression.
$$\displaystyle\sum_{j=0}^{2n-1}\left[a\cos\left(\theta+\dfrac{j\pi}{n}\right)+\sqrt{1-a^2\sin^2\left(\theta+\dfrac{j\pi}n\right)}\right]^{2k}$$
$$= \displaystyle\sum_{j=0}^{n-1}\left[\left[a\cos\left(\theta+\dfrac{j\pi}{n}\right)+\sqrt{1-a^2\sin^2\left(\theta+\dfrac{j\pi}n\right)}\right]^{2k} + \left[a\cos\left(\theta+\dfrac{(j+n)\pi}{n}\right)+\sqrt{1-a^2\sin^2\left(\theta+\dfrac{(j+n)\pi}n\right)}\right]^{2k}\right]$$
$$= \displaystyle\sum_{j=0}^{n-1}\left[\left[a\cos\left(\theta+\dfrac{j\pi}{n}\right)+\sqrt{1-a^2\sin^2\left(\theta+\dfrac{j\pi}n\right)}\right]^{2k} + \left[-a\cos\left(\theta+\dfrac{j\pi}{n}\right)+\sqrt{1-a^2\sin^2\left(\theta+\dfrac{j\pi}n\right)}\right]^{2k}\right]$$
$$= \displaystyle\sum_{j=0}^{n-1}\left[\left[\sum_{m=0}^{2k}\binom{2k}{m}a^m\cos^m\left(\theta+\dfrac{j\pi}n\right)\left(1-a^2\sin^2\left(\theta+\dfrac{j\pi}n\right)\right)^{k-m/2}\right] + \left[\sum_{m=0}^{2k}\binom{2k}{m}(-a)^m\cos^m\left(\theta+\dfrac{j\pi}n\right)\left(1-a^2\sin^2\left(\theta+\dfrac{j\pi}n\right)\right)^{k-m/2}\right]\right]$$
$$= \displaystyle\sum_{j=0}^{n-1}\sum_{m=0}^{2k}\binom{2k}{m}\left(1+(-1)^m\right)a^m\cos^m\left(\theta+\dfrac{j\pi}n\right)\left(1-a^2\sin^2\left(\theta+\dfrac{j\pi}n\right)\right)^{k-m/2}$$
$$= \displaystyle\sum_{j=0}^{n-1}\sum_{m=0}^k\binom{2k}{2m}2a^{2m}\cos^{2m}\left(\theta+\dfrac{j\pi}n\right)\left(1-a^2\sin^2\left(\theta+\dfrac{j\pi}n\right)\right)^{k-m}$$
(In the last step, we switched to just summing over the even values of $m$, since the odd values vanish due to the $1+(-1)^m$.)
So now we've managed to get rid of that pesky square root. Now, since this problem has "roots of unity" written all over it, the next thing we'll try is interchanging the sums and trying to get the $j$ sum to simplify to something trivial.
$$\displaystyle\sum_{j=0}^{n-1}\sum_{m=0}^k\binom{2k}{2m}2a^{2m}\cos^{2m}\left(\theta+\dfrac{j\pi}n\right)\left(1-a^2\sin^2\left(\theta+\dfrac{j\pi}n\right)\right)^{k-m}$$
$$= 2\displaystyle\sum_{m=0}^k\binom{2k}{2m}a^{2m}\sum_{j=0}^{n-1}\cos^{2m}\left(\theta+\dfrac{j\pi}n\right)\left(1-a^2\sin^2\left(\theta+\dfrac{j\pi}n\right)\right)^{k-m}$$
$$= 2\displaystyle\sum_{m=0}^k\binom{2k}{2m}a^{2m}\sum_{j=0}^{n-1}\cos^{2m}\left(\theta+\dfrac{j\pi}n\right)\sum_{\ell=0}^{k-m}\binom{k-m}{\ell}(-1)^{\ell}a^{2\ell}\sin^{2\ell}\left(\theta+\dfrac{j\pi}n\right)$$
$$= 2\displaystyle\sum_{m=0}^k\sum_{\ell=0}^{k-m}\binom{2k}{2m}\binom{k-m}{\ell}(-1)^{\ell}a^{2\ell+2m}\sum_{j=0}^{n-1}\cos^{2m}\left(\theta+\dfrac{j\pi}n\right)\sin^{2\ell}\left(\theta+\dfrac{j\pi}n\right)$$
And now we concentrate on just the innermost sum. In the following, let $z=e^{i\theta}$ and $\omega=e^{\frac{i\pi}n}$. (So $\omega$ is a $2n$-th root of unity.) We note by Euler's Identity that
$$\cos\left(\theta+\dfrac{j\pi}n\right) = \dfrac{z\omega^j + \frac1{z\omega^j}}2$$ and
$$\sin\left(\theta+\dfrac{j\pi}n\right) = \dfrac{z\omega^j - \frac1{z\omega^j}}{2i}$$
So the inner sum becomes
$$\sum_{j=0}^{n-1}\cos^{2m}\left(\theta+\dfrac{j\pi}n\right)\sin^{2\ell}\left(\theta+\dfrac{j\pi}n\right)$$
$$= \sum_{j=0}^{n-1}\left(\dfrac{z\omega^j + \frac1{z\omega^j}}2\right)^{2m}\left(\dfrac{z\omega^j - \frac1{z\omega^j}}{2i}\right)^{2\ell}$$
$$= \dfrac{(-1)^{\ell}}{4^{\ell+m}}\sum_{j=0}^{n-1}\left(z\omega^j + \dfrac1{z\omega^j}\right)^{2m}\left(z\omega^j - \dfrac1{z\omega^j}\right)^{2\ell}$$
$$= \dfrac{(-1)^{\ell}}{4^{\ell+m}}\sum_{j=0}^{n-1}\left[\sum_{r=0}^{2m}\binom{2m}{r}\left(z\omega^j\right)^r\left(\dfrac1{z\omega^j}\right)^{2m-r}\right]\left[\sum_{s=0}^{2\ell}\binom{2\ell}{s}\left(z\omega^j\right)^s\left(-\dfrac1{z\omega^j}\right)^{2\ell-s}\right]$$
$$= \dfrac{(-1)^{\ell}}{4^{\ell+m}}\sum_{j=0}^{n-1}\sum_{r=0}^{2m}\sum_{s=0}^{2\ell}\binom{2m}{r}\binom{2\ell}{s}(-1)^s\left(z\omega^j\right)^{2(r+s-\ell-m)}$$
$$= \dfrac{(-1)^{\ell}}{4^{\ell+m}}\sum_{r=0}^{2m}\sum_{s=0}^{2\ell}\binom{2m}{r}\binom{2\ell}{s}(-1)^sz^{2(r+s-\ell-m)}\left[\sum_{j=0}^{n-1}\left(\omega^2\right)^{j(r+s-\ell-m)}\right]$$
Now, since $\omega^2$ is an $n$-th root of unity, the sum in brackets above is zero... unless $r+s-\ell-m$ is a multiple of $n$, in which case every term of that sum turns out to be 1, which gives a grand total of $n$ instead. Now, we need to look at our nested indices and figure out how large $r+s-\ell-m$ can get.
We know $0\le m\le k$, $0\le\ell\le k-m$, $0\le r\le 2m$, and $0\le s\le 2\ell$. The sum $r+s-\ell-m$ is minimized when $r=s=0$, and then since $\ell\le k-m$, $\ell+m\le k$, so the minimum is at $-k$. SImilarly, the sum is maximized when $r=2m$ and $s=2\ell$, which gives $\ell+m\le k$. Finally, $k<n$. So the only possible value of $r+s-\ell-m$ that is divisible by $n$ is $0$ itself, since $-n<r+s-\ell-m<n$.
Now we're going to rework the sum so that we only use values of $r$ and $s$ such that $r+s=\ell+m$. Then our sum is
$$= \dfrac{(-1)^{\ell}}{4^{\ell+m}}\sum_{r=0}^{2m}\sum_{s=0}^{2\ell}\binom{2m}{r}\binom{2\ell}{s}(-1)^sz^{2(r+s-\ell-m)}\left[\sum_{j=0}^{n-1}\left(\omega^2\right)^{j(r+s-\ell-m)}\right]$$
$$= \dfrac{(-1)^{\ell}}{4^{\ell+m}}\sum_{0\le r\le 2m;\,0\le s\le 2\ell;\,r+s=\ell+m}\binom{2m}{r}\binom{2\ell}{s}(-1)^sn$$
Now, we let $t=r-m=\ell-s$. Then $-m\le t\le m$, and $-\ell\le t\le\ell$. Using this information, we can simplify to a single sum:
$$\dfrac{n}{4^{\ell+m}}\sum_{t=-\min(\ell,m)}^{\min(\ell,m)}\binom{2m}{m+t}\binom{2\ell}{\ell+t}(-1)^t$$
Since the sum is symmetric, we can assume WLOG that $m\le \ell$ to get rid of the annoying index constraint.
$$\dfrac{n}{4^{\ell+m}}\sum_{t=-m}^{m}\binom{2m}{m+t}\binom{2\ell}{\ell+t}(-1)^t$$
$$=\dfrac{(-1)^mn}{4^{\ell+m}}\sum_{t=0}^{2m}\binom{2m}{t}\binom{2\ell}{\ell-m+t}(-1)^t$$
$$=\dfrac{(-1)^mn}{4^{\ell+m}}\dfrac{(2m)!(2\ell)!}{(m+\ell)!^2}\sum_{t=0}^{2m}\binom{\ell+m}{t}\binom{\ell+m}{2m-t}(-1)^t$$
And now we consider the binomial expansion of $(1+x)^{\ell+m}(1-x)^{\ell+m}$. The coefficient of $x^{2m}$ in this expansion is given by the sum $$\sum_{t=0}^{2m}\binom{\ell+m}{t}\binom{\ell+m}{2m-t}(-1)^t$$
due to expanding with the binomial theorem. Meanwhile, if we multiply using the difference of squares, this simplifies to $(1-x^2)^{\ell+m}$, which shows that $x^{2m}$ has a coefficient of $(-1)^m\binom{\ell+m}{m}$. So the two must be equal:
$$\sum_{t=0}^{2m}\binom{\ell+m}{t}\binom{\ell+m}{2m-t}(-1)^t=(-1)^m\binom{\ell+m}{m}$$.
(The above identity is stated as Equation 1.19 in [url=http://www.math.wvu.edu/~gould/Vol.4.PDF]this PDF[/url], which is where I eventually had to resort to looking in trying to evaluate this stubborn sum.)
Now that we have a closed form for our sum, we plug it back in.
$$\dfrac{n}{4^{\ell+m}}\sum_{t=-\min(\ell,m)}^{\min(\ell,m)}\binom{2m}{m+t}\binom{2\ell}{\ell+t}(-1)^t = \dfrac{n}{4^{\ell+m}}\dfrac{(2m)!(2\ell)!}{(m+\ell)!^2}\binom{\ell+m}{\ell} = \dfrac{n}{4^{\ell+m}}\dfrac{(2m)!(2\ell)!}{m!\ell!(m+\ell)!}$$
But this is all just the evaluation of the innermost sum with $j$. The original problem still has two more layers of summation! With our simplification, the problem now becomes
$$2n\displaystyle\sum_{m=0}^k\sum_{\ell=0}^{k-m}\binom{2k}{2m}\binom{k-m}{\ell}\dfrac{(-1)^{\ell}a^{2(\ell+m)}}{4^{\ell+m}}\dfrac{(2m)!(2\ell)!}{m!\ell!(m+\ell)!}$$
This is finally starting to look kind of like the expression on the right! Now, a change of variables is in order. We let $p=\ell+m$. (At this point, we're really starting to run out of letters of the alphabet to use for variable names...) Then, after suitably changing the indices in the double sum, we obtain
$$2n\displaystyle\sum_{p=0}^k\sum_{\ell=0}^{p}\binom{2k}{2p-2\ell}\binom{k+\ell-p}{\ell}\dfrac{(-1)^{\ell}a^{2p}}{4^p}\dfrac{(2p-2\ell)!(2\ell)!}{p!\ell!(p-\ell)!}$$
$$=2n\displaystyle\sum_{p=0}^k\dfrac{a^{2p}}{4^pp!}\left[\sum_{\ell=0}^{p}\binom{2k}{2p-2\ell}\binom{k+\ell-p}{\ell}\dfrac{(-1)^{\ell}(2p-2\ell)!(2\ell)!}{\ell!(p-\ell)!}\right]$$
We focus now on the inner sum.
$$\displaystyle\sum_{\ell=0}^{p}\binom{2k}{2p-2\ell}\binom{k+\ell-p}{\ell}\dfrac{(-1)^{\ell}(2p-2\ell)!(2\ell)!}{\ell!(p-\ell)!}$$
$$=\dfrac{(2k)!}{(k-p)!}\displaystyle\sum_{\ell=0}^{p}\binom{2\ell}{\ell}(-1)^{\ell}\dfrac{(k+\ell-p)!}{(2k+2\ell-2p)!(p-\ell)!}$$
$$=\dfrac{(2k)!}{k!(k-p)!}\displaystyle\sum_{\ell=0}^{p}(-1)^{\ell}\dfrac{\binom{2\ell}{\ell}\binom{k}{p-\ell}}{\binom{2k+2\ell-2p}{k+\ell-p}}$$
It remains to establish the following identity:
$$\sum_{\ell=0}^{p}(-1)^{\ell}\dfrac{\binom{2\ell}{\ell}\binom{k}{p-\ell}}{\binom{2k+2\ell-2p}{k+\ell-p}} = \dfrac{4^p\binom{k-1}{p}}{\binom{2k}{k}}$$
which can be easily checked for small values of $p$. (We use the convention that, if $p>k-1$, then $\binom{k-1}{p}=0$.)
[b]If the above identity, which I have not yet been able to prove rigorously, is true[/b], then the outer sum becomes
$$2n\displaystyle\sum_{p=0}^k\dfrac{a^{2p}}{4^pp!}\left[\dfrac{(2k)!}{k!(k-p)!}\dfrac{4^p\binom{k-1}{p}}{\binom{2k}{k}}\right]$$
$$=2n\displaystyle\sum_{p=0}^ka^{2p}\binom{k}{p}\binom{k-1}{p}$$
which becomes the desired expression after substituting $p=k-m$ and disregarding the $m=0$ case.
Comment: Even though it's long and looks messy, I can't help but appreciate how much brutal work you've put into this :)
Comment: @I hate over moderation
For the last identity, you can see this post:
https://math.stackexchange.com/questions/2603599/hard-combinatorial-identity-sum-l-0p-1l-binom2ll-binomkp-l-bino


If a song's key is Gb major - how do I play the chord Bm if its notes are not in that key?

Question: I'm trying to play the chords for a songs chord progression.
It goes:
Gb, Bm/Gb, Gb, Bm/Gb, Gb, Bm6

What are the notes I play on a piano for Bm/Gb?

Does is mean play both Bm AND Gb - or - Bm OR Gb?

Bm = B, D, Gb

B and D are not in the scale of Gb major - So do I still play "B, D, Gb" or do I need to play the closest "legal" notes that fit the scale?
Comment: Gb is the same (in tempered tuning) as F#, and Bm is the minor chord on the fourth scale of the key, i.e. iv. You could also call it Cbm if you wish to remain in Gb.
Comment: You play it as Bm: B, D, F# = Gb. Within a song, it is not necessary that every chord be a part of the overall key of that song.
Comment: No'am isn't chord IV in the key of F# maj = B major?
Comment: Aaron what about "Bm/Gb"? Does it mean play both chords at the same time?
Comment: You are correct that the IV chord is B major; however, the iv chord (the minor IV chord) is "borrowed" from Gb minor. This is known as "modal mixture." The slash in this case means "play B minor with Gb as the lowest pitch." For more on slash notation, see [What does the chord notation X/Y ("slash chord") mean?](https://music.stackexchange.com/questions/104163/what-does-the-chord-notation-x-y-slash-chord-mean).
Comment: @James: Note that I wrote 'iv', not 'IV': lower case Roman numerals signify minor chords.
Answer: First, it's important that you understand that there is absolutely no rule that says that a song has to use only the 7 diatonic notes of the key it is written in. Any note may be used in a chord or a melody at any time during a song.
As for your specific chord progression of Gb to Bm/Gb, the main problem with this progression is a poor enharmomic spelling. What that basically means is it is using accidentals in an illogical way, in this case, combining flats and sharps when there is no need to do it. Also, Gb (or F#) is an awkward key to begin with.
As it is, it's confusing because you have a Bm, B-D-F# with a Gb in the bass, which is also F#, the 5th of the Bm chord.
It is easier to think of this as F#, in which case the second chord would be simply Bm/F#, or a IV minor chord over I in the bass.
However if it has to be in Gb then the thing to do is think of it as Cbm/Gb. In this scenario, Cbm is Cb, Ebb, Gb and you'll notice the only note that is not in the key of Gb is the Ebb (the same as D).
Comment: +1 for mentioning that B minor does not really make sense* in Gb major context! (* unless it does)
Comment: @yo' thanks and you get an uptick for (*unless it does)
Answer:
What are the notes I play on a piano for Bm/Gb? Does is mean play both Bm AND Gb - or - Bm OR Gb?

This is "slash chord" notation. It means play the chord to the left of the slash over the bass tone to the right of the slash. Play the chord Bm over the bass Gb.

Bm = B, D, Gb

This system of chords uses what's called tertian harmony, chord built of stacked thirds above a root. You should learn to recite the gamut of letters in thirds - B D F A C E G B D... - and then you apply accidentals to set the appropriate intervals major thirds, perfect fifths, etc.
Bm is B D #F.
The alternate options of Gb or F# are called enharmonic equivalents. They are the same pitch, but enharmonically spelled differently. Chords should be spelled by what's intended. Bm is B D F# but B D Gb would be an odd augmented triad with an augmented third, surely not the intended chord.

...not in the scale of Gb major...do I need to play the closest "legal" notes that fit the scale?

No. Play what is written.
But in this case it will be a lot easier to talk about if the passage if first re-written to spell the chords correctly...
F#, Bm/F#, F#, Bm/F#, F#, Bm6
...and the scale will be F# major.
If you were to talk about this being in the key of F# major, you could then say the diatonic chord in F# major, rooted on B is a B major chord. However, in F# minor, the diatonic chord rooted on B is B minor. F# major and F# minor have the same tonic - F# - and so are called parallel keys. And, you can "borrow" chords between parallel keys. You can "borrow" Bm from F# minor and play it in F# major.
If you identify the chords with Roman numerals, it would be F#: I iv6/4 I iv6/4 I iiø4/2. The chord root B is the fourth degree of the scale so it's labelled iv. So, the progression is in F# major and borrowing the iv chord from the parallel minor.
Answer: Chord symbols like Gb, Bm, or Bm6 are literal, not relative to the key of the piece as a whole. So no matter what key a piece is in, Gb always comprises the pitches Gb Bb Db, Bm comprises B D F#, and Bm6 comprises B D F# G#.
The slash notation, in this case, indicates that Gb should be played in the bass. That is, Gb should be the lowest pitch played. It need not be part of the chord, though in this case it is (Gb = F#). Thus, Bm/Gb means "play a Bm chord and also play Gb in the bass."
For more on slash notation, see What does the chord notation X/Y ("slash chord") mean?.
Answer:
What are the notes I play on a piano for Bm/Gb?

The notes you play for Bm/G♭ are the same on any instrument. The symbol to the left of the slash indicates a chord. In this case, it's a Bm chord, which is B, D, and F♯. The symbol to the right of the slash is the bass note, which may or may not be a note of the chord on the left of the slash. In this case, that note is G♭, which is enharmonic to F♯. That means G♭ and F♯ share the same pitch (in equal temperament) but are named differently. You're correct that B and D are not in the G♭ major scale. Neither is F♯, for that matter.

Do I need to play the closest "legal" notes that fit the scale?

You play the chord indicated. It is common for non-diatonic chords to occur in a piece of music. That means that a piece of music in a particular key can "borrow" chords from another key. It doesn't necessarily--or even usually--mean that the key changes.
However, it is likely that whoever notated this music is confused. In the key of G♭ major, you would usually call this chord C♭m. A C♭ minor chord is C♭, E♭♭ (E double flat), and G♭. C♭ is enharmonic to B, E♭♭ is enharmonic to D, and G♭ is enharmonic to F♯. In this case, there would only be one note not in the key... E♭♭. You can extend the meaning of enharmonic to chords, meaning that their constituent pitches are the same as a differently-named chord. Therefore, C♭m/G♭ is enharmonic to Bm/F♯ and Bm/G♭.


Let a function take precedence/priority over another in Node.js

Question: I have a MongoClient function which seems to be asynchronous in nature. Followed by child process function which I am explicitly declaring as synchronous. The cp takes a parameter nextPort, and the value of nextPort is assigned inside MongoClient. Since cp.execSync takes precedence over MongoClient it doesn't take the new value of the variable rather the value it was declared with.
app.js
var nextPort=0; //Declaration
MongoClient.connect(url1,{ useUnifiedTopology: true }, function(err, db) {
    if (err) throw err;
    var dbo = db.db("mydb");
    dbo.collection("mycol").distinct('port', function(err, result) {
      if (err) throw err;
      portArr=result;
      console.log(portArr.length);
      nextPort = portArr[portArr.length-1]+1; //New Value of nextPort
      console.log(nextPort);
      db.close();
    });
});

console.log('Container Created\n');
console.log(nextPort);
const result3 = cp.execSync('docker run -d -p '+nextPort+':27017 -v '+volumeLoc+' --name '+containerName+' mongo:'+version);
//Taking the declaration value instead of new
console.log(result3.toString());

How do I execute MongoClient before cp.execSync. (Also, I'd really appreciate if the solution doesn't deal with promises)
Comment: Asking for a solution that doesn't involve promises is like asking to pound a nail in without a hammer when it's the best tool for the job.  Promises are the best tool the Javascript language has for sequencing asynchronous operations and the sooner you learn how to use them with your database, the faster you can write good, clear and solid code for problems like this.
Comment: `cp.execSync` doesn't really take precedence, it's just running before the `connect` and `distinct` async functions have completed. If you don't want promises, the `cp.execSync` needs to be nested within the async functions (around the `console.log(nextPort)`)
Answer: Try to learn the async / await syntax for cleaner code. I dont know if this is just a script or an function, anyway, i wrapped it in an async IIFE:
(async () => {
  var nextPort = 0; //Declaration
  try {
    var db = await MongoClient.connect(url1, { useUnifiedTopology: true });

    var dbo = db.db("mydb");

    var result = await dbo.collection("mycol").distinct("port");
    portArr = result;
    console.log(portArr.length);
    nextPort = portArr[portArr.length - 1] + 1; //New Value of nextPort
    console.log(nextPort);
    db.close();
  } catch (err) {
    throw err;
  }

  console.log("Container Created\n");
  console.log(nextPort);
  const result3 = cp.execSync(
    "docker run -d -p " +
      nextPort +
      ":27017 -v " +
      volumeLoc +
      " --name " +
      containerName +
      " mongo:" +
      version
  );
  //Taking the declaration value instead of new
  console.log(result3.toString());
})();

Answer: You either need to call your cp.execSync inside the callback function you provided to MongoClient.connect or you should use async/await syntax, e.g.:
const client = await MongoClient.connect(url1, { useUnifiedTopology: true })
const result3 = cp.execSync(...)

Make sure your wrapper function (factory method to instantiate a client in
a separate module would be better approach) is async, take a look at the example


Difference between using an interaction term for categorical predictors vs. creating subgroups (linear regression)

Question: In a linear regression with two categorical predictor variables:
Let's say the most simple case (e.g. 0= male, 1=female; 0= no vegetarian, 1= vegetarian), so based on those two nominal variable a total of four subgroups could be found in the sampel.
In the regression model we could now include the two main effects + one interaction effect for those two variables.
However, if instead we would make a new variable that identifies the four groups
0=male+no vegetarian
1=female + no vegetarian
2=male + vegetarian
3= female vegetarian
and would put that (in dummified form) in the regression analysis what information would we lose?
The ability to see whether overall differences for only gender and only vegetarianism exist (thus the main effects for those variables)? Or are there more disadvantage?
Answer: I suggest you read this article that presents an example that highlights presentational (and not quantitative) differences between ANOVA and regression models.
To quote part of the referenced article:

In the ANOVA, the categorical variable is effect coded. This means that the categories are coded with 1's and -1 so that each category's mean is compared to the grand mean.
In the regression, the categorical variable is dummy coded**, which means that each category's intercept is compared to the reference group's intercept.  Since the intercept is defined as the mean value when all other predictors = 0, and there are no other predictors, the three intercepts are just means.
In both analyses, Job Category has an F=69.192, with a p < .001.  Highly significant.
In the ANOVA, we find the means of the three groups are:
Clerical:      85.039
Custodial: 298.111
Manager:   77.619
In the Regression, we find these coefficients:
Intercept:    77.619
Clerical:         7.420
Custodial: 220.492
The intercept is simply the mean of the reference group, Managers.  The coefficients for the other two groups are the differences in the mean between the reference group and the other groups.
You'll notice, for example, that the regression coefficient for Clerical is the difference between the mean for Clerical, 85.039, and the Intercept, or mean for Manager (85.039 – 77.619 = 7.420).  The same works for Custodial.
So an ANOVA reports each mean and a p-value that says at least two are significantly different.  A regression reports only one mean(as an intercept), and the differences between that one and all other means, but the p-values evaluate those specific comparisons.
It's all the same model; the same information but presented in different ways.  Understand what the model tells you in each way, and you are empowered.
I suggest you try this little exercise with any data set, then add in a second categorical variable, first without, then with an interaction.  Go through the means and the re


Calculus - Infinite Series

Question: Decide whether the infinite series converges of diverges.
$$\sum_{n=1}^\infty \frac{2^n+3^n}{3^n+4^n}$$
My thought process:
   The nth term test doesn't seem viable after initial use.
   The comparison function I derived for DCT/LCT is: $\frac{3^n}{4^n}$.
   I cannot create an appropriate inequality between the given function and my comparison function I found, so I tried LCT. I am aware that
$\sum_{i=1}^\infty \frac{3^n}{4^n}$ is geometric and because the common ratio (r) is $ \frac{3}{4}$, $-1<r<1$ the series converges, however I cannot compute the limit LCT requires.
Application of the root test would seem unbeneficial because roots do not split over sums.
As for the ratio test I was also unsuccessful in proceeding with the computation of the limit.
The above are the only tests I have learned as of right now. My question is what test should I be looking to utilize to determine convergence or divergence?
Comment: $2^n +3^n < 2\times 3^n$, $3^n +4^n > 4^n$.
Comment: When you comeback in this site, please [read this](https://math.meta.stackexchange.com/questions/3399/why-should-we-accept-answers)
Answer: Use the comparison test.
For every $n$, let
$$
a_n = \dfrac{2^n + 3^n}{3^n + 4^n}.
$$
The given series is $\sum_{n=1}^{\infty} a_n$. We will show that it converges.
For every $n$,
$$
a_n = \dfrac{2^n + 3^n}{3^n + 4^n} \leq \dfrac{3^n + 3^n}{4^n} = 2 \biggl( \dfrac{3}{4} \biggr)^n.
$$
For every $n$, let $b_n = 2(\tfrac{3}{4})^n$. So $a_n \leq b_n$ for every $n$. Since $\sum_{n=1}^{\infty} (\tfrac{3}{4})^n$ is a geometric series with common ratio $\tfrac{3}{4}$, it converges. Thus, $2 \sum_{n=1}^{\infty} (\tfrac{3}{4})^n$ converges also, i.e., $\sum_{n=1}^{\infty} b_n$ converges. Therefore, $\sum_{n=1}^{\infty} a_n$ converges by the comparison test.
Answer: Let us try to split:
$$\frac{2^n+3^n}{3^n+4^n}=\frac{2^n}{3^n+4^n}+\frac{3^n}{3^n+4^n}.$$
Then we consider each the following series:
$$\sum_{n=1}^\infty \frac{2^n}{3^n+4^n}\quad\text{and}\quad \sum_{n=1}^\infty \frac{3^n}{3^n+4^n}\tag 1$$
As we can see, we have
$$\frac{2^n}{3^n+4^n}<\frac{2^n}{3^n}=\bigg(\frac{2}{3}\bigg)^n\quad \forall n\in\Bbb N$$ and
$$\frac{3^n}{3^n+4^n}<\frac{3^n}{4^n}=\bigg(\frac{3}{4}\bigg)^n\quad \forall n\in\Bbb N$$
Convergence of the given two series in $(1)$ follows from the Comparison Test because
$$\sum_{n=1}^\infty \bigg(\frac{2}{3}\bigg)^n\quad\text{and}\quad \sum_{n=1}^\infty \bigg(\frac{3}{4}\bigg)^n$$  are both convergent. Hence, the series
$$\sum_{n=1}^\infty \frac{2^n+3^n}{3^n+4^n}$$ is convergent (being a sum of two convergent series).
Answer: It's enough to notice that all terms $a_n$ of your sequence satisfy $$
0< a_n < q^n \tag{1}
$$
for an appropriately chosen $q<1$. For example, you can choose $q=0.9$, and $(1)$ will be true for all $n\ge1$. Then you can use the fact that the geometric series
$$
\sum_{n=1}^\infty q^n = {q\over 1-q}
$$
converges; therefore your series $\sum_{n=1}^\infty a_n$ converges too, by comparison test.
Answer: Besides the already provided solutions, I'd like to point out that both the LCT and the Root Test do work here too.
If we're applying the LCT to $\sum_{n=1}^\infty \frac{2^n+3^n}{3^n+4^n}$ and $\sum_{n=1}^\infty \frac{3^n}{4^n}=\sum_{n=1}^\infty \left(\frac{3}{4}\right)^n$:
$$\frac{\frac{2^n+3^n}{3^n+4^n}}{\frac{3^n}{4^n}}=\frac{2^n+3^n}{3^n+4^n}\cdot\frac{4^n}{3^n}=\frac{8^n+12^n}{9^n+12^n}=\frac{(8^n+12^n)\color{red}{\div12^n}}{(9^n+12^n)\color{red}{\div12^n}}=\frac{\left(\frac{8}{12}\right)^n+1}{\left(\frac{9}{12}\right)^n+1}\to\frac{0+1}{0+1}=1,$$
so the LCT applies to these two series and they behave the same way.
A similar trick works with the Root Test too. We can factor our $3^n$ and $4^n$ in the numerator and the denominator, respectively, to find that
$$\sqrt[n]{\frac{2^n+3^n}{3^n+4^n}}=\sqrt[n]{\frac{\color{red}{3^n\cdot}\left(\left(\frac{2}{3}\right)^n+1\right)}{\color{red}{4^n\cdot}\left(\left(\frac{3}{4}\right)^n+1\right)}}=\color{red}{\frac{3}{4}\cdot}\sqrt[n]{\frac{\left(\frac{2}{3}\right)^n+1}{\left(\frac{3}{4}\right)^n+1}}\to\frac{3}{4}\cdot1=\frac{3}{4}.$$
UPDATE: I've just noticed that the OP mentioned the Ratio Test too. I'm not going to type one more solution, but the limit of the fraction in the Ratio Test can be simplified here using a trick similar to the one used in the LCT calculation above.
Comment: Very useful. I completely overlooked some of the manipulations/tricks you utilized. Cheers!

Calculus - Infinite Series


Calculating the probability of 2 for the sum of two dices, knowing that the sum will be even.

Question: I'm having a problem with calculating the probability of the followig scenario. I have two normal dices (6 sides a piece). I know that the sum of the two tosses is even. I want to know what the chance is that the sum of the two tosses is 2. In other words I want to calculate P(X = 2 | X is even). Where X is the sum of the points. I believe the answer should be 1/18 because there're 36 possible scenarios (1, 1) ... (1,6), (2.1) ... (6,6), from these 36 scenario's 18 are even. And only one of those gives 2 as the sum.
When I want to calculate this, I use P(A|B) = (P(A intersection B) / P(B)). I rewrite A intersection B to P(A)P(B) this however doens't result in 1/18. Where am I going wrong?
Comment: That's $2$ *dice*, I'll warrant.
Comment: Here $A\cap B=A$, hence $P(A\cap B)=P(A)$ where $A$ stands for $X=2$ and $B$ for $X$ is even.
Comment: Welcome to the math.SE! For some basic information about writing math at this site see, e.g.,
[here](http://meta.math.stackexchange.com/questions/5020/),
[here](http://meta.stackexchange.com/a/70559/155238),
[here](http://meta.math.stackexchange.com/questions/1773/) and
[here](http://math.stackexchange.com/help/notation).
Comment: As for the question per se, the main problem is that the equality $P(A \cap B) = P(A) P(B)$ only holds if $A$ and $B$ are independent. In this case, they aren't.
Comment: Thx for the help all, I'll go through the writing math documentation.
Answer: Note that $A$ and $B$ are NOT independent, so $P(A \cap B) \neq P(A)P(B)$. Indeed, notice that if your sum happens to be $2$, then you automatically have an even sum. In set notation, this means that $A \subseteq B$, which tells us that $A \cap B = A$. Thus:
$$
P(A \mid B)
= \frac{P(A \cap B)}{P(B)}
= \frac{P(A)}{P(B)}
= \frac{1/36}{18/36}
= \frac{1}{18}
$$
as desired.


Close GWT navigation bar (MenuBar) items when focus is lost

Question: I have a navigation bar that is just a GWT MenuBar component which has other MenuBars with their own MenuItems. Just like http://samples.gwtproject.org/samples/Showcase/Showcase.html#!CwMenuBar
GWT MenuBar opens the cascade menu bar when you hover over it (provided you have .setAutoOpen(true)). I would like to create the effect that the menu closes when you stop hovering (because I find it annoying that the menu remains open just because I accidentally hovered over it, for example).
I have read as much as I have been able to find on Google. I tried doing something like
<code>    myMenuBar.addHandler(new BlurHandler() {
         @Override
        public void onBlur(BlurEvent event) {
            myMenuBar.closeAllChildren(true);
        }
    }, BlurEvent.getType());
</code>
(onBlur should be the opposite to onFocus) only to discover that the MenuBar loses focus when I hover over its children (so I can't select anything, because the main MenuBar loses focus and it closes, making the navigation bar useless), but annoyingly, it wont lose focus if I hover anywhere else (top, sides, etc., probably because there are no other components there to steal the focus), leaving the cascade menu open.
I tried using .setFocusOnHoverEnabled(false), but without focus I can't know when I'm not hovering over the MenuBar or its MenuItems.
I am starting to think I can't actually override this behavior with the GWT MenuBar (A menu in JavaScript could behave this way, closing the cascade menu when you stop hovering over it, but since GWT is writing that JS code for me, I guess that the price to pay is that it will behave that way...), so, please any advice about either how to do this with GWT or to confirm it is not possible is appreciated.
Answer: It seems this behavior (lets say autoHide on onBlur) is not possible with the GWT standard components. The MenuBar and MenuItem components simply don't behave that way and can't be forced to do so.
What I have tried with event listeners and handlers didn't seem to work.
Best approach to achieve this seems to be building custom components.


What is the meaning of super script 2 subscript 2 within the context of norms?

Question: I am new to optimization. I keep seeing equations that have a superscript 2 and a subscript 2 on the right-hand side of a norm. For instance, here is the least squares equation
min $ ||Ax-b||^2_2$
I think I understand the superscript 2: it means to square the value of the norm. But what is the subscript 2? How should I read these equations?
Comment: $||\theta||_p$ is the $\ell_p$-norm of $\theta$. Let's say $\theta$ is $d$-dimensional, then $||\theta||_p = \left(\sum_{i=1}^d |\theta_i|^p\right)^\frac{1}{p}$.
Comment: Single vertical bars are used for absolute value (magnitude): $|\theta|$
Comment: Thanks!...but what is the superscript 2 for?...the subsript is for the pth norm....the superscript is for?
Comment: @user1467929: Squaring - if it's anything else they'd surely have said.
Answer: You are right about the superscript. The subscript $||.||_p$ specifies the $p$-norm.
Therefore:
$$||x_i||_p=(\sum_i|x_i|^p)^{1/p}$$
And:
$$||x_i||_p^p=\sum_i|x_i|^p$$
Comment: ah. And there are conventions for the meanings of the subscripts I see. https://en.wikipedia.org/wiki/Norm_(mathematics)#p-norm. So like 1 = taxicab norm, 2=euclid norm etc
Comment: @bernie2436: These are special cases of the general definition given in the answer above (except maybe the sup-norm with $p = \infty$)
Comment: This is a good explanation.
Answer: $\|x\|_2$ is the Euclidean norm of the vector $x$; $\|x\|_2^2$ is the squared Euclidean norm of $x$. Note that as the Euclidean norm is probably the mostly commonly used norm people routinely abbreviated by $\|x\|$. By definition when assuming a Euclidean vector space: $\|x\|_2 := \sqrt{x_1^2 + x_2^2 + \dots + x_n^2}$.
As mentioned in the comments, the subscript $p$ refers to the degree of the norm. Other commonly used norms are for $p = 0$, $p = 1$ and $p = \infty$. For $p=0$ one gets the number of non-zero elements in $x$, for $p=1$ (ie. $\|x\|_1$) one gets the Manhattan norm and for $p = \infty$ one gets the maximum absolute value from the elements in $x$. Both $p = 0$ and $p = 1$ are popular in sparse/compressed application settings where one wants to "urge" some coefficient(s) to be zero.


How to correctly measure effect on heavy-tailed distribution

Question: I ran an experiment on my website where I randomly assigned users to either the treatment or control group, and have two questions about how to correctly compute significance of the results.
Some context: The outcome variable is the total number of actions they took on my website. I am computing the mean number of actions taken by users in my control and treatment groups, respectively: $A_C = \frac{\sum_{i \in C} a_i }{|C|}$, $A_T = \frac{\sum_{i \in T} a_i}{|T|}$ (where $T$ and $C$ are my treatment and control groups and $a_i$ is the number of actions performed by user $i$). Is $A_T-A_C$ a reasonable outcome to measure? My concern is that since the $a_i$'s are distributed according to a heavy-tailed distribution, the mean is heavily skewed by a few power users. Usually I'd take the median, but the tails are so heavy that the median is very small.
Another thing I have measured is the KS statistic on the distributions of number of actions for users in the control and treatment groups.

Is the difference in means or KS-statistic a more reasonable way to determine if the treatment had an effect?
I am calculating bootstrapped p values by computing the same measures (difference in means and KS statistic) for many random splits of the user population, then counting how many random splits give rise to "more significant" values than my experimental control/treatment split gave. Is this correct?
Answer: There are two issues, though discussion of them are somewhat related:
i) What's a meaningful measure of treatment effect in the population?
ii) What's a good way to measure/test it in samples?
If you're especially interested in the difference in population means, then you should be looking to base your inference on that. On the other hand, often people really have a concept of just comparing the size "I want to know which one tends to be typically smaller". Indeed, a ratio of typical values may be just as meaningful to them as a difference, for example.
If the difference of population means is not especially more meaningful than say a ratio of means or a difference in medians, then you might consider a nonparametric test, such as a Wilcoxon-Mann-Whitney test (often called a Wilcoxon Rank-Sum test or a Mann-Whitney U test). This is good at pickup up differences and is not very badly affected by large outliers. In addition, it's equally adept at picking up that a ratio of typical values differs from 1 (this would be the same as looking at the difference of logs, and it will take the same value on the log scale as it would on the original scale). On the other hand it's also sensitive to other kinds of location measure than the mean, and can be conceived in terms of the probability that a random value from one population exceeds a random value from the other (and you can even write your hypotheses that way if you choose).
If the difference in population means is central, then you look at that, but as you note, in samples the sample means are sensitive to a few large values. This can certainly affect the usual t-test, but it's possible to use, for example, a permutation test or a bootstrap test (the two are quite similar).
A Kolmogorov-Smirnov test is sensitive to much more than a tendency for one group to be larger or smaller than the other. For example, if the treatment makes the observations more variable without making them larger, the KS test will still tend to reject the null - it will tell you they're different, because it's a test for equality of distributions. By having power against such alternatives, it has less power against alternatives that measure tendency to be larger or smaller.
The fact that you'd consider a Kolmogorov-Smirnov test makes me lean toward suggesting the Wilcoxon-Mann-Whitney as very likely a substantially better option.
If you haven't considered it, you might want to look into the possibility of matching or otherwise adjusting for use level. If you have some way of measuring/identifying the heavy users you could either match on it (and do a paired test), or you could use it as a covariate (or perhaps as an exposure measure) in a GLM. This will tend to give you better power to identify a treatment-difference.
Answer: This is an old thread but as lots of people are reading it...
From the description it sounds like you have a skewed distribution, not a heavy tailed distribution as those terms are commonly used.  This matters as the remedies are different.  For a skewed distribution, a common remedy is to transform the data to something like a normal distribution.  Taking logs is one common such transformation.  I have no way of knowing if logs would work here.  Google "ladder of transformations".
Your "2" also sounds reasonable though it sounds like a permutation test rather than bootstrapping.


Upper bound of the spectral norm of a matrix power

Question: Let $A\in\mathbb{C}^{n\times n}$ be a complex valued square matrix which can be written as $A=PUP$ in which $P$ is a projector and $U$ is a unitary matrix. The interesting case is $P$ and $U$ do not commute.
The matrix $A$ is not normal, and I would like to upper bound the 2-norm of $A^{n-1}$. It is the case that $\|A\|=1$, so an trivial upper bound is $\|A^{n-1}\|\leq\|A\|^{n-1}=1$. Is it possible to find a bound which is strictly less than 1?
I tried to read through some articles, e.g., this thesis, in particular, Chapter 3, but did not find an obvious approach.
Comment: If the spectral radius of $A$ is $1$ (as you write), then there is an eigenvalue of $A$ on the unit circle. This then also holds for any $A^k$. Hence also $\rho(A^{n-1})=1$ and thus $\|A^{n-1}\|=1$.
Comment: It is not necessarily the case $\|A^{n-1}\|=1$; we may take the answer by @Omnomnomnom as an example.
Comment: So, why do you write $\rho(A)=1$ in your question? This is not the case in Omnomnom's example.
Comment: Oh I see. But did you claim that $\rho(A)^k=\|A^k\|$? I am not sure if that is the case when $A$ is not normal.
Comment: Are they orthogonal projectors?
Comment: @user50394 No, I did not claim that. I just claimed what I wrote. Again, if $\rho(A)=1$, then $A$ has an eigenvalue on the unit circle, $Ax = ax$ with $|a|=1$. Hence $A^kx = a^kx$, so $A^k$ has the eigenvalue $a^k$, which is also on the unit circle. Consequently, $1 = \rho(A^k) \le\|A^k\|\le 1$ and therefore $\|A^k\|=1$ for all $k$.
Comment: @amsmath Thanks. You're right. Then I'll have to modify my question. I had observation that there exists an $x$ such that $\|Ax\|=\|x\|$ but such an $x$ cannot be an eigenvector in the problem I'm looking at.
Comment: @Geronimo Yes they are.
Comment: @user50394 I think it is even possible that $A^{n-1} = 0$, even if $P$ is $(n-1)$-dimensional.
Comment: @amsmath I think so. Taking U to be an $n$-cycle permutation matrix and P to be diagonal seems to give you $A^{n-1}=0$.
Comment: @user50394 Exactly. That's what I just found out. For example, take $P = \left(\begin{matrix}1 & 0 & 0\\0 & 1 & 0\\0 & 0 & 0\end{matrix}\right)$ and $U = \left(\begin{matrix}0 & 1 & 0\\0 & 0 & 1\\1 & 0 & 0\end{matrix}\right)$.
Comment: @user50394 On the other hand, if $P$ maps to a subspace that is invariant under $U$, you have $\|A^k\|=\rho(A^k) = 1$ for all $k$. That's the other extreme, where $A$ is actually normal.
Comment: @amsmath That's right.
Answer: Taking
$$
P = \pmatrix{1&0\\0&0}, \quad U = \pmatrix{\sqrt{1 - \epsilon^2} & -\epsilon \\ \epsilon & \sqrt{1 - \epsilon^2}}
$$
is enough for us to see that $\|(PUP)^{n-1}\|$ can be made arbitrarily close to $1$ in the case of $n = 2$.  A similar example works for arbitrary $n$.  That is, it's enough to take
$$
\pmatrix{1&0\\0&0_{(n-1)\times(n-1)}}, \quad \pmatrix{U&0\\0&I_{n-2}}
$$
for sufficiently small $\epsilon > 0$.
Comment: I would suspect, however, that it is possible to come up with a non-trivial bound which depends on $\|PU - UP\|$.
Comment: Thanks, @Omnomnomnom. I think I would view it as that if the projector is of rank one, then the upper bound is trivial. Perhaps a more interesting case to me is that if $P$ is of rank say $n-1$ then can we say something about the upper bound?
Comment: @user50394 the answer is still no.  If $\tilde P$ denotes the bigger projection matrix, consider $I - \tilde P$
Comment: Not sure if I understand it. Your answer seems to claim that $\|((I-P)U(I-P))^{n-1}\|=\|(PUP)^{n-1}\|$ but I don't see why that should be the case.
Comment: You should find that $(I-P)U(I-P)$ is a diagonal matrix.  Take it from there.
Comment: Never mind, I've made a mistake.  You're right


correlation between basis vectors

Question: how come Matlab give me the result corr(u,v)=-1
u=[1 0]' and v=[0 1]'  (i.e., two orthogonal column vectors, basis of the Euclidean plane ...)
Suddenly this makes no sense to me ... their scalar product = 0 ... they should be perfectly UNcorrelated?
i know it works out to -1 with the correlation formula $dot((x-mean(x)),(y-mean(y))/(norm(x)*norm(y))$ but could someone enlighten me ? (it's very frustrating ... i seem to miss something (and I have been working with such things for a while...)
To summarize: why (logical understanding point of view) are they negatively perfectly correlated (-1) whereas I would expect them to be perfectly UNCORRELATED (0) ?
Answer: We have two data points: (u[0], v[0]) and (u[1], v[1]). In terms of $x$ and $y$ axis, when $x=0$ then $y=1$. When $x=1$, $y$ went down and became $y=0$. So when $x$ increases, $y$ decreases. I wouldn't interpret the data points as vectors. Even if you were to interpret them as vectors, clearly the two vectors are orthogonal so there is perfect anti-correlation. No correlation means if $x$ is increasing $y$ stays the same
Comment: oh thanks yes of course it makes perfectly sense ... i wonder why I made this terrible confusion... any idea why?
Comment: Well it can be hard to see the relation when there are only two data points
Comment: yes that's true but what about orthogonality? How would you define "relation" or whatever we can call it, between correlation and orthogonal vectors such as U and V here
Comment: also the fact that there is a dot product in the definition of CORRELATION is misleading because as they are orthogonal...
Comment: Note that your two data points are not $u$ and $v$. $u$ contains all Xs and $v$ contains all Ys. Your data points are $(u[0], v[0])$ and $(u[1], v[1])$(which happen to be the same as $u$ and $v$). Nevertheless, you need to first subtract the mean from each direction and then visualize the vectors. You get something like $(0.5, -0.5)$ and $(-0.5, 0.5)$ which you can see they point in different directions. I will update my answer to add an intuitive explanation
Comment: also i just thought that as we can interpret the correlation of the centered vectors as the cosine of the angle between these centered vectors, then arccos(-1) = 180 degrees which 2as far as they can be"in a sense because 360 degrees = 0 = colinear and same sign
Comment: yes i think i understand what you mean, (0.5, -0.5) and (-0.5, 0.5 ) are the centered vectors which are at 180 degrees resulting in a dot prod of -0.5, this time and not 90 degrees. what do you think of my previous thought?
Comment: Yes you have the correct intuition. The angle of the centered vectors does indeed capture the notion of correlation since it also ignores the length of each vector(which is the reason why we also normalize)
Comment: hum interesting thanks. yet what to say about ortogonality ?
Comment: Orthogonality was basically an accident here. $(1,2)$ and $(2,1)$ would give you the same result and they are not orthogonal. That's why I prefer to not interpret the data points as vectors. But if you prefer vectors then you can try and visualize the difference vector. You can see that both in my example and yours, it's the same.
Comment: ok we can clear it but if possible i would very much like to speak to you in private (if you want)? i can quickly drop and remove an e-mail addr (i m doing a PhD im computer science )
Comment: oh ok found it. I will contact you at your email there then

correlation between basis vectors


sed is ignoring some matches

Question: I'm trying to replace all matches of http to https using backreference:
example test3.txt file:
http://stronka.wpblog.internal http://stronka.wpblog.internal
abc
jdfgijdf dfijog http://stronka.wpblog.internal dfgtdgrtg http://stronka.wpblog.internal/ sfdgth http://stronka.wpblog.internal/dupa drgfthj
ghj gjerioghj fhjdf http://stronka.wpblog.internal/

and when I run sed against the test3.txt file:
~# sed -r 's#http(://.*.wpblog.internal)#https\1#g' test3.txt
https://stronka.wpblog.internal http://stronka.wpblog.internal
abc
jdfgijdf dfijog https://stronka.wpblog.internal dfgtdgrtg https://stronka.wpblog.internal/ sfdgth http://stronka.wpblog.internal/dupa drgfthj
ghj gjerioghj fhjdf https://stronka.wpblog.internal/

Line 1 second link remains unchanged, line 2 third link remains unchanged, I'm lost, how could I tell sed to replace everything that is matching?
Comment: Just use `sed 's#http://#https://#g'`
Comment: How about this: `sed 's/http:\/\//https:\/\//g'`
Comment: your `.*` is consuming the whole intermediary part of the string;  Change your pattern to: s#http(://.*.wpblog.internal)#\1# and it will be obvious .
Answer: Because the .* wildcard is greedy, i.e. it will consume as much as possible of the line.
The simplest solution by far is to not use a wildcard at all; then sed does precisely what you expect on the simple input you provided.
sed 's#http://#https://#g' test3.txt

(Nothing in this regex needs anything except bog-standard 1968 regex, so the -r option - or its Linux equivalent -E - is not necessary or useful here.)
If for some reason you want a wildcard, use one which doesn't match across URL boundaries. In your example data, spaces seem to separate distinct URLs, so we can match greedily as many non-space characters as possible:
sed -r 's#http(://[^ ]*\.wpblog\.internal)#https\1#g' test3.txt

(Notice also how we use \. to match literal dots.)
Modern regex dialects like Perl's have non-greedy wildcards, but even then, it's better to use a regex which actually means what you want.
Answer: Try below:
sed -r 's/\bhttp\b/https/g'

\b is used to set boundaries around "http"
Answer: Based on the replies I've replaced the greedy wildcard .*:
sed -E 's#http(://[a-zA-Z0-9.-]*\.wpblog\.internal)#https\1#g'
And it's working as it should now, thank you all!

sed is ignoring some matches


find out origin of script call

Question: When loading a website I get this warning and I can't find the origin of the call:

In the network pane I found that it was initiated by js:45, but I have no idea where js:45 is coming from:

At this point I'm stuck.
It is a WordPress site and I can't seem to find the function/plugin which loads those scripts.
Any ideas how to find the function that originally loads those scripts?
Comment: can you give us that link?
Comment: https://chargetech.com
Answer: The following is the script that is being loaded and will eventually log that warning due to a missing API key.

You'd need to look for the file that this script tag is in on your server. It's not possible for us to work out which file it is originating in on the client, as the server will send a generated response from multiple resources on the server.
Comment: Thanks mate! I was so caught up with finding the solution in the debugger that I didn't scan the source code properly. Fixing it was easy now.

find out origin of script call


Writing the iterative output into a file in python

Question: I am trying to write the output of my print statements into an output file instead of printing them at console. Is there any simple way to do that without affecting the code written in my print statements?
Code :-
outputfile = open('output1.txt','w')
outputfile.write("Order_id  Order_date  User_id    Avg_Item_Price    Start_page_url     Error_msg")

for i in inputm[1:]:
     if '::' in i[0] or ':' not in i[0]:
         print('\n',"This is not a valid order record.")
     else:
         print('\n',i[0].split(':')[0]
                              ,str(datetime.strptime(i[0].split(':')[1],'%Y%m%d'))[:10]
                              ,i[1]
                              ,round(sum( float(v) if v else 0.0 for v in i[2:6])/4,2)
                              ,i[6] if Counter(i[6][0:23])  == Counter("http://www.google.com") else '                              '
                              ,'Valid URL' if Counter(i[6][0:23])  == Counter("http://www.google.com")  else 'Invalid URL'
                          )

outputfile.close()

Comment: just change `print()` with `outputfile.write()` is not working ?
Comment: No that doesnt work.... because the internal functions used with in print seem to be print specific...
Answer: You need to format your string before writing to file!!
print('\n,',"This is not a valid order record.")

to
output file.write('\n %s'%("This is not a valid order record.")

that is
outputfile = open('output1.txt','w')

outputfile.write("Order_id  Order_date  User_id    Avg_Item_Price    Start_page_url     Error_msg")

for i in inputm[1:]:
     if '::' in i[0] or ':' not in i[0]:
         outputfile.write('\n %s'%("This is not a valid order record."))
     else:
         outputfile.write('\n%s %s %s %f %s %s'%(i[0].split(':')[0]
                              ,str(datetime.strptime(i[0].split(':')[1],'%Y%m%d'))[:10]
                              ,str(i[1])
                              ,round(sum( float(v) if v else 0.0 for v in i[2:6])/4,2)
                              ,i[6] if Counter(i[6][0:23])  == Counter("http://www.google.com") else '                              '
                              ,'Valid URL' if Counter(i[6][0:23])  == Counter("http://www.google.com")  else 'Invalid URL'))

outputfile.close()

Answer: If you don't want to change any of your code, you could change the print function to append to the file instead:
def print(*args):
    with open("output1.txt", "a") as outputfile:
        outputfile.write(" ".join(str(arg) for arg in args) + "\n")

But it would be better to create a new function like this:
def write_to_file(*args):
    with open("output1.txt", "a") as outputfile:
        outputfile.write(" ".join(str(arg) for arg in args) + "\n")

write_to_file("Order_id  Order_date  User_id    Avg_Item_Price    Start_page_url     Error_msg")

for i in inputm[1:]:
     if '::' in i[0] or ':' not in i[0]:
         write_to_file('\n',"This is not a valid order record.")
     else:
         write_to_file('\n',i[0].split(':')[0]
                              ,str(datetime.strptime(i[0].split(':')[1],'%Y%m%d'))[:10]
                              ,i[1]
                              ,round(sum( float(v) if v else 0.0 for v in i[2:6])/4,2)
                              ,i[6] if Counter(i[6][0:23])  == Counter("http://www.google.com") else '                              '
                              ,'Valid URL' if Counter(i[6][0:23])  == Counter("http://www.google.com")  else 'Invalid URL'
                          )

outputfile.close()


Nginx: Wordpress: Blank Page

Question: When I try to access my webserver, I get a blank page. It is set up to work with wordpress, but it doesn't.
This is my wordpress.conf (located in conf.d):
server {
  listen 80;
  #listen 443 default ssl;

  server_name snapecraft.ddns.net;
  root /var/www/html;

  #ssl_certificate /etc/nginx/ssl/mydomain.crt;
  #ssl_certificate_key /etc/nginx/ssl/mydomain.key;

  access_log /var/log/nginx/access.log;
  error_log /var/log/nginx/error.log error;

  index index.php index.phtml index.html;

  error_page   500 502 503 504 404  /50x.html;

  location = /50x.html {
        root   /usr/share/nginx/html;
  }

  location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_intercept_errors on;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include /etc/nginx/fastcgi_params;

  }
}

When I do curl -I snapecraft.ddns.net this is the result:
HTTP/1.1 301 Moved Permanently
Server: nginx/1.15.5
Date: Fri, 26 Oct 2018 16:41:11 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Location: https://snapecraft.ddns.net/

This is my nginx.conf:
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

This is the php.ini file:
https://pastebin.com/P6UccG70
Of course I reloaded nginx and PHP
Thank you very much for your help!
Answer: WordPress can be set to force https, but you have commented those lines out on your wordpress.conf. Your server is not answering  on HTTPS, but does a redirection to it.
You have two options:

Make http://snapecraft.ddns.net/ (without TLS) the canonical address for your site.
Set up the TLS enabled https://snapecraft.ddns.net/.

This day and age you should choose option 2.

Nginx: Wordpress: Blank Page


How can I add processing of text blocks before outputting them on site?

Question: I have a library, that formats text for better readability. I want to put processing of text blocks and strings before outputting them on site, Where and how to do this?
The processor a very simple:
<code>require_once("EMT.php");

$typograph = new EMTypograph();

$typograph->set_text($contentof_text_block);

$contentof_text_block = $typograph->apply();
</code>
Drupal 8
Answer: You implement a text filter. Here is an example, FilterHtml, from core: https://api.drupal.org/api/drupal/core!modules!filter!src!Plugin!Filter!FilterHtml.php/8
Here is one that I made: http://cgit.drupalcode.org/mathjax/tree/src/Plugin/Filter/MathjaxFilter.php