How to find the imaginary roots of polynomials

Question: I'm looking for a simple way to calculate roots in the complex numbers.
I'm having the polynomial $2x^2-x+2$
I know that the result is $1/4-$($\sqrt{15}/4)i$.
However I'm not aware of an easy way to get there.
Answer: $$2x^2 - x +2 = 2\left(x^2 - \dfrac{x}2 + 1 \right) = 2\left(\underbrace{x^2 - 2 \times x \times \dfrac14 + \left(\dfrac14 \right)^2}_{a^2 - 2ab + b^2 = (a-b)^2} - \left(\dfrac14 \right)^2 + 1  \right) = 2 \left( \left(x- \dfrac14 \right)^2 + \dfrac{15}{16}\right)$$
Setting the above to zero, we get that
$$\left(x- \dfrac14 \right)^2 + \dfrac{15}{16} = 0 \implies \left(x- \dfrac14 \right)^2 = \dfrac{-15}{16} \implies x - \dfrac14 = \pm\dfrac{i\sqrt{15}}{4}$$
Hence, $$x = \dfrac{1 \pm i \sqrt{15}}4$$
Comment: @BabakSorouh: I'm simply sticking with Fola's solution cause I'm studying for a multiply choice test. However I will try to learn the other way later this week, when I get some spare time, as I can see the benefits of it.
Comment: Thanks for the alternative solutions baka-sorouh & @marvis
Comment: If you spot it you can complete the square as $\frac 1 8 (16x^2-8x+16) = \frac 1 8 \left( (4x-1)^2+15\right)$. The factor is $4a$.
Comment: @AlekOliver: The way Marvis suggested is full of practical methods you can use for other second order polynomial equation. Try to reflect it.+1
Answer: Hint: $x=\cfrac{-b\pm\sqrt{b^2-4ac}}{2a}$ for a quadratic equation $ax^2+bx+c=0$ and $i^2=-1$
You have $2x^2-x+2=0$, $a=2$, $b=-1$ and $c=2$, then $$x=\cfrac{-(-1)\pm\sqrt{(-1)^2-4(2)(2)}}{2(2)}=\cfrac{1\pm\sqrt{-15}}{4}=\cfrac{1\pm i\sqrt{15}}{4}$$
and $x=\cfrac{1 + i\sqrt{15}}{4}$  $OR$  $\cfrac{1- i\sqrt{15}}{4}$
Comment: @AlekOliver  $\sqrt{-15} = i\sqrt{15}$ and your result should be  $\cfrac{1 \pm i\sqrt{15}}{4}$
Comment: Solving x1: $\dfrac{(1+\sqrt(1^2-4*2*2))}{4} 4$) <=>
$1/4-sqr(15)/4i$?
So when sqr(-15) appears I have to think, how can i solve this with complex numbers?
Comment: @AlekOliver can you edit your comment?
Comment: Still working on it, not that used to Latex yet :)
Comment: Solving x1= $\dfrac{(1+\sqrt(1^2-4*2*2))}{4} $) =
 $\dfrac{(1/4-sqrt(15)}{4}$ =
 $\dfrac{(1/4-isqrt(15)}{4} $ $\\$
x2 =  $\dfrac{(1/4+isqrt(15)}{4} $
Like this?
F0la Yinka thanks:)
Answer: You can use the way that @FOla suggested, or you can do as following: $$2x^2-x+2=0\rightarrow2x^2-x+2+\frac{1}{8}-\frac{1}{8}=0\rightarrow(2x^2-x+\frac{1}{8})=\frac{1}{8}\\(\sqrt{2}x-\frac{\sqrt{2}}{4})^2=\frac{1}{8}-2=\frac{-15}{8}\rightarrow\sqrt{2}x-\frac{\sqrt{2}}{4}=\pm\bigg ( \frac{\sqrt{15}I}{2\sqrt{2}}\bigg)$$ Now divide both sides by $\sqrt{2}$. You would see your solutions.
Comment: @DonAntonio: You are always **welcome** to me, Don.


Flutter pubspec.yaml - Adding forked dependency from branch - A dependency may only have one source

Question: I had to modify an existing pub package which has multiple branches besides the main one. I needed the branch 3x_null_safety
So I forked the repo, modified the code and pushed it to my github.
dependencies:
  geoflutterfire:
    git:
      url: https://github.com/[myUsername]/GeoFlutterFire
    ref: 3x_null_safety

Also tried this:
dependencies:
  geoflutterfire:
    git: git://github.com/[myUsername]/GeoFlutterFire.git
    ref: 3x_null_safety

In both cases I'm getting this error:

pubspec.yaml: A dependency may only have one source
Answer: Indentation is important.
As shown in the pubspec.yaml examples for Git repositories, you should use:
dependencies:
  geoflutterfire:
    git:
      url: https://github.com/[myUsername]/GeoFlutterFire
      ref: 3x_null_safety

That is, ref should be a field of git, not of geoflutterfire.  By using the wrong indentation, ref: was treated as a source in addition to the git one.


Not able to set the time for auction products, using the Ubercart Auction module

Question: I guess this question is for those of us using the ubercart auction module
This module allow you to make auction of products (of the Product Content Type generated by Ubercart). When you create a new product you have to fill the Auction Settings and in there you have to set the expiration date and time of the auction.
My problem is that I see the field to set the date but no input is shown to fill the time (i.e.: 18:00:00).
The README file of the module says:

Use the "Expiration date and time" field to set the expiration time for the auction.

then I understand that this is either a bug (I already posted the issue) or I have a mis-configuration on my site.
Answer: I think you just need to upgrade to the latest dev version, this is what the same fieldset looks like for me with that version:

This is on a blank Drupal 7.14 installation with only the required modules for uc_auction enabled:

Ubercart Auction - 7.x-1.x-dev (2011-Dec-11)
Ubercart - 7.x-3.1
Date - 7.x-2.5

It would be a good idea to make sure you have the latest stable versions of those contrib modules installed as well; if I remember rightly the date_popup module used to have an issue with setting the #default_value of a date_popup type field, so the problem might just be that.
Comment: I guess there's another module interfering with it then (it works perfectly on a blank install as you can see from the image), I would start methodically disabling any contrib modules you have installed until you find the culprit
Comment: I have all these modules updated to the last version. Then it must be related to the issue you mention about date_popup module, how can I go through this? I think of removing the popup calendar in the `uc_auction.module` file. After this, the date should be entered manually. What do you think?
Comment: I just tried the dev version of Date but...nope.
Comment: Rare... I just disabled all modules (130 modules) but the problem still persist. I also installed auction in a clean installation and it works fine. I give up... I will change the value `date_pop` to `textarea` to enter the date and time manually.
Comment: That's quite weird...I guess it's a configuration option or something then but I can't think what it would be. Sorry I can't help further
Comment: Thanks, I understand, you can't reproduce the problem at all.
Answer: date still affects the product that is not auctioned. an error occured when I try to checkout with an unauctioned product. "Edit Issue Your order could not continue because one of the items you are trying to purchase using the "Buy Now" feature cannot be purchased because it has expired. Please remove the item from your cart to continue."


Webform User Contact Form in Block

Question: I cant seem to find any solid info on how to do this in the Webform module, is there a function or a module that goes with webforms to do this?
Thanks
Answer: Webforms when created are nodes by default. In drupal 6 there was a module called webform block (http://drupal.org/project/webformblock) this got encorprated into webform with webform 3 (which as your using drupal 7 you will be using, I dont think its even possible to get webform 2.x on D7)
To get the webform as block:

Create your webform in a node.
Edit the node.
Select the Webform tab.
Select the Forms settings tab.
Select the Forms settings tab.
Select Advanced settings.
Switch on Available as block.
Save configuration.

Source: http://drupal.org/node/1447436
Comment: what version of webform are you using? perhaps an update will sort this for you
Comment: yeah i tried this but there isnt a option there, ultimately im thinking web form isnt creating the forms by default, it may be d7 core, the way i am seeing the form is through user/"uid"/contact
Comment: im using Webform 7.x-3.15
Answer: Here's a video to show you how to make a web form block
http://www.youtube.com/watch?v=p5CLio9_DfU

Webform User Contact Form in Block


Are all ordinal attribute types nominal?

Question: I'm currently writing a .NET library to handle various statistical/classification tasks and I am currently writing the structures to represent nominal and ordinal data.
In doing so, I've been debating whether or not the structures that handle ordinal data should derive from the structures that handle nominal data.
My thought is that yes, all ordinal data is nominal data; even though it means huge (or infinite) sets, each of them is an attribute that while being able to compared to another attribute for rank (for lack of a better term, which implies ordinal) can still be compared to for equality and is still a label (nominal).
Comment: I know this is old but going to leave a comment anyway in case future people see this. #1: Don't write this code. Someone else who has researched the area more has already written it so you should import their stuff instead. #2: Yep, the data-structure you are considering is correct. You could look at [Ord](https://hackage.haskell.org/package/base-126.96.36.199/docs/Data-Ord.html) for a nice well-thought-out tree of the standard ⊂ for statistical data types.
Comment: @isomorphismes If someone else has written this code for .NET would you point it out?  Ord looks nice, but it's for Haskell, and the question clearly indicates this is for .NET.
Answer: I would definitely make the distinction between discrete ordinal variables and continuous ordinal variables. For the second case, in practice there never is any sense in comparing values for equality.
I don't see a sound reason to state that continuous ordinal variables are in fact nominal: what would be the gain?
Comment: The design of the object oriented program would be nicer.
Comment: Well, not if it doesn't reflect reality. You're going to get stuck somewhere down the line...
Comment: @xmjx hit the mark with the intent and the gain; Nominal dervies from Ordinal.  Discrete ordinals and continuous ordinals can be derivations of Discrete ordinals when I get to that point.  Another example, Nominal types can do two things, say if they are equal to another nominal type, and tell if they are missing; these characteristics/methods are shared with all ordinal ordinal values.
Comment: How could you have a continuous ordinal variable?


Proving a map is continuous (in the topological sense)

Question: I'm going through a fairly involved proof in Algebraic Topology, and am stumbling at the last hurdle because my point-set topology is rusty.
Suppose I have a map $f : Z \to Y$, where $Y$ and $Z$ are topological spaces. If I've shown that $f^{-1}(A)$, where $A$ is any open set in a basis for the topology on $Y$, contains a set open in $Z$, does it follow that $f$ is continuous?
Thanks
Comment: Note: the empty set is open, so your condition is always trivially satisfied...
Comment: This looks a bit like the neighbourhood definition of continuous: $f$ is continuous at a point $z \in Z$ iff for any neighbourhood $V$ of $f(z)$, there is a neighbourhood $U$ of $z$ such that $f(U) \subseteq V$, but not quite. Have you written the details correctly?
Answer: Even if you "don't count the empty set as open" this is wrong. For example the identity map on the set $M:=\{1,2,3,4\}$ is not continuous but satisfies your condition if we use the following topologies on $M$:
$M_1$: $\{1\},\{2,3\},\{4\}$ are a basis
$M_2$: $\{1,2\}$ and $\{3,4\}$ are a basis.
Now the identity map is a discontinuous map $M_1\rightarrow M_2$ satisfying your criterion.
Answer: No. You need for $f^{-1}(A)$ to be open for any (necessarily open) set in the basis for the topology of $Y$. If you have this, then for any open set $U$ we have $U=\bigcup\limits_{i\in I} A_i$ for some collection of $A_i$ in the basis for $Y$, and so
$$f^{-1}(U)=f^{-1}\left(\bigcup\limits_{i\in I} A_i\right)=\bigcup\limits_{i\in I} f^{-1}(A_i)$$
is open as the union of a collection of open sets is open.
Comment: Checking that $f^{-1}[S]$ is open for every $S$ in some *subbase* for the topology of $Y$ suffices.
Comment: @BrianM.Scott That's true, but OP is working with a basis and it is certainly necessary for the preimages of basis elements be open.


Understanding residuals vs. fitted plot for a linear mixed model

Question: I am modeling body mass (y var) according to indices of dysregulation for different physiologic systems (x vars). I did a likelihood ratio test, which supported using a linear mixed model, with a random effect of individual, over a simple linear model.
library(lme4)
require(RLRsim)
mod1 <- lm(mass_kg_zscore ~ metabolic_index + immune_index + neuro_index, data = pb)
mod2 <- lmer(mass_kg_zscore ~ metabolic_index + immune_index + neuro_index + (1|id), data = pb, REML = FALSE)
exactLRT(mod2,mod1) # individual, null - tests individual
# P =0.0026, so there is support for keeping the RE of individual

However, the residuals vs. fitted plot for the linear mixed model looks pathologic:
plot(fitted(mod2),residuals(mod2))
abline(h = 0)

The QQ plot for mod2 looks relatively okay:

Now, if I remove the random effect of individual, and just do a simple linear model, my residuals vs. fitted plot looks much better:

My question is, why does the inclusion of the random effect cause such a wonky residuals vs. fitted plot? Does this mean I should exclude the RE, even though the likelihood ratio test supported keeping the RE in the model?
Thank you!
Answer:
My question is, why does the inclusion of the random effect cause such a wonky residuals vs. fitted plot?

It's quite hard to say, without having the data itself.
First note that the bulk of range of the residuals for the mixed model is around -1 to +1 (ignoring a few outliers). However, for the linear model, the bulk of the range of the residuals is -2 to +2. This is telling you that the random effects are reducing the residual variance, which is to be expected.
Your main concern is that there appears to be an upward trend in the residuals of the mixed model. This might just be a random artefact. Do you have more data ? If so, it would be very interesting to see it was reproduced with further data. Note that in the linear model (lm) you have not adjusted for the effects of id. There is clearly some variation attributable to it, so it would be a good idea to fit id in the linear model, as a fixed effect and then compare the plots again.

Does this mean I should exclude the RE, even though the likelihood ratio test supported keeping the RE in the model?

No, I don't think so. I would be inclined to retain the random intercepts, and look into fitting a robust linear mixed model using package robustlmm


For what $n$ is there an injective homomorphism from $\mathbb{Z_n} \to S_7$

Question: So I came across this problem:

For what $n$ is there an injective homomorphism from $\mathbb{Z}_n\to S_7$?

I have the solution but the solution doesn't make much sense to me. It said that $n=1,2,3,4,5,6,7,10,12$. Also  I'm wondering why $n$ can't be $8$?
A homomorphism $\phi$ is just a mapping such that for all $a,b\in \mathbb{Z}_n$ $\phi(ab)=\phi(a)\phi(b)$
Since we can always map the elements of $\mathbb{Z}_8$ injectively to $S_7$ as the order difference is quite large I would assume that the property $\phi(ab)=\phi(a)\phi(b)$ is the property that doesn't hold for $\mathbb{Z}_8$.
But I am not exactly sure how to explicitly show this, please help!!
Answer: The question is equivalent to asking whether we can find an element $a \in S_7$ with order $n$. (If we can, then we map $1\in \mathbb Z_n$ to $a$, which uniquely determines the mapping; can you see why it must be injective? Conversely, if we have an injective mapping $\phi$, $\phi(1)$ must have order $n$.)
So is there any element of $S_7$ of order $8$?
The elements of $S_7$ are permutations. One way to write a permutation is to decompose it into disjoint cycles. The best way to explain this is to illustrate by example: one element of $S_7$ is written $(1436)(27)(5)$, which is the permutation that sends $1$ to $4$, $4$ to $3$, $3$ to $6$, and $6$ back to $1$; $2$ to $7$ and $7$ to $2$; and $5$ to itself. That's a $4$-cycle, a $2$-cycle, and a $1$-cycle.
There's a way to find the order of an element based on the lengths of the cycles in its cycle decomposition. I'm not going to give away the punchline yet. But play with some examples of these cycle decompositions and see if you can find their orders.
Answer: For n = 2,3,4,5,6,7,10,12 you can get an injective group homomorphism from Zn into S7.
Let f : Zn -->  S7 be an injective group homomorphism. Then |Ker f| = 1 as f is injective and Zn is isomorphic to a subgroup ( say H ) of S7.
Now by isomorphism Th
Zn/ Ker f ~ H and H must be cyclic as Zn is cyclic. Now in S7 there are elements of order 2,3,4,5,6,7,10,12. Let a be any element of order mentioned above then you get a cyclic group       < a > of order n.
Note that there is no element of order 8 in S7. In order to have an element of order 8 in Sn one has break the element into disjoint cycles such that the l.c.m. of the lengths of cycle become 8, which is impossible for S7.
Answer: For $n=1,\dots,7$, clearly $S_7$ contains $n$-cycles: each of them is isomorphic to $\mathbb Z_n$. For $n=10$, for example the subgroup $\langle (12)(34567)\rangle$ is isomorphic to $\mathbb Z_{10}$. Likewise, for $n=12$, for example the subgroup $\langle (123)(4567)\rangle$ is isomorphic to $\mathbb Z_{12}$. Can you see now why $S_7$ hasn't got subgroups isomorphic to $\mathbb Z_n$ for $n=8,9,11$?


What is meant by "expand f[x,y]=xy in powers of x-1 and y-1"?

Question: This question refers to C.H. Edwards, Jr.'s Advanced Calculus of Several Variables, Chapter II-7, Example 2.

Suppose we want to expand $f[x,y]=xy$ in powers of $x-1$ and $y-1$.  Of course the result will be
$xy=1+(x-1)+(y-1)+(x-1)(y-1)$,
but let us obtain this result by calculating the second degree Taylor polynomial $P_2[\mathbf{h}]$ of $f[x,y]$ at $\mathbf{a}=\{1,1\}$ with $\mathbf{h}=\{h_1,h_2\}=\{x-1,y-1\}$. ...

Establishing the equivalence is a matter of simple algebra, but "expand $f[x,y]=xy$ in powers of $x-1$ and $y-1$" has no clear meaning to me.  Edwards obviously does not mean to use a Taylor polynomial, because he wants to show the above result is equivalent to the Taylor polynomial.
What exactly does it mean to expand a function in powers of some given pattern?  I'm assuming this is something I should have learned in high school.
Comment: probably like a multivariable taylor expansion around $x=1,y=1$
Comment: I added more text from the example to make it clear that the Taylor polynomial is not what was meant.  The objective is to show the result to be the same as the Taylor expansion.
Comment: You can make many polynomial approximations which are not Taylor polynomials, unless a more clear description of how to obtain the coefficients it's difficult to prove them to be the same.
Comment: @mathreadler That's why I asked the question.  Edwards obviously expects the reader to know what is meant by 'expand f in powers of ...'.  But I would not have had a clue what was meant had he not shown the result.
Answer: $\newcommand{\dd}{\partial}$To expand a polynomial $p(x, y)$ in powers of $x - a$ and $y - b$ is to find coefficients $c_{jk}$ (which turn out to exist uniquely, and with all but finitely many equal to $0$) such that
$$
p(x, y) = \sum_{j,k=0}^{\infty} c_{j,k} (x - a)^{j} (y - b)^{k}.
$$
(If the total degree of $p$ is $N$, the sum is limited to indices with $j + k \leq N$.)
One way to achieve this expansion is to write, using your example $p(x, y) = xy$,
\begin{align*}
  xy &= \bigl(a + (x - a)\bigr) \bigl(b + (y - b)\bigr) \\
  &= ab + b(x - a) + a(y - b) + (x - a)(y - b).
  \tag{1}
\end{align*}
(Analogous use of the binomial theorem handles arbitrary monomials $x^{\ell} y^{m}$, and every polynomial in two variables is a finite sum of monomials.)
Another way approach is to invoke Taylor's theorem:
$$
p(x, y) = \sum_{n=0}^{\infty} \sum_{j=0}^{n} \frac{\dd^{n} p}{\dd^{j} x\, \dd^{n-j} y}(a, b)\, \frac{(x - a)^{j}}{j!}\, \frac{(y - b)^{n-j}}{(n - j)!}.
\tag{2}
$$
Again taking $p(x, y) = xy$, one finds
$$
c_{0,0} = p(a, b) = ab,\quad
c_{1,0} = \frac{\dd p}{\dd x}(a, b) = b,\quad
c_{0,1} = \frac{\dd p}{\dd y}(a, b) = a,\quad
c_{1,1} = \frac{\dd^{2} p}{\dd x\, \dd y}(a, b) = 1,
$$
with all other partial derivatives vanishing, so that (2) agrees with (1). This is presumably the content of Edwards' example.
Generally, (2) yields the coefficients
$$
c_{j,k} = \frac{\dd^{j+k} p}{\dd^{j} x\, \dd^{k} y}(a, b)\, \frac{1}{j!\, k!}.
$$
There are similar formulas for sufficiently smooth (non-polynomial) functions, perhaps with infinitely many non-zero coefficients, and with "error" or "remainder" terms.
Answer: Rewrite $x$ as $(x-1)+1$ and similarly for $y=(y-1)+1$. Now let $X=x-1$ and $Y=y-1$. So
\begin{eqnarray*}
f(x,y)=xy&=&((x-1)+1)((y-1)+1)=(X+1)(Y+1) \\
\end{eqnarray*}
\begin{eqnarray*}
&=&XY&+&X&+&Y&+&1 \\
&=&(x-1)(y-1)&+&(x-1)&+&(y-1)&+&1
\end{eqnarray*}
So the solution you give in the question is spot on.


matplotlib.pyplot.subplots() - how to set the name of the figure?

Question: When I create a single plot using the figure()-function of PyPlot, I can set the name of the appearing window using a string as argument:
import matplotlib.pyplot as plt
figure = plt.figure('MyName')

The function plt.subplots() doesn´t accept strings as first argument. For example:
plt.subplots(2,2)  # for creating a window with 4 subplots

So how can I set the name of the figure?
Answer: Taken from the docs:
import matplotlib.pyplot as plt

#...

# Just a figure and one subplot
f, ax = plt.subplots()
ax.plot(x, y)
ax.set_title('Simple plot')

And, to change the title of the Window:
import matplotlib.pyplot as plt
fig = plt.figure()
fig.canvas.manager.set_window_title('My Window Title')
plt.show()

If you're using a Matplotlib version < 3.4, use: fig.canvas.set_window_title('My Windows Title')
Reference to deprecation (kudos to KaiserKatze).
Comment: set_title('string') only sets the title of the plot, not the name of the window that is showing up, when you run the code. The window keeps called "Figure 1".
Comment: @MoTSCHIGGE: The last sentence of the OP's question states: _So how can I set the name of the figure?_ However, I've addressed your concerns - as I possibly misread it wrong. Thank you for your comment.
Answer: plt.subplots() passes additional keyword arguments to plt.figure. Therefore, the num keyword will do what you want.
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, num='MyName')

You can also set figsize and dpi etc. in this way too (see plt.figure docs).
Comment: I hunted hi and low for this answer and finally found it here!  Thanks for this.  Matplotlib's documentation is just a hot mess.
Answer: You can also do this:
f, axarr = plt.subplots(2,2, num = PlotName)

where PlotName is a string and thus you can generate a window name upon instantiation


Data decimal to Binary

Question:
Convert X10 to Binary X2 ; You MUST determine and state exactly how many bits are necessary for the representation of X10 in binary. Round up the value for the number of bits necessary to represent X2 to the nearest multiple of 4 and express X2 in this number of bits with a space between each 4-bit group.

x10  58927634
I have converted x10 to x2
11100000110010101000010010
but I could not understand the part where it says round up the value for the number of bits necessary to represent X2 to the nearest multiple of 4, please I really need help I need only an explanation to solve this I don't need answer just explanation.
Answer: You just need to determine how many bits are needed to represent your decimal number - and then round it up so that it is a multiple of 4. Example:
<code>Decimal = 19
Binary = 10011
Bits needed (minimum) = 5
Bits needed (rounded up) = 8
Final binary string = 0001 0011

Decimal = 58927634
Binary = 11100000110010101000010010
Bits needed (minimum) = 26
Bits needed (rounded up) = 28
Final binary string = 0011 1000 0011 0010 1010 0001 0010
</code>

Data decimal to Binary


forming confidence ellipse versus using contrast

Question: Suppose I am testing a hypothesis on data that is bivariate normal, $(x,y)\sim N(\mu,\Sigma)$ where $\Sigma$ is known but $\mu$ is not. My null hypothesis is a contrast $a^T\mu=a_1\mu_1+a_2\mu_2=0$. The data gives me $(\bar x,\bar y)\sim N(\mu,\Sigma/n)$. I'm trying to understand the relationship between two testing strategies:

Since $a^T(\bar x,\bar y)\sim N(a^T\mu,a^T\Sigma a/n),$ test the z-statistic $$\frac{a^T(\bar x,\bar y)-a^T\mu}{\sqrt{a^T\Sigma a/n}}$$
if it exceeds $z_\alpha$.
Since $(\bar x,\bar y)^T\Sigma^{-1}(\bar x,\bar y)/n$ is chi-squared with 2 degrees of freedom, I could form a confidence ellipse in the $(\mu_1,\mu_2)$ plane with center at $(\bar x, \bar y)$ with the size determined by a chi-squared quantile, and see if it includes the line given by the contrast, $a^T\mu=0$.

Are these equivalent tests? Is the second even a valid test of the contrast?
Comment: No ellipse wholly includes *any* line.  This makes it difficult to understand what you mean by (2).
Comment: @whuber I meant intersects the line. So there would be points in the null hypothesis set that are compatible with the data in that they lie in the confidence ellipse, then don't reject that null.
Comment: I was hoping that formulating such a description of the situation would make it clear to you that the second approach is invalid and show how to reconcile it with the first one.  Maybe it would help to rephrase your description of "intersects the line" as "projects to an interval in the subspace generated by the contrast."
Comment: @whuber but wouldn't the projection of an ellipse onto a line be an interval whether or not the line intersects the ellipse?
Comment: The interval is determined by the width of the ellipse perpendicular to the line direction.
Comment: Looks to me like a multiple comparisons problem. As such, the first approach is invalid because there is no multiplicity correction. The second approach, when tidied up, looks like the Working-Hotelling approach, which is valid.
Comment: @BigBendRegion Where are the multiple comparisons?  A single hypothesis is being tested.  When appropriate coordinates are chosen, this problem is equivalent to the univariate case of testing $\mu=0$ using a sample from a (scalar) Normal$(\mu,1)$ distribution.
Answer: It helps to analyze this distribution a little, because it reduces the situation to a familiar one with a clear answer.
Upon setting
$$z=a_1x + a_2 y = \pmatrix{a_1,&a_2}\pmatrix{x\\y} = \mathbf a^\prime \pmatrix{x\\y},$$
compute the moments of this linear combination of the bivariate Normal random variable $(x,y)^\prime$ as
$$E[z] = a_1E[x]+a_2E[y] = a_1\mu_1 + a_2 \mu_2$$
and
$$\operatorname{Var}(z) = \pmatrix{a_1,&a_2}\Sigma\pmatrix{a_1\\a_2} = \mathbf a^\prime \Sigma \mathbf a = \sigma^2$$
(thereby defining $\sigma^2$).
Consequently, $z$ has a Normal distribution with known variance and your null hypothesis can be expressed as $H_0: E[z]=0.$ Test this in the usual way with a Z test.  The test statistic is
$$Z = \frac{\bar z}{\operatorname{SE}(\bar z)} = \frac{a_1\bar x + a_2\bar y}{\sigma/\sqrt{n}}= \frac{\mathbf a^\prime (\bar x,\bar y)^\prime}{\sqrt{\mathbf a^\prime \Sigma \mathbf a\,/n}}.$$
I believe this is what (1) in the question is intended to say.  (Notice that $\mu$ cannot appear anywhere in the statistic because it is unknown.)  Because the alternative hypothesis is $E[z]\ne 0,$ the critical region is where $|Z|\gt Z_{\alpha/2}$ where $Z_{\alpha/2}$ is the $100(1-\alpha/2)$ percentile of the standard Normal distribution.
In response to a comment to the question, this is a single test making a single comparison and therefore needs no adjustment for multiple comparisons.

The problem with (2) in the question is that, by constructing a critical region in the $(\bar x, \bar y)$ plane, it involves an independent random variable; namely, another linear combination of $(\bar x, \bar y)$ that is uncorrelated with $\bar z.$  Using the confidence region approach effectively balances the potential for decision errors in the test you are interested in against decision errors involving this unrelated variable and therefore cannot be any better.


Binary logistic regression and percentage change variable

Question: I am a student approaching binary logistic analysis. I was wondering whether the independent variables used in the logistic regression can be expressed in percentage changes. If yes, How to interprete the OR?
Thanks so much for any help!
Matias
Comment: An odds-ratio effect of say $3$ will change a probability of $1\%$ to almost $3\%$ but a probability of $50\%$ to $75\%$.  So in any particular case you can say what the effect is on the probability but it depends on the starting probability
Answer: You can always input any variable you want into logistic regression, however, you then need to do the math to associate the variable's units with the regression coefficients and if exponentiated, how those units relate to OR.  Regarding use of a per cent change input variable, logistic reg makes no assumptions about the distribution of input variables -- so you're ok there.
As an alternative, ORs from logistic regression are commonly derived from binary (0,1) variables like yes/no, exposed/nonexposed, treated/placebo, etc.  If you took this approach, you would recode (binarize) your per cent change variable into a new variable with a 1 representing per cent change above the median, and 0 representing below the median.  Then you'd rerun the model using that binary variable as a predictor with/without other covariates, and then simply exponentiate the regression coef for the binary variable, $OR=\exp(\beta)$ to get the OR.  Once done, the conclusion would be: "the OR for having $y=1$ for objects with a per cent change above the median (e.g. high value of per cent change) is XX.XX."


If I were to switch from playing clarinet (6 years) to starting oboe, how hard would it be?

Question: So I'm aware that oboe is one of the hardest instruments to pick up and learn (partially because of embouchure, reed maintenance, etc.) but I love the instrument and I'd really like to start learning. I've been playing for 6 years currently on the clarinet, and so I was wondering how hard it would be to adapt to the new oboe embouchure, etc.?
I have had a tiny bit of experience with bassoon (I tried it out once at school) and I actually found the reed and embouchure quite easy to get - I was able to play almost 1 1/2 octaves. I understand that oboe embouchure is much tighter and the reed is narrower (with much more resistance), but most of the defining characteristics of the embouchure would carry across right (e.g vibrating the double reed)??
Hence would the resistance on the reed be significantly different to the clarinet? I currently play with a 3 1/2 Vandoren clarinet reed - is there a massive difference?
Also - if anyone's got some good tips for buying a student-intermediate oboe at a relatively cheap price, that would be incredible! Honestly, I'm having a hard time understanding all the different specifications of the oboe (like semi vs. full automation, conservatory systems and how left F keys or 3rd octave keys factor into the different playing levels of the instruments)... :)
Thanks!
Comment: +1 for @JohnBelzaguy: if you *really* want to "switch" to oboe, then you shouldn't really be preoccupied by "how hard would it be": any instrument is hard. Just do it. «Do. Or do not. There is no try».
Comment: I agree with @musicamante, this question is pointless and also opinion based to an extent. A few questions for you: Is this something you really want to do? Is the amount of difficulty you think you would encounter significant enough to discourage you from doing it? If your answers are yes and no then go get yourself an oboe!
Comment: They are instruments that belong to the "same" family, but they're quite different. Coming from a "similar" instrument, you'll probably already know some important aspects that will reflect on the oboe in a similar way, but, answering to a question such as "how hard will it be" is pointless: we could give you lots of advice or experience-based suggestions, but you should also consider that SE communities are intended for *general* public: while your question *could* be useful to **some**body, it's unlikely that any actual suggestion valid for you would be fine to anybody else in your situation
Comment: @musicamante - In many schools at least in the U.S. (where I'm most familiar), one of the most common pathways to playing oboe is to start on clarinet (as many primary general music teachers feel double reeds are too "finicky" and/or don't feel they have the skills and background to teach well), so I think the general question of how hard it is to switch between these two *particular* instruments is useful for a large audience.  Yes, it's vague to address this specific person's specific case, but the general question is perhaps relevant to a lot of folks.
Comment: Please consider that question asking about equipment suggestions are considered off topic here (I'm obviously only referring to the last section of your post).
Comment: An insight. I'm a classical educated percussionist. I've seen fellow students coming from "other" instruments, most from drumset or conceptually "similar" instruments (usually, piano). Excluding people coming from completely different families (me includied, as my first instrument was violin), most of them came from "percussion" based instruments. Well, we all struggled in different ways. There's no "unique" path, it all depends on your experience and how you dealt with it. I've seen drumset players having more difficulties than others that played wind instruments before trying percussions.
Comment: Much higher resistance is easier to handle than the very small air consumption for tone production - it is hard to learn change exhaling.
Comment: I don't understand these *"how hard is it to learn X"* questions.  Who cares how "hard" other people think it is - do you want to play oboe or not?  If yes, then go give it all you've got.  If you don't want to play oboe, then don't.  Don't worry about how "hard" other people say it is or it isn't.  There's only one thing that matters - either you want to try playing or you don't.  If people tell you it's really hard, are you honestly not even going to try?  Is that what's making the decision for you?
Comment: @Athanasius It's not relevant to anyone.  The unspoken ask in the question is *"Please tell me I'm good enough to have a chance at success because I don't believe in myself and I'm afraid of trying something and failing"*.  The information in the answers is irrelevant.  What OP is looking for is counselling and emotional support.  You could write a thousand variations on this question that all take the same answer - *"Don't worry about it - just do it"*.
Comment: @J... I wasn't aware that answering questions on StackExchange was about psychoanalyzing the questioner.  The actual question asked is basically "If I'm a somewhat experienced clarinet player, how hard will it be to learn oboe?"  If anything, the implicit question is, "Will anything from my clarinet experience be helpful in learning oboe?" and the answer to that (as seen in some answer below) is, "Yeah, some of it.  Other stuff, not so much."  You are entitled to your opinion about what questions the OP may have wanted to ask but didn't, but I'm interested in the actual question posed.
Comment: @Athanasius I still fail to see how anyone's opinion on the matter matters - this is the definition of an opinion-based answer.  OP is either going to pick up an oboe and try to play it or they are not.  If someone says their clarinet playing will help, they will still try to play the oboe because they want to.  If someone says their clarinet playing will not help, they will still try to play the oboe because they want to.  *"I only intend to try if other people tell me it will be easy"* is a terrible trap to fall into, which is exactly what the top answer says - wanna play?  *Then go do it.*
Comment: @J... There is too much discussion going on in comments here, but let me phrase it this way: if someone asked, "I've been playing clarinet for 6 years.  I want to play saxophone.  Will it be difficult, and will my experience help with saxophone?"  The answer is *obviously* that experience on clarinet with help with saxophone.  A beginner may not realize the commonalities and the differences, which could be elucidated in the answer here.  This question is NOT, "I've played drums for 6 years.  How hard will it be to switch to oboe?" In that case, it's pretty obvious they'd be starting anew.
Comment: @Athanasius And it changes nothing about their future experience of learning to play the oboe - whether some random person said it would be easier or harder makes no difference.  It will be whatever difficulty it is for OP and other peoples' opinions about how hard it is to play oboe count for nothing - they don't make it any easier for OP and they don't make it any harder for OP.  Agreed there's too much discussion - the question is pointless and there's nothing to do but have a long subjective discussion about it, which is why it should be off-topic (also the shopping questions at the end).
Comment: @J... There are many, many professional wind players who double on various instruments.  Asking other professionals who have learned both instruments whether there are commonalities and skills that can transfer is certainly useful information.  Maybe you're right that OP needs a vote of confidence rather than info, but they could certainly be useful to someone.  I agree that I'd prefer to see a slightly differently worded question (without the "how hard is it" general phrasing), but the *specifics* of adapting embrochure, etc. are useful to ask.
Answer:
I love the instrument and I'd really like to start learning

Then do it. I'm almost 48 years old. About two months ago I started French horn lessons. I have never played a brass instrument before. I'm sure you know that in the brass family, the French horn is seen as the difficult one. I thought a lot about taking up the trombone or the trumpet, but I realized that even if I got a great sound out of one of those, it will never speak to me the way the French horn does. And no matter how frustrated I might get at the French horn, I'll be on a path with a destination that I am really excited about.
So it doesn't matter how hard it is. You love it, you want to learn it, so do it. I'm extremely confident you won't regret it (I'm super happy with being a terrible horn player - for now!)
Regarding the rest of your questions, I have a suggestion that worked out very well for me:
The first thing you do is find a teacher. Book a first lesson and tell the teacher when you're booking the lesson that you have musical training in the clarinet, you want to learn oboe, and you don't yet have an oboe.
The topic of the first lesson is all of your questions. Where can you get a decent oboe, what to look for in a beginner instrument, what kind of reed to start on, synthetic vs cane, pre-cut vs learning to cut your own, etc. If the teacher is reluctant to discuss these things or doesn't provide you with effective help, maybe you don't want them as a teacher and you should look around more.
When I started clarinet lessons I had an old instrument I'd picked up so that's what I used, but my teacher started talking about it and what maintenance it might need pretty early on. So when I started French horn, I did exactly as I suggest and had a first lesson before I even had a horn. My teacher did a great job of telling me where to find "affordable" used horns (the price of entry for a double horn is very high) and also talked to me about things that didn't really matter that much until I'm much more advanced. In the end the cost of a lesson where I didn't learn to play at all was nothing compared to the benefit of starting off with the equipment and the sheet music that would get me going on a solid footing right from the second lesson.
I strongly suspect that a lot of your embouchure from clarinet won't translate to oboe. But what I'm very confident will translate are:

Your overall lung power
Your understanding of "fast air"
The strength and development of your lip muscles
The greater kinesthetic sense of your tongue compared with someone who has never played a wind instrument
Your ability to read treble clef and your understanding of music
Comment: «the French horn is seen as the difficult one». Well, the French horn *is* a difficult one - as much as it's a wonderful instrument. We've a common joke, and I bet it's not only a local one: When you buy a French horn, the price includes all the wrong notes. (we call them "scrocchi", that is a jargon for notes that come out wrong even if you tried all you could to get them right).
Comment: @musicamante One thing I find very pleasant about learning the French horn is that my worst notes make me laugh because I sound like a dying elephant. On the clarinet, when things go wrong as a beginner it's usually painful to the ears. Horn is a lovely instrument to be terrible at by comparison. My only complaint is that my ear is good enough that I can tell how wretched my intonation is, and I know that's going to be a long, long road on the horn.
Comment: if you're experienced enough, you already know that that road will be as long as it will be interesting and wonderful - and as much as long as the air column is... That said, we could change the above saying with «When you buy a French horn, the price includes all the wrong notes, lots of laughs and even an elephant!». And since I know some fellow horn players that are able to do it, there's a hidden easter egg too: if you get good enough, there's also a helicopter!
Comment: Excellent advice, and I think sharing your personal experience will serve the OP well.
Answer: The oboe is much harder to play than the clarinet. Your experience on the clarinet will help a bit, a lot of the fingerings will be familiar. The oboe has much more resistance, you will need to re-learn a lot of your breath control. The embouchure muscles work differently and it will take a long time to build them up, your clarinet experience won't help much.
There will be a lot of work do do, but if you like the oboe then go for it. Get a good teacher, you won't have much success without one.
For keywork: get a full automatic conservatory system instrument (most are) , it will work like you're used to from the clarinet.
Comment: @CarlWitthoft — I knew a married couple who were both oboists for the NSO.  They lived a three-bedroom house: one bedroom was for sleeping, one was his reed-carving room, and one was her reed-carving room.  Both reed-carving rooms looked like hamster cages from all the wood shavings on the floor.
Comment: Not to mention that most serious oboists end up making their own reeds, a major time-pig!


What is the correct way to access an instance variable in a model method from another controller?

Question: I created some scaffolding to manage audio clips which are going to be organized by index:
rails generate scaffold Clips name:string

I uploaded all the clips to my file server, and added them to the db using the auto generated rails control panel.
Now, I need to be able to access them, so I added a url method to the model:
class Clip < ActiveRecord::Base
    def self.url
        "http://example.file_server.com/audio-clips/#{@id}.mp3"
    end
end

Now, in the controller than runs the site itself, calling this method looks like it outputs everything but the id....
class TwilioController < ApplicationController
    def index

        Twilio::TwiML::Response.new do |r|
            @response = r.play Clip.where(name: "root").url
        end

        render :xml => @response
    end
end

Outputs:
<Response>
<play>http://example.file_server.com/audio-clips/.mp3</play>
</Response>

How can I get this thing to insert the id into the URL string?
Answer: A few things, one, you defined url as self.url, which makes it a class level method.  I'm guessing you didn't want to do that.
Also, don't use id as an instance variable, use its generated accessor method:
class Clip < ActiveRecord::Base
  def url
    "http://example.file_server.com/audio-clips/#{id}.mp3"
  end
end

Also, you are calling url right after the where call, which returns a relation.  You'll want to do something like:
Twilio::TwiML::Response.new do |r|
  @response = r.play Clip.where(name: "root").first.url
end

But that depends more on what you are doing.  If you expect there to be several results, you'll have to handle it differently.  Also beware it may return no results...
Comment: I ended up doing `self` because of the relation problem. adding `.first` fixed my issue. Thanks!


Machine learning algorithms to handle missing data

Question: I am trying to develop a predictive model using high-dimensional clinical data including laboratory values. The data space is sparse with 5k samples and 200 variables. The idea is to rank the variables using a feature selection method (IG, RF etc) and use top-ranking features for developing a predictive model.
While feature selection is going well with a Naïve Bayes approach, I am now hitting an issue in implementing a predictive model due to missing data (NA) in my variable space. Is there any machine learning algorithm that can carefully handle samples with missing data?
Comment: The existence of upvoted answers implies to me that this question is not too broad to be answerable. I'm voting to leave open.
Answer: It depends on the model you use. If you are using some generative model, then there is a principled way to deal with missing values (). For example in models like Naive Bayes or Gaussian Processes you would integrate out missing variables, and choose the best option with the remaining variables.
For discriminative models it is more elaborate, since that is not possible. There are a number of approaches. Gharamani and Jordan describe a principled approach, where missing values are treated like hidden variables, and a variant of the EM algorithm is used to estimate them. In a similar fashion, Smola et al. describe a variant of the SVM algorithm which explicitly tackles the problem.
Note that it is often recommended to substitute the missing values by the mean value of the variable. This is problematic, as described in the first paper. Sometimes, I have come across papers that do regression on the variables to estimate missing values, but I cannot say whether that applies to your case.
Comment: **it is often recommended to substitute the missing values by the mean value of the variable**. Can you please point to the source?
Comment: @juampa Why do you claim it is not possible to integrate out missing variables in discriminative models? We do this for logistic regression all the time. In fact, it can be shown to be equal to multiple imputation.
Comment: @SergeyBushmanov I am with you in your confusion here. It is *not* often recommended to use (single) mean imputation because it leads to bias in some cases and anticonservative validation metrics in other cases.
Answer: The R-package randomForestSRC, which implements Breiman's random forests, handles missing data for a wide class of analyses (regression, classification, survival, competing risk, unsupervised, multivariate).
See the following post:
Why doesn't Random Forest handle missing values in predictors?
Answer: Try imputation using nearest neighbours to get rid of missing data.
Additionally, the Caret package has interfaces to a wide variety of algorithms and they all come with predict methods in R that can be used to predict novel data. Performance metrics can also be estimated using k-fold cross validation using the same package.
Answer: There are also algorithms that can use the missing value as a unique and different value when building the predictive model, such as classification and regression trees. such as xgboost
Answer: lightgbm can handle NaNs from the box(http://lightgbm.readthedocs.io/en/latest/).


'Search Form' block I would like to add a link called "Advanced Search" below the existing Search box

Question: Within our 'Search Form' block I would like to add a link called "Advanced Search" below the existing Search box.  One possible way of implementing this would be to utilize hook_block_view_alter or hook_block_view_MODULE_DELTA_alter within a custom module and then add this new link to the bottom of this block.
Is this the best way to add this link to the 'Search Form' block?
Answer: You could either use the hook_block_view_alter to add the link, just like you say. Or you can implement the search-block-form.tpl.php in your theme and add the link in the template file.


Find the area bounded by $y=\operatorname{ln}(x)$ and $y=\operatorname{ln}^2(x)$? How to find which curve is above the other?

Question:
Find the area bounded by $y=\operatorname{ln}(x)$ and $y=\operatorname{ln}^{2}(x)$?

Also how to find which curve will be above the other mathematically?
Comment: How have you possibly got to integrating exponentials like this without going through derivatives of them beforehand?
Answer: Find the intersection points:
$$\ln{x}=\ln^2{x} \Rightarrow x_1=1,x_2=e.$$
Note:
$$\ln^2x<\ln x, 1<x<e.$$
Hence:
$$A=\int_1^e (\ln x- \ln^2 x)dx=\int_1^e\ln x dx -\int_1^e \ln^2 x dx=B-C$$
$$B=\int_1^e \ln xdx=x\ln x \bigg|_1^e-\int_1^e x\cdot \frac{1}{x}dx=1.$$
$$C=\int_1^e \ln^2 xdx=x\ln^2x \bigg|_1^e-\int_1^e x\cdot \frac{2\ln x}{x}dx=e-2B=e-2.$$
$$A=B-C=1-(e-2)=3-e.$$
Answer: We have $ \ln x = (\ln x)^2 \iff x \in \{1,e\}$.
The area in question is given by $|\int_{1}^e (\ln x - (\ln x)^2) dx|$
Comment: Why the absolute value around the integral?


Why is -2*Log Likelihood inreasing when I add a predictor? / Multilevel Model

Question:
I'm working on a multi-level model using Mplus and trying to fit a regression at level 1 (within level).
I'm surprised to see that adding a second predictor at the within level increases my -2LL (-2*log likelihood) instead of reducing it.
A couple of information about the two models:

I'm only adding one L1 predictor to the initial model that contained one predictor and one DV at L1
The fit indices decrease a bit but remain very good (CFI > .95; RMSEA < .05; SRMR W and B < .08)
The -2LL for the 1st model is around 2.600 and exceeds 3.700 for the second model (with the additional predictor)
The initial predictor becomes marginally significant (previously significant at p < .05), while the newly added one is significant (p = .000)
My sample size does not change between the two models.

If it's helpful, here is the code for the second model (in which I'm adding the second predictor: Ctrl):
USEVARIABLES = ID Y X Ctrl;
WITHIN = X Ctrl;
BETWEEN = ;
CLUSTER = ID;
MISSING = ALL (-99, -9, -1);

DEFINE:
    CENTER X (GROUPMEAN);
    CENTER Ctrl (GROUPMEAN);

ANALYSIS:
    TYPE = TWOLEVEL RANDOM;
    ESTIMATOR = ML;
    ITERATIONS = 10000;
    CONVERGENCE = 0.00005;

MODEL:
    %WITHIN%
    Y ON X Ctrl; ! Predictors
    Y X Ctrl;

    %BETWEEN%
    [Y]; ! intercept
    Y;

My understanding is that -2LL should be decreasing because we are providing more explanatory variables to the model. In fact, my second predictor is significant with a higher coefficient compared to my first predictor.
Any thoughts as to why it is increasing instead is this case?
Is there something I can try to fix it?
Thank you for your help!
Comment: Given what you shared, this is strange. First question, is the outcome the same in both models? It could be a missing data problem such that the log likelihood drops from losing cases when you add in the predictor.
Comment: Thank you for your comment! The DV is the same in both models as well as number of cases. I am having the same issue whether applying FIML (because I do have missing data) or using LISTWISE=ON (to use only complete data). For information, I collected my data over 4 time points for several days (3-7 days), That's why I have missing data in some points and why I intend to keep FIML (if it's not causing the issue). The first predictor is from T2, the second predictor and the DV are T4 variables.
Comment: I'd recommend creating a complete cases dataset for all variables in both models and running the analysis with this complete cases dataset to see if the same issue happens. Also, what exactly is your model given that you have these CFI, TLI statistics?
Comment: Hello, thanks again for your feedback. I have tried using only complete data in a different dataset and the results are the same (drop in LL instead of improvement). As for the model, my aim is build up a moderation model (after this, I'm adding a third predictor supposed to be my moderator), but the LL keeps deteriorating, so... I will edit my post above to include the syntax for both models if that is helpful.
Comment: I would try this model in a different software for a start to see if the same problem happens. I know Mplus may be doing something unique with group mean centering so you may not be able to exactly replicate what you have here. But you could create the more usual group mean centered variables.
Answer:
For information, I collected my data over 4 time points for several
days (3-7 days), That's why I have missing data in some points and why
I intend to keep FIML (if it's not causing the issue). The first
predictor is from T2, the second predictor and the DV are T4
variables.

This could be part of your problem. This model assumes that the outcome is repeatedly measured within clusters (ID). So if the outcome was only measured at T4, then a multilevel model is not valid given everything else you've said about your data (X measured at T2).
Instead, you can run this as a single level regression or path model. Assuming the data is wide (separate rows for each timepoint of a variable):
USEVARIABLES = ID Y_T4 X_T2 Ctrl;
MISSING = ALL (-99, -9, -1);

ANALYSIS:
        ESTIMATOR = MLR;
        ITERATIONS = 10000;
        CONVERGENCE = 0.00005;

MODEL:
    Y_T4 ON X_T2 Ctrl; ! Predictors
    Y_T4 X_T2 Ctrl; X_T2 WITH Ctrl; ! for full FIML specification

Comment: Hello! Thank you for your feeedback! Sorry, I was not very clear. I have collected those variables 4 times a day each day for between 3 and 7 days for each participant. That means that for each day within individuals, I have collected all my variables above, so they are at the within level (within individuals). The different time points serve to seperate measurements and estalish a stronger causal claim. However, they are not measured only once, they are repeated measures.


Ljung-Box and Breusch-Godfrey for univariate time series

Question: I am testing autocorrelation of a raw time series, not the residuals with Ljung-Box and Breusch-Godfrey tests. The problem is that I am getting contradicting p-value results for some series:
Ljung-Box
> x<-c(-1.26,-1.33,0.63,1.08,1.65,2.86,0.77,1.06,-0.25,0.44,-0.81,0.18,1.02,0.44,0.88,1.61,0.15,-0.95,-0.92,2.13,1.12,-0.18,0.9,0.2,0.59,-0.35,0.78,-2.14,-1.66,0.36,1.24,-0.57,-0.56,-1.12,-0.07,0.93,-0.19,-1.03,1.26,1.14,1.95,1.9,1.06,0.53,1.44,0.33,0.3,-0.86,-2.05,0.3,-0.46,2.24,-1.53,1.9,0.1,-0.35,0.16,1.46,2.53,0.75,1.23,0.8,-8.83,-1.72,1.07,-0.77,5.6,5.27,5.66,2.98,3.61,4.56,7.6,2.88,3.04,2.52,2.16,0.55,2.19,0.39,2,4.27,1.24,1.93,2.05,2,0.66,-2.8,2.22,2.93,2.32,3.6,1.57,3.64,2.01,0.05,1.85,0.65,-0.48,1.54,2.17,3.96,4.64,3.91,4.58,1.49,1.75,2.48,4.75,-0.41,0.32,2.16,1.61,2.59,1.62,1.36,1.08,2.02,1.46,-0.15,0.75,0.59,1.18,2.33,2.25,0.49,0.93,0.89,1.95,1.24,1.03,0.3,2.06,1.39,1.28,1.43,-1.12,-1.39,6.31,2.45,0.25,1.77,-1.85,-1.65,0.49,0.44,-2.75,-0.25,0.64,3.18,-0.75,-0.78,4.41,2.43,1.85,1.29,1.99,2.62,1.11,0.88,-0.15,2.01,1.15)
> lb<-Box.test(x, lag=1, fitdf=0, type="Ljung-Box")$p.value
> lb
[1] 3.185489e-07

Breusch-Godfrey:
> xlag <- cbind(
+     filter(x, c(0,1), method= "conv", sides=1),
+     filter(x, c(0,0,1), method= "conv", sides=1),
+     filter(x, c(0,0,0,1), method= "conv", sides=1))
> bg1 <- bgtest(x ~ 1+xlag, order=1, type="F", fill=NA)$p.value
> bg1
[1] 0.4321826

What am I doing wrong?
Answer: Your Ljung-Box test is indeed applied on the raw data. However, your Breusch-Godfrey test is applied on residuals from an autoregressive model (due to the code bit x ~ 1+xlag; see the section formula in the bgtest documentation for details).


Question on calculating probability of independent and mutually exclusive events

Question: I am given the following question:
Monitor customer behavior in the Phonesmart store. Classify the behavior as buying (B) if a customer purchases a smartphone. Otherwise the behavior is no purchase (N). Classify the time a customer is in the store as long (L) if the customer
stays more than three minutes; otherwise classify the amount of time as rapid
(R). Based on experience with many customers, we use the probability model
P[N] = 0.7, P[L] = 0.6, P[NL] = 0.35. Find the following probabilities:
a) $P[B\cup L]$
b) $P[N\cup L]$
c) $P[N\cup B]$
d) $P[LR]$
Here is my approach, create a table listing L R B N
The table with original data:
<code>     L      R
---------------------
B
---------------------
N   0.35          0.7
---------------------
    0.6
</code>
Then I just fill in the blanks:
<code>     L      R
---------------------
B   0.25   0.05   0.3
---------------------
N   0.35   0.35   0.7
---------------------
    0.6    0.4    1.0
</code>
so then
a) $P[B\cup L] = P[B] + P[L] - P[B\cap L] = 0.3 + 0.6 - 0.25 = 0.65$
b) $P[N\cup L] = P[N] + P[L] - P[N\cap L] = 0.7 + 0.6 - 0.35 = 0.95$
c) $P[N\cup B] = P[N] + P[B] = .7 + .3 = 1$
d) $P[LR] = 0$ since L and R are mutually exclusive.
Questions:

Did I calculate these probabilities correctly?
Are events L and R,  B and N mutually exclusive events?
Are events (B, L),  (B, R), (N, L), (N, R) independent events?
If the answer to 3 is Yes, then I am confused, according to the independence definition: $\text{Events A and B are independent if and only if }P[AB] = P[A]*P[B]$  P[NL] from the table is 0.35, but according to the definition, P[NL] = 0.7 * 0.6 = 0.42. Where did I get it wrong?
Answer: To answer my own question #3.
I suppose, since P[NL] = 0.35, and does not equal to P[N] * P[L] = 0.7 * 0.6 = 0.42, event N and L are are independent events.
Knowing how long a customer stays in a store can predict the likelihood of spending money by said customer.
However, if P[L] and P[R] each has a probability of 0.5, then event N and L can become two independent events:
<code>Assume L and R each has a probability of 50%

     L      R
---------------------
B   0.15   0.05   0.3
---------------------
N   0.35   0.35   0.7
---------------------
    0.5    0.5    1.0
</code>
then P[NL] = P[N] * P[L] = 0.7 * 0.5 = 0.35, only then the duration of a customer staying in the shop has no influence on their purchase decision.
Comment: "does not equal" implies that they are *not* independent here
Comment: @Henry, if I change the P[L] to be 0.5 instead of 0.6, , then P[N] * P[L] = 0.35, which equals to P[NL], does it then make L and N independent?
Comment: Yes - if you changed the "table with original data" to have $0.5$ instead of $0.6$ and left the $0.7$ and $0.35$ unchanged then $N$ and $L$ would be independent  (as would $B$ and $L$, and $N$ and $R$, and $B$ and $R$)
Comment: @Henry, that is very interesting. Two (or more) events could be made independent or dependent of each other just by empirical observation, i.e., one day, N and L can be dependent, and the next day, N and L can become independent, only to rely on the customers' behavior of that day.
Comment: In the question these are random variables, so can be dependent or independent; they can be mutually exclusive and if they are then will be dependent (unless one of them has probability $0$ or $1$).  Observations are different: if you do not know the probabilities then the observations may be suggestive of whether the probabilities are independent or not (for example you could use a chi-squared test)  but cannot tell you for sure
Answer: I think you have everything correct.
<code>     L      R
---------------------
B   0.25   0.05   0.3
---------------------
N   0.35   0.35   0.7
---------------------
    0.6    0.4    1.0
</code>
looks reasonable so I would use addition of the components as a check and say

$P[B\cup L] = P[B\cap L] + P[B \cap R] + P[N\cap L] = 0.25 + 0.05 +0.35  = 0.65$

$P[N\cup L] = P[N\cap L] + P[N \cap R] + P[B\cap L] = 0.35 + 0.35 +0.25  = 0.95$

$P[N\cup B] = P[N\cap L] + P[N \cap R] + P[B\cap L] + P[B\cap R] = 0.35 + 0.35 +0.25+0.05  = 1$

As described: L and R are mutually exclusive (otherwise helps here); similarly N and B are mutually exclusive.
The events are not independent: as you say for example $P[N\cap L]=0.35$, which is not equal to $P[N]\, P[L] = 0.7 \times 0.6=0.42$.


Which function I am required to alter the table (add column) in a stored procedure? Select into? or Insert into?

Question: I'm working on a complex stored procedure that is already existing. I wanted to add few more columns when I noticed that I need to alter the table / temptable first before I could add it in the stored procedure.
I thought the temp table is just temporary for that session , why do I have to alter the table before I could add a new column?
SELECT *INTO #FAC_CEDED_PREMIUM_Casualty_BA FROM
(
    SELECT
        POLICY_NO AS POLICY_NO,
        REINSURANCE_CONTRACT AS REINSURANCE_CONTRACT_ID,
        EXTERNAL_CARRIER AS EXTERNAL_CARRIER_ID,
        INTERMEDIARY_CD AS INTERMEDIARY_CD,
        TRANS_ACCTG_TMONTHNUMBER AS ACCOUNTING_PERIOD,
        RC1.FAC_Certificate_NO as Certificate_No,
        RC1.COVERS_FULL_POLICY_IND AS COVERS_FULL_POLICY_IND,
        RC1.reinsurance_contract_type_cd as REINSURANCE_CONTRACT_TYPE_CD,
        RC.REINSURANCE_CONTRACT_REFERENCE_NO as REINSURANCE_CONTRACT_REFERENCE_NO,
        RC1.CONTRACT_CURRENCY as CONTRACT_CURRENCY,
        RC1.TREATY_OR_FACULTATIVE_CD,
        RC1.Contract_Nm,
        RC1.CONTRACT_EXPIRATION_DT,
        SUM(WRITTEN_PREMIUM_TRANSACTIONAL_CURRENCY_AMT) AS WRITTEN_PREMIUM,
        SUM(COMMISSION_TRANSACTIONAL_CURRENCY_AMT) AS COMMISSION

    FROM CEDED_PREMIUM_Casualty_BA CP
        INNER JOIN DW.VDWH_REINSURANCE_CONTRACT RC ON CP.REINSURANCE_CONTRACT = RC.ID
        INNER JOIN DW.VDWH_REINSURANCE_CONTRACT01 RC1 ON RC.ID = RC1.ID AND RC1.TO_DATE = '9999-12-31 00:00:00.000'
    WHERE 1=1

    GROUP BY POLICY_NO,RC1.TREATY_OR_FACULTATIVE_CD,REINSURANCE_CONTRACT,EXTERNAL_CARRIER,INTERMEDIARY_CD,
            FAC_CERTIFICATE_NO,
            Contract_Nm,
            RC1.CONTRACT_EXPIRATION_DT,
            TRANS_ACCTG_TMONTHNUMBER,
            COVERS_FULL_POLICY_IND,reinsurance_contract_type_cd,REINSURANCE_CONTRACT_REFERENCE_NO,CONTRACT_CURRENCY

)A

SELECT *INTO #FAC_FACT_LIMIT_Casualty_BA FROM
(
    SELECT
        VL.POLICY_NO,
        VL.REINSURANCE_CONTRACT_REFERENCE_NO,
        VL.REINSURANCE_CONTRACT,
        VL01.TRANSACTION_CURRENCY_LIMIT_AMT ,
        VL01.TRANSACTION_CURRENCY_PART_OF_AMT,
        VL01.TRANSACTION_CURRENCY_EXCESS_OF_AMT,
        VL01.TRANSACTION_CURRENCY_AGGREGATE_AMT,
        VL01.TRANSACTION_CURRENCY_MINIMUM_AMT   ,
        VL01.TRANSACTION_CURRENCY_MAXIMUM_AMT   ,
        VL01.FUNCTIONAL_CURRENCY_LIMIT_AMT,
        VL01.FUNCTIONAL_CURRENCY_PART_OF_AMT    ,
        VL01.FUNCTIONAL_CURRENCY_EXCESS_OF_AMT  ,
        VL01.FUNCTIONAL_CURRENCY_AGGREGATE_AMT,
        VL01.FUNCTIONAL_CURRENCY_MINIMUM_AMT,
        VL01.FUNCTIONAL_CURRENCY_MAXIMUM_AMT
    FROM DW.VDWH_LIMIT VL
   INNER JOIN DW.VDWH_LIMIT01 VL01 ON VL.ID = VL01.ID AND VL01.TO_DATE = '9999-12-31 00:00:00.000'
    WHERE 1=1--POLICY_NO  = '32ESP1546200'
    AND DIRECT_ASSUMED_CEDED_CD  = 'C'
)A

**ALTER TABLE #FAC_CEDED_PREMIUM_Casualty_BA ADD FAC_LAYER_ID INT NULL**

Another set of Altering the table is this.
SELECT
    POLICY_NO,
    0 FAC_LAYER_ID,
    [Insured Name],
    [Effective Date],
    [Expiration Date],

    /* LS(093014) - Added Region and Underwriter */
    Region,
    Underwriter,
    /*********************************************/

    /* LS(101614) - Added BU and SubU            */
    Business_Division,
    Business_Subdivision,
    /*********************************************/

    REINSURANCE_CONTRACT_TYPE_CD,
    FAC_CERTIFICATE_NO,
    COVERS_FULL_POLICY_IND,
    CARRIER_NM,
    POLICY_STATUS_CD,

    GWP,
    COMMISION,
    CommisionPct,
    TotalCWP,
    NWP,
    'Treaty' TreatyFac,
    TreatyCededPremium CededPremium,
    TreatyCededCommission CededCommision,
    CAST(CASE
        WHEN ISNULL(TreatyCededPremium,0) <> 0 THEN ROUND((TreatyCededCommission/TreatyCededPremium) * 100,2)
        ELSE 0
    END AS DECIMAL(25,2)) CommissionPct,
    'QS' CedingType,--CHANGE IT LATER NOT HARDCODED
    1 Sort

INTO #TEMP_Reinsurance_Report_Details_Casualty_BA
FROM ERG.Reinsurance_Report_Summary_Casualty_BA WITH(NOLOCK)

ALTER TABLE #TEMP_Reinsurance_Report_Details_Casualty_BA ADD
    --FACLimit DECIMAL(18,2) NULL,
    --FACAttachmentPoint DECIMAL(18,2) NULL,
    --Reinsurer VARCHAR(500) NULL,
    --ReinsurerCWP DECIMAL(18,2) NULL,
    --ReinsurerCommission DECIMAL(18,2) NULL,
    --ReinsurerCommissionPCT DECIMAL(5,2) NULL

    **FACLimit DECIMAL(25,2) NULL,
    FACAttachmentPoint DECIMAL(25,2) NULL,
    Reinsurer VARCHAR(500) NULL,
    ReinsurerCWP DECIMAL(25,2) NULL,
    ReinsurerCommission DECIMAL(25,2) NULL,
    ReinsurerCommissionPCT DECIMAL(25,2) NULL**

Comment: As posted this doesn't make a lot of sense. The only question I see is asking about why you have to alter the table. That is because it is how you add columns to a table. It doesn't matter if it is a persistent table or a temp table. Once it is created, to change it you have to issue an alter statement.
Answer: You don't have to alter the table, you can just add the columns to the original select with null value + convert, like this:
SELECT
    POLICY_NO AS POLICY_NO,
    ...
    convert(int, NULL) as FAC_LAYER_ID

Altering the temporary tables is usually not a good idea because it will prevent caching of the tables in temp db for the next run. You can read more details about this in Paul White's blog post


How do I use raw_input with classes in a definition

Question: Problem
I'm writing a script in Python 2.7 that has the user input the atomic symbol for an element. The script then prints out information about the element.
However, I'm not sure how to have a class use a variable from the raw_input. Here is the code with a couple of the 118 elements gone for readability:
Code
class PTable(object):
    def __init__(self, name, atom_num, atom_sym, atom_mass,period, group, atom_type,state):
        self.name = name
        self.atom_num = atom_num
        self.atom_sym = atom_sym
        self.atom_mass = atom_mass
        self.period = period
        self.group = group
        self.atom_type = atom_type
        self.state = state

h = PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas")
he = PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas")
li = PTable("Lithium",3,"Li",6.941,2,1,"Alkali metal","Solid")
be = PTable("Beryllium",4,"Be",9.0121831,2,2,"Alkaline earth","solid")
og = PTable("Oganesson",1,"H",1.008,1,1,"Nonmetal","Gas")

def results(name, num, sym, mass, per, gro, typ, state):
    print "Name:", name
    print "Atomic number:", num
    print "Atomic symbol:", sym
    print "Atomic mass:", mass
    print "Period:", per
    print "Group:", gro
    print "Type:", typ
    print "State:", state
# results(h.name, h.atom_num, h.atom_sym, h.atom_mass, h.period, h.group, h.atom_type, h.state)
def hub():
    x = raw_input("What element? ")
    results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x)
    hub()

hub()

Errors
The code that gives me the syntax error is:
results(%s.name, %s.atom_num, %s.atom_sym, %s.atom_mass, %s.period, %s.group, %s.atom_type, %s.state) % (x)

The error is obvious; syntax is wrong, so I tried another way:
results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state)

That, too, did not work, and I got the error

Traceback (most recent call last):
File "C:/Users/NAME/Desktop/PTable.py", line 146, in
hub()

File "C:/Users/NAME/Desktop/PTable.py", line 143, in hub
results(x.name, x.atom_num, x.atom_sym, x.atom_mass, x.period, x.group, x.atom_type, x.state)

AttributeError: 'str' object has no attribute 'name'

Question
Do you know how I can make it so the user is able to type in the name of the element (the atomic symbol) and the code prints out the information?
Comment: you are confusing string formatting with class syntax. maybe look for a [good python tutorial](https://docs.python.org/2/tutorial/classes.html#a-first-look-at-classes)
Comment: Oganesson is kind of new.
Answer: Recovering an element
The line x = raw_input("What element? ") provides you with a string, say 'he', so when you call x.name you are attempting to access an attribute of that string and  not of the variable he.
What you should do is store your elements in a dictionary instead of having them as variables and access them with the key provided by your user.
periodic_table = {
    'h': PTable("Hydrogen",1,"H",1.0079,1,1,"Nonmetal","Gas"),
    'he': PTable("Helium",2,"He",4.0026,1,18,"Nonmetal","Gas"),
    ...
}

symbol = raw_input("What element? ")

try:
    element = periodic_table[symbol]

except KeyError:
    print('This element does not exist')

Printing the element
As for printing the element, I would suggest a more object-oriented approach by implementing the PTable.__str__ method.
class PTable(object):

    ...

    def __str__(self):
        # Add in the format and information that you want to be printed
        return "Name: {}".format(self.name)

You can then directly print your elements.
print periodic_table['he']
# prints: 'Name: Helium'


Whats The Difference Between The Following Two C++ Classes?

Question:     //Version 1
    template <typename T>
    class Node<T> {
        private:
            T data;
            Node *next;
        public:
            Node(T data) {
                this->data = data;
                this->next = NULL;
            }
    };

    //Version 2
    template <typename T>
    class Node {
        private:
            T data;
            Node *next;
        public:
            Node(T);
    };
    template <typename T>
    Node<T>::Node(T val) {
        data = val;
        next = NULL;
    }

I am confused on what the difference is between making a class using version 1 compared to making a class using version 2. What is the preferred way, Version 1 or Version 2?
Comment: One compiles, the other doesn't. Prefer the one that does.
Comment: @juanchopanza (rather, the other doesn't link.)
Comment: Please read a book and get used class-member initializer-lists.
Comment: The two are completely equivalent.
Comment: Version 2 won't even compile, it should be `template Node::Node(T val) { ... }`.
Comment: @TheParamagneticCroissant No, it doesn't compile.
Comment: @TheParamagneticCroissant you should really write an answer here. This issue is quite subtle and I can bet many many beginners are terribly confused by the linker error.
Comment: @vsoftco Meh, I don't think it's worth the pain. There are many duplicates already… I'm not here for rep-wh*ring :P ;)
Comment: @TheParamagneticCroissant actually the code links... The problem appear when trying to define friend functions outside the class.
Answer: Firstly, the second one simply does not compile. A correct syntax is
template <typename T>
Node<T>::Node(T val) {  // note the <T> part

But apart from this, there is no difference from the point of view of a compiler.
However, there is difference from the point of view of a programmer. It is generally considered wrong to pollute class declaration with implementation.  Another programmer who wants to use your code (or even you yourself when you move to another part of your project) should be able to understand what your code does without looking at implementation, therefore you should not pollute class declaration with implementation details.
Even better will be to separate code into a separate .cpp file, and #include that .cpp file into a header (the latter being a requirement for a templated class unless you use explicit instantiation). (Sometimes an extension other than .cpp, for example .tpp, is used for this purpose, but anyway the file should be included into the header.)

A separate note is that you should stick to member initialization lists in your constructors:
template <typename T>
Node::Node(T val): data(val), next(NULL)
{}

Comment: "...separate code into a separate .cpp file", considering this is a template, the OP is already putting the implementation [in the right place](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file?s=2|2.6765), so I'm not sure why this is even mentioned as part of this answer.
Comment: @WhozCraig, note the "...and #include in into a header" in my answer, and "A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header" in the link you gave.
Comment: @WhozCraig, fixed explicit instantiation, my bad. Also rephrased that part to make it more clear that the implementation should be still `#include`d into the header.
Comment: So you think version 2 is ideal? But instead of my version 2, I should add the implementations into a separate .cpp file?
Comment: I don't like the word 'ideal' as it's too strong, but personally I would choose version 2 with implementation in a separate file `#include`'d into the header (and with initializer lists). See also the question linked by WhozCraig
Answer: I would go with version 1 but without the explicit this pointers and member initializers:
//Version 1'
template <typename T>
class Node {
    private:
        T data;
        Node *next;
    public:
        Node(T _data) : data(_data), next(0) { }
};

For version 2 the namespace access with "::" is normally used in implementation files (.cc .cpp ...) and not in headers afaik
Comment: true, for version 1 the constructor is enclosed with in the class struct, well it was sloppy to call the class/struct name a namespace in case of version 2.
Answer: Formally, in the first version the constructor is inline, in the second version it is not. However for templates and modern optimizing compilers, this difference is immaterial: Since it is a template, the definition has to be in the same file anyway, and the optimizer likely ignores the optimization hint since it can determine by itself when the function is worthy of being inlined (which for such a simple function is always).


How to reload spfx web part after post()?

Question: I am creating spfx webpart with React framework.
I am having render method where all the controls were rendered. i am having a button, few checkboxes in the DOM which will send data to SharePoint using post method this.context.spHttpClient.post when user clicks on button. I am able to submit the data to SharePoint. But once I submit the data I am not able to reload the spfx webpart. I have to reload the web part again without reloading the page. I have tried to call the render method again. Of course it may not be correct way, so it is not working.
Answer: You can either call a force reload or set state as shown here and here
"By default, when your component's state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().
Calling forceUpdate() will cause render() to be called on the component, skipping shouldComponentUpdate(). This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate() method of each child. React will still only update the DOM if the markup changes.
Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render()."
Answer: You should use this methods:

componentDidMount()
componentDidUpdate(prevProps, prevState, snapshot)
componentWillUnmount()
shouldComponentUpdate(nextProps, nextState)

More info here https://reactjs.org/docs/react-component.html.
For example, in a project i have a list of buttons and i do a click so i send the event to another component that use the state:
LeftPanel.tsx :
import * as React from 'react';
import { Button } from 'react-bootstrap';
import { Event } from '../interfaces/Event';
import '../components/GruposDeColaboracion.module.scss';
import '../css/leftPanel.css';

export class LeftPanel extends React.Component {
    constructor(public props, public context) {
        super(props, context);
    }

    private getAllGroups = (e) => {
        this.clearState();
        this.setActive('allGroups');
        this.props.setEvent(Event.GET_ALL_GROUPS);
        //e.stopPropagation();
    }

    public render():JSX.Element{
            return (

                    <Button
                        id="allGroups"
                        onClick={this.getAllGroups}
                        className="list-group-item rounded-0 list-group-item-action btn btn-default active">
                        Todos
                    </Button>

            );
    }
}

MainPanel.tsx:
import * as React from 'react';
import { LeftPanel } from '../views/LeftPanel';
import { CenterPanel } from '../views/CenterPanel';
import { IHomeState } from '../interfaces/IHomeState';

export class MainPanel extends React.Component<{}, IMainState> {

    constructor(public props, public context) {
        super(props, context);
        this.state = {
            event: null
        };
    }

    private getEvent = (event) => {
        this.setState({ event: event });
    }

    public shouldComponentUpdate(nextProps, nextState): boolean {
        if (this.state.event != nextState.event) {
            return true;
        }
        return false;
    }

    public render(): JSX.Element {
            return (

                        <LeftPanel setEvent={this.getEvent} />

                        <CenterPanel event={this.state.event} context={this.props.context} />

            );
        }
}

CenterPanel.tsx :
export class CenterPanel extends React.Component<{}, ICenterPanelState> {
    constructor(public props, public context) {
        super(props, context);
    }

  public componentWillMount() {

        this.state = {
            render: <Spinner />
        };
    }

  public componentWillReceiveProps(nextProps) {
    if (nextProps.event == Event.GET_ALL_GROUPS) {
      let dataForRender = 'Hello';
      this.setState({
        render: <ResponseHandler data = {dataForRender}/>
      });
    }
  }
    public render():JSX.Element{
        return(

            {this.state.render}

        );
    }
}

ResponseHandler.tsx :
import * as React from 'react';

export class ResponseHandler extends React.Component {

    constructor(public props, public context) {
        super(props, context);
    }

    public render():JSX.Element {

        return (

                {this.props.data}

        );
    }
}

In this example you can see:

Left panel use this.props.setEvent('custom event') to send the event from MainPanel.
In main panel private getEvent = (event) => {...} recive the event and change the state and in render method i have: . You can see the event={this.state.event} that change the prop event in the class CenterPanel.
In center panel public componentWillReceiveProps(nextProps) {....} recive the event and and use state to render.


Comentários em classes causam lentidão no Eclipse?

Question: Eu tenho um projeto antigo, cujo tamanho é 225Mb, onde a maioria das classes tem o corpo todo comentado. No passado eu não usava versionamento de código na minha empresa e o versionamento era feito no próprio código, comentando uma linha e escrevendo a alteração na linha abaixo. Exemplo:
==> 2019-07-09 o código era:
<code>System.out.println ("Hello World 1");
</code>
==> 2019-07-10 o código era:
<code>//System.out.println("Olá Mundo 1 ");
System.out.println ("Hello World 2");
</code>
==> 2019-07-11 o código era:
<code>//System.out.println("Olá Mundo 1 ");
//System.out.println ("Hello World 2");
System.out.println ("Hello World 3");
</code>
Agora imagine isso para mais de 2000 classes, onde existem vários blocos grandes de código comentado.
Todas essas classes podem causar lentidão no Eclipse?
Por que quando abro este projeto o Eclipse fica muito lento?
Comment: @IgorMoisés como não é uma questão do programa sendo desenvolvido, você precisa usar um `profiler` direto no Eclipse. Talvez o VisualVM consiga pegar, mas não sei o quão útil será para você, nem se a informação estará prontamente legível.
Comment: Sim, absolutamente, o eclispe é um IDE e corre verificações analisando o texto e quanto maior o texto maior o tempo de execução e por isso aparece a lentidão a que se refere.
Estão a ser feitas operações no fundo, o que faz com que o programa de edição fique lento.
Comment: Há algum profile do eclipse onde seja possível apresentar esses gargalos ?
Answer: Não vou afirmar categoricamente, mas não causa nada muito significativo, pelo menos deveria ser algo muito pequeno e imperceptível.
Eu sei que o Eclipse faz muitas análises enquanto você está codificando e isso tem um custo, quanto mais texto para analisar mais lento fica, mas não é para mudar muita coisa, o grosso do tempo gasto na análise é feita em coisas muito mais relevantes, o casso dos comentários só gastará tempo no scanner e imagino ter otimizações para evitar repetição onde não deve, então não deve se preocupar com isso.
Eu passaria os dados de versionamento para outro lugar e retirá-los pra limpar o código com coisas que não deveriam estar aí, deve dar um ligeiro ganho (bem ligeiro mesmo, não sei se perceberá) mas o motivo para fazer isto não deve ser a performance.
Códigos antigos não deveriam ficar na base de código oficial, tire isto também.
O Eclipse é lento e isto é perceptível quanto mais código tem. O estrago maior é analisando o código em si e não os comentários. O Eclipse tem uma arquitetura ruim e ultrapassada, é famoso por ser lento e dá má fama ao Java que um dia já foi lento mas hoje não é mais. A maior parte das lentidões encontradas em programas Java é culpa do programa e não do Java, é muita gente com mentalidade de "código enterprise" enfiando um monte de penduricalhos desnecessários em nome de "boas práticas" que elas não entendem.
Comment: @IgorMoisés apaga e ignora
Comment: A situação é que esse código legado já foi colocado num sistema de versionamento. O que acontece é que ele subiu do jeito que esta. Com grandes blocos de código comentado dentro das inúmeras classes. Quais outras ferramentas para desenvolvimento em java tem-se atualmente ?
Comment: JetBrains IntelliJ
Comment: Obrigado nobres colegas! Irei propor as mudanças!
Comment: Lembrando que o IntelliJ é pago, e a versão community não provê diversas features


$\lim_{n \to \infty} \frac{1}{2n}\log\binom{2n}{n}$

Question: Please help me to solve this problem. I can find almost no clue regarding the log part. I tried to break the $\binom{2n}{n}$ part, but in vague...will the breaking help me in anyway?
Comment: Think about a Riemann sum
Comment: Are you sure it's that? Something tells me it's the limit of $\frac{\binom {2n}{n}}{2n}.$
Comment: $\binom{2n}{n}$  doesn't matter. As long as it is an integer $\ge 2$, $\frac{1}{2n\log\binom{2n}{n}} \le \frac{1}{2\log(2) n}$...
Comment: Hmm... looking at the edit revisions. the edit from version 1 to version 2 seems wrong. The very original question can be interpreted as finding the limit of $\frac{1}{2n}\log\binom{2n}{n}$ too.
Comment: I meant $\frac{\log \binom {2n}{n}}{2n}.$
Comment: all - I changed the question to what it supposed to ask (based on edit version 1)
Comment: I think like @zhw it should be $\frac{\log{\binom{2n}{n}}}{2n}$ otherwise the limit is $0$ like in the hints I the answer of Elaqqad
Comment: It would be nice if MATHS would join in and reveal which question is being asked rather than those speculations!
Answer: $$\log\binom{2n}{n}=\log\prod_{k=1}^{n}\frac{n+k}{k}=\sum_{k=1}^{n}\log\frac{1+\frac{k}{n}}{\frac{k}{n}}\approx n\int_{0}^{1}\log\left(\frac{x+1}{x}\right)\,dx = 2n\log 2.$$
Answer: There are $2^{2n}=4^n$ subsets of a set of size $2n$, each of which has between $0$ and $2n$ elements.  Of these, ${2n}\choose{n}$ have exactly $n$ elements, and ${{2n}\choose{n}} > {{2n}\choose{k}}$ for any $k\neq n$.  Therefore,
$$
\frac{4^n}{2n+1} < {{2n}\choose{n}} \le 4^n,
$$
so
$$
n\log 4-\log(2n+1) < \log{{2n}\choose{n}} \le n \log 4,
$$
and
$$
\log 2-\frac{\log(2n+1)}{2n} < \frac{1}{2n}\log{{2n}\choose{n}} \le \log 2.
$$
We conclude that
$$
\lim_{n\rightarrow\infty}\frac{1}{2n}\log{{2n}\choose{n}} = \log 2.
$$
Answer: Hint You can use the following inequality: $$\frac{4^n}{n}\leq{2n \choose n}\leq 4^n$$ for large $n\geq 4$ (this is the proof for the left inequality)


Why do guitarists move fingers up and down on the same note?

Question: Usually at the end of playing a set of notes, I have noticed guitarists move a string up and down on the last note of that part (although not so much such that it classifies as a bend).
What is this for? Some kind of smoothening out of the note?
I have seen Eric Clapton do it a lot so don't know if it's a personal thing or a guitarist technique for better sounding music.
If the description above is not sufficient, watch 2:33-2:35 of this Clapton video to see what I mean
Comment: I cannot see the video that has been linked, as they are blocked where I am. Is this a an up-and-down motion (stretching the strings) or side-to-side one? I am assuming Clapton isn't playing an upright bass...
Comment: You can hear the effect if you listen, your video is actually a very strong example.
Answer: The particular vibrato that Eric is using is fairly specific to electric guitar playing. Its side to side motion changes the pitch of the fretted note and can be miminal, so very subtle, to more than a tone up and down. Whilst adding character to the note played (the speed of the vibrato will not always be the same), it also rubs the string across the fretwire, increasing the sustain of the note.
A similar, but different vibrato is used in classical guitar playing, when the finger rolls along the length of the string (all within the fret played on), which not only changes the pitch slightly, but also the tone of the note played.
Comment: Just adding to that, it's not that this vibrato doesn't work on other instruments - it certainly does.  But it produces a different type of sound which is not the same as that traditionally heard on those instruments.
Comment: @Graham - somehow, can't imagine violinists using it!
Comment: When I played the violin a bit more than I do now, I had to do something like that.  My arm can't do the normal violin vibrato, so I have to fake it with my fingers.  My pseudo-vibrato consists of pulling harder with my finger, essentially doing that slight string-bend as on a guitar, but laterally along the string.  It doesn't sound quite right for a violin, I have to admit, but it's the best I can do. :)
Answer: That is vibrato, which is a common technique with most stringed instruments.

a slightly tremulous effect imparted to vocal or instrumental tone for added warmth and expressiveness by slight and rapid variations in pitch (SOURCE: Merriam-Webster)

Various finger techniques to produce vibrato are used for stringed instruments, but many other instruments (can) produce vibrato: brass and wind instruments, for example. Singers – especially soloists – particularly focus on developing their vibrato.
A search for "vibrato" on this site will bring up numerous and widely varied questions related to the technique.
Comment: *Some* singers. Vibrato is not a desired property in every choral style.
Comment: Not at all sure the finger technique is common to most stringed instruments. In fact, it's more likely only common to guitars. On the premise that violins, celli, et al, use a rather different finger technique.
Answer:
Why do guitarists move fingers up and down on the same note?

It subtly moves the pitch of the note up and down to give a "sweeter" sound.
Here is a video that explicitly talks about producing vibrato on a guitar. It even distinguishes between different types of vibrato and shows in detail how to execute them.
Learn Electric Guitar Lesson - Vibrato


Prove $8(1-\cos^2a)(1-\cos^2b)(1-\cos^2c) \geq 27 \cos a\cos b\cos c$

Question:
Let $a$, $b$ and $c$ be angles of an acute triangle. Prove that:
  $$8(1-\cos^2a)(1-\cos^2b)(1-\cos^2c) \geq 27 \cos a\cos b\cos c$$

I tried am-gm, rm-gm rm-am and a couple of other inequalities but I didn't get anywhere.
Comment: What are $a,b,c$? Are they angles of a triangle?
Answer: Let $u$, $v$ and $w$ be lengths-sides of the triangle such that
$\cos{a}=\frac{v^2+w^2-u^2}{2vw}$, $\cos{b}=\frac{u^2+w^2-v^2}{2uw}$, $\cos{c}=\frac{u^2+v^2-w^2}{2uv}$ and
let $u^2+v^2-w^2=r$, $u^2+w^2-v^2=q$, $v^2+w^2-u^2=p$.
Hence, we need to prove that
$$8\prod_{cyc}\left(1-\frac{r^2}{(p+r)(q+r)}\right)\geq\frac{27pqr}{(p+q)(p+r)(q+r)}$$ or
$$8(pq+pr+qr)^3\geq27pqr(p+q)(p+r)(q+r).$$
Let $pq=z$, $pr=y$ and $qr=x$.
Hence, we need to prove that
$$8(x+y+z)^3\geq27(x+y)(x+z)(y+z),$$
which is AM-GM:
$$\left(\frac{\sum\limits_{cyc}(x+y)}{3}\right)^3\geq\prod_{cyc}(x+y).$$
Done!
Answer: Here's a proof that accounts for all acute-angled triangles whose angles lie in $ \left(\tan^{-1}{\sqrt{2}}, \dfrac{\pi}{2}\right)$.
Note that $f(x) = \ln \sin(x) \tan(x)$ is convex over $ \left( \tan^{-1}{\sqrt{2}}, \dfrac{\pi}{2}\right)$ since $f''(x) = \dfrac{\tan^{2}(x) -2}{\sin^{2}(x)} > 0 \quad \forall x\in \left(\tan^{-1}{\sqrt{2}}, \dfrac{\pi}{2}\right)$
Hence we can apply Jensen's inequality to $f(x)$ and $a, b,c \in \left(\tan^{-1}{\sqrt{2}}, \dfrac{\pi}{2}\right)$ to get:
$f\left(\dfrac{a+b+c}{3}\right)\leq \dfrac{f(a) + f(b)+ f(c)}{3}$
$\Rightarrow \ln \dfrac{3}{2} \leq \dfrac{\ln \dfrac{\sin^{2}(a)\,\sin^{2}(b)\,\sin^{2}(c)}{\cos(a)\,\cos(b)\,\cos(c)}}{3}$
$\Rightarrow \dfrac{27}{8} \leq \dfrac{\sin^{2}(a)\,\sin^{2}(b)\,\sin^{2}(c)}{\cos(a)\,\cos(b)\,\cos(c)}$, as required.
Can someone figure out an extension of this argument that accounts for those acute-angled triangles with one angle in $ \left(0, \tan^{-1}{\sqrt{2}}\right)$?
Answer: Let
$$\ a,\ b,\ c \in\left(0, \dfrac{\pi}{2}\right),\quad a+b+c = \pi,\qquad(1) $$
and let us try to find minimum of function
$$f(a,b) = 8\sin^2a\sin^2b\sin^2(\pi-a-b) - 27\cos a\cos b\cos(\pi-a-b),$$
in this area.
Equaling partial derivatives to zero, one can get
$$\begin{cases}
16\sin a\sin^2b\sin(\pi-a-b)(\cos a \sin(\pi-a-b) - \sin(a)\cos(\pi-a-b))\\
 - 27\cos b(-\sin a\cos(\pi-a-b) + \cos a\sin(\pi-a-b) = 0,\\
16\sin^2a\sin b\sin(\pi-a-b)(\cos b \sin(\pi-a-b) - \sin(b)\cos(\pi-a-b))\\
 - 27\cos a(-\sin b\cos(\pi-a-b) + \cos b\sin(\pi-a-b) = 0,
\end{cases}$$
$$\begin{cases}
-16\sin a\sin^2b\sin(\pi-a-b)\sin(\pi-2a-b) + 27\cos b(\sin(\pi-2a-b) = 0,\\
-16\sin^2a\sin b\sin(\pi-a-b)\sin(\pi-a-2b) + 27\cos a(\sin(\pi-a-2b) = 0,
\end{cases}$$
$$\begin{cases}
\genfrac{[}{.}{0}{0}{\sin(\pi-2a-b)=0}{16\sin a\sin^2b\sin(\pi-a-b) = 27\cos b }\\
\genfrac{[}{.}{0}{0}{\sin(\pi-a-2b)=0}{16\sin^2a\sin b\sin(\pi-a-b) = 27\cos a. }\\
\end{cases}$$
Let us consider all posible cases.
Case $1$
$$\begin{cases}
\sin(\pi-2a-b)=0\\
\sin(\pi-a-2b)=0
\end{cases}\qquad\rightarrow
\begin{cases}
2a+b = \pi\\
a+2b = \pi,
\end{cases}$$
$$a=b=\pi/3,\quad f(a,b) = 0.$$
Case $2$
$$\begin{cases}
\sin(\pi-2a-b)=0\\
16\sin^2a\sin b\sin(\pi-a-b) = 27\cos a,
\end{cases}\rightarrow
\begin{cases}
b = \pi-2a\\
16\sin^3a\sin2a = 27\cos a,
\end{cases}$$
$$\sin^4a = \frac{27}{32},\quad \sin^2a >5/6,\quad \cos2a = 1-2\sin^2a<-\dfrac23.\qquad(2)$$
So
$$f(a,\pi-2a) = 8\sin^4a\sin^22a + 27\cos2a\cos^2a = 16\sin^5a\sin2a\cos a + 27\cos2a\cos^2a$$
$$ = 27\sin^2a\cos^2a + 27\cos2a\cos^2a = 27\cos^2a(\sin^2a + \cos2a),$$
$$f(a, \pi-2a) > 27\cos^2a\cdot\dfrac16 >0.$$
Case $3$
$$\begin{cases}
\sin(\pi-a-2b)=0\\
16\sin^2a\sin b\sin(\pi-a-b) = 27\cos b,
\end{cases}$$
proves similarly to case $2$.
Case $4$
$$\begin{cases}
16\sin a\sin^2b\sin(\pi-a-b) = 27\cos b\\
16\sin^2a\sin b\sin(\pi-a-b) = 27\cos a.
\end{cases}\quad(3).$$
Subtraction of these equations with non-zero factors $\cos a$ and $\cos b$ leads to equation
$$\sin a\sin b\sin(\pi-a-b)(\sin b\cos a - \sin a\cos b) = 0,$$
$$\sin a\sin b\sin(\pi-a-b)\sin(a-b) = 0,$$
$$\sin(a-b) = 0,\quad a=b.$$
Substitution to $(3)$ gives
$$16\sin^3a\sin2a = 27\cos a,$$
$$32\sin^4a = 27,$$
and then using $(2)$
$$f(a,a) = 8\sin^4a\sin^22a + 27\cos2a\cos^2a = 16\sin^5a\sin2a\cos a + 27\cos2a\cos^2a$$
$$ = 27\sin^2a\cos^2a + 27\cos2a\cos^2a = 27\cos^2a(\sin^2a + \cos2a),$$
$$f(a, a) > 27\cos^2a\cdot\dfrac16 >0.$$
That means that in the OP conditions
$$\boxed{8(1-\cos^2a)(1-\cos^2b)(1-\cos^2c) \geq 27 \cos a\cos b\cos c}$$