How do I stretch the view when tab is hidden

Question: I'm using the auto layout via the storyboard.
override func viewWillAppear(animated: Bool) {
<code>    //hide bottom bar
    self.tabBarController?.tabBar.hidden = true

}

// postload func
override func viewWillDisappear(animated: Bool) {
    self.tabBarController?.tabBar.hidden = false

}
</code>

As you can see black is tabczontroller's height..How do I stretch the view to screen's bottom?
Answer: You just layout to bottom layout guide which contains the tab bar.
Comment: Thanks for the reply. I had solved to check "Hide bottom Bar on Push" instead of self.tabBarController?.tabBar.hidden = true thanks :)


Which notation should be used for the mean, SD, and median: mean±SD or mean (SD)?

Question: I usually use mean±SD notation for reporting values. I know that many people use mean (SD) notation and I understand why.
Right now in the document I am writing I am also reporting medians but I don't know which notation I should use for the 3 measures. Any suggestions?
Answer: Both conventions you mention are ambiguous - for example you can't tell whether the number after the $\pm$ is a standard deviation, a standard error, or the half-width of an interval. (a problem that has led to numerous questions on this site).
If you're publishing somewhere that offers precise guidelines follow those, but otherwise I suggest being explicit, for example: $``\text{median } 28.5,$ $\text{ mean } 31.2,$ $\text{ standard deviation } 3.6\!"$ -- then there's no possibility of misinterpretation.
Comment: +1. I usually write $``31.2 \pm 3.6\text{ (mean}\pm\text{SD)}\!"$ and hope that this is clear enough...
Comment: @amoeba That's explicit, so it looks okay to me. I wasn't trying to hold people to any one format, just avoiding ambiguity; yours does that.
Comment: Well, I end up using 5.0 (5) ± 0.5 (2.5) [0 - 10] for the hypothesis variable (the numbers I show here are not the true values) and inserted a footnote explaining the format Mean (Median) ± SD (Q1-Q3) [Min - Max]. For all other variables, since they are presented in tables, it was inserted a table footnote explaining the format: Mean ± SD [Min - Max] or Median (Q1-Q3)
Answer: I personally usually use Mean (Median) $\pm$ SD (IQR) [Min - Max]. That's quite maximalist, so may be a bit too much for certain purposes/readers, but is a quite logical grouping of indicators (central tendency $\pm$ dispersion, with traditional indicator first, robust alternative in parenthesis), I believe. (Minimum and maximum is of course added not because they're statistically especially important or good indicators, but because on the biomedical field it is often required for ''clinical'' purposes.)
Comment: I actually like this idea, but only if the order is explicitly specified in the paper so the reader knows what they're looking at
Comment: @ssdecontrol: Of course! I usually specify it in the - say - table caption.


Determine the number of integral solutions of the equation

Question: \begin{align}
&\mbox{Let}\quad
x_{1} + x_{2} + x_{3} + x_{4} = 20\quad
\mbox{which satisfy:}\quad
\left\{\begin{array}{rcccl}
{\displaystyle 1} & {\displaystyle \leq} &  {\displaystyle x_{1}} & {\displaystyle \leq} & {\displaystyle  6}
\\
{\displaystyle 0} & {\displaystyle \leq} & {\displaystyle x_{2}} & {\displaystyle \leq} & {\displaystyle 5}
\\
{\displaystyle 4} &  {\displaystyle \leq} &  {\displaystyle x_{3}} &
{\displaystyle \leq} & {\displaystyle 9}
\\
{\displaystyle 2} & {\displaystyle \leq} &  {\displaystyle x_{4}} &  {\displaystyle \leq} &  {\displaystyle 7}
\end{array}\right.
\\
&\mbox{Determine the number of integral solutions.}
\\ &\mbox{}
\end{align}
I figured out that I could change each equation to some $y_{i}$ such that
$0 \leq y_{i} \leq 6$.

So I would have $y_{1} = x_{1}, y_{2} = x_{2} + 1, y_{3} = x_{3} - 3$ and $y_{4} = x_{4} - 1$.

This then gives me an equation where
$y_{1} + \cdots + y_{4} = 17$.
From here, I do not know where to go. How do I figure out the number of integer solutions ?.
Answer: The first step is to transform the bounds on your variables. The equivalent problem is to find the number of integer solutions for:
$z_1+z_2+z_3+z_4=17 \\ 1\leq z_1,z_2,z_3,z_4\leq 6$
Now let $y_i=7-z_i$, then an auxiliary problem is
$y_1+y_2+y_3+y_4=11 \\ 1\leq y_1,y_2,y_3,y_4\leq 6$
We can now start a stars-and-bars approach. We're going to be separating eleven stars using three bars. That's $_{10}C_3$. Now, we're going to subtract off the ways we can go outside of our bounds with any of the variables.
Suppose one of our variables is bigger than $6$. WLOG, let $y_1>6$. There are two valid cases, one when $y_1=7$ and one when $y_1=8$. We can't have $y_1$ be bigger than that, because $3$ units must be left over for the other variables.
When $y_1=7$, we count arrangements by applying the stars-and-bars approach to the remaining four units. That's $_3C_2$. When $y_1=8$, there's only going to be one valid arrangement for the other variables, $y_2=y_3=y_4=1$. That's a total of $_3C_2+1=3+1=4$ infringing  arrangements when $y_1>6$. Because our choice of infringing variable was arbitrary, we need to account for the other three variables, too. That's a total of $4\times4=16$ infringing arrangements. No two variables can be over six at the same time, so there's no double-counting.
The total number of valid solutions to this problem would then be $_{10}C_3-16=120-16=104$.
Answer: $\newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\dsc}[1]{\displaystyle{\color{red}{#1}}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,{\rm Li}_{#1}}
 \newcommand{\norm}[1]{\left\vert\left\vert\, #1\,\right\vert\right\vert}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
\begin{align}
&\bbox[10px,#ffd]{\ds{%
\sum_{x_{1}\ =\ 1}^{6}\sum_{x_{2}\ =\ 0}^{5}\sum_{x_{3}\ =\ 4}^{9}
\sum_{x_{4}\ =\ 2}^{7}\delta_{x_{1} + x_{2} + x_{3} + x_{4},\,20}}} =
\sum_{x_{1}\ =\ 0}^{5}\sum_{x_{2}\ =\ 0}^{5}\sum_{x_{3}\ =\ 0}^{5}
\sum_{x_{4}\ =\ 0}^{5}
\delta_{\pars{x_{1} + 1} + x_{2} + \pars{x_{3} + 4}+ \pars{x_{4} + 2},20}
\\[5mm] = &\
\sum_{x_{1}\ =\ 0}^{5}\sum_{x_{2}\ =\ 0}^{5}\sum_{x_{3}\ =\ 0}^{5}
\sum_{x_{4}\ =\ 0}^{5}\delta_{x_{1} + x_{2} + x_{3} + x_{4},13} =
\sum_{x_{1}\ =\ 0}^{5}\sum_{x_{2}\ =\ 0}^{5}\sum_{x_{3}\ =\ 0}^{5}
\sum_{x_{4}\ =\ 0}^{5}\bracks{z^{13}}z^{x_{1} + x_{2} + x_{3} + x_{4}} =
\bracks{z^{13}}\pars{\sum_{x = 0}^{5}z^{x}}^{4}
\\[5mm] = &\
\bracks{z^{13}}\pars{z^{6} - 1 \over z - 1}^{4} =
\bracks{z^{13}}\pars{1 - z^{6}}^{4}\pars{1 - z}^{-4} =
\bracks{z^{13}}\sum_{k = 0}^{4}{4 \choose k}\pars{-z^{6}}^{k}
\sum_{n = 0}^{\infty}{-4 \choose n}\pars{-z}^{n}
\\[5mm] = &\
\bracks{z^{13}}\sum_{k = 0}^{4}\sum_{n = 0}^{\infty}{4 \choose k}
{-4 \choose n}\pars{-1}^{k + n}\,z^{6k + n} =
\sum_{k = 0}^{4}\sum_{n = 0}^{\infty}{4 \choose k}
{n + 3 \choose n}\pars{-1}^{k}\,\,\delta_{6k + n,13}
\\[5mm] = &\
\sum_{k = 0}^{4}\sum_{n = 0}^{\infty}{4 \choose k}
{n + 3 \choose 3}\pars{-1}^{k}\,\,\delta_{n,13 - 6k} =
\sum_{k = 0}^{4}{4 \choose k}
{16 - 6k \choose 3}\pars{-1}^{k}\bracks{13 - 6k \geq 0}
\\[5mm] = &\
\sum_{k = 0}^{4}{4 \choose k}
{16 - 6k \choose 3}\pars{-1}^{k}\bracks{k \leq {13 \over 6}} =
\sum_{k = 0}^{2}{4 \choose k}{16 - 6k \choose 3}\pars{-1}^{k}
\\[5mm] = &\
\underbrace{{4 \choose 0}{16 \choose 3}}_{\ds{560}}\ -\
\underbrace{{4 \choose 1}{10 \choose 3}}_{\ds{480}}\ +\
\underbrace{{4 \choose 2}{4 \choose 3}}_{\ds{24}}\ =\
\bbox[10px,border:2px groove navy]{\ds{\large 104}}
\end{align}


is this proof correct - If K is algebraic over F, L is algebraic over K then L is algebraic over F

Question: I solved this theorem using following. pls correct if my approach is correct or not
theorem - given field extensions K,L, F, If K is algebraic over F, L is algebraic over K then L is algebraic over F
Let $a \in L$ be algebraic over K, then $ \exists f(x) \in K[x]  :f(a) = 0 $.
let
$f(x)=a_0 +a_1x+a_2x^2+....+a_nx^n : a_i \forall i \in K$
As $a_i \in K $ and K is algebraic over F  $\implies \exists $ another  $g_i(x) : g_i(a_i)=0$;
Let $g_i(x)=b_{i0} +b_{i1}x+b_{i2}x^2+....+b_{in}x^n : b_{ij}  \in F \forall i,j$
then $f(a) = g_{0}(a_0)+g_1(a_1)a+g_2(a_2)a^2+...+g_n(a_n)a^n = 0$ where $g_i(a_i) \in F$
this means f(a) = Span[$1,a,a^2...a^n$] with coordinates from field F.
$\implies$ $f(x) = g_{0}(x)+g_1(x)x+g_2(x)x^2+...+g_n(x)x^n = 0$ where $g_i(x) =  b_{i0} +b_{i1}x+b_{i2}x^2+....+b_{in}x^n : b_{ij}  \in F \forall i,j$
Now f(x) has coefficients from F
This means $a \in L$ is algebraic over F. So L is algebraic over F
Pls correct me is i am wrong.
Comment: The proof does not work as written. You already know that $f(a)=0$, hence $f(a)$ is element of any span of whatever elements.
Comment: Here my constructed f(x) has cooeffients from F(initiallly from K, as K is algebraic over F, i each cooefficient in K is algebraic over F)
Comment: @HagenvonEitzen pls verify my constructed f(x) [i have edited now]
Answer: Sorry, I did not understand what $f(a) = g_0(a_0)+...+g_n(a_n)a^n$ is supposed to mean. To me it reads as $0 = 0$.
I would argue with dimensionality. Any finite field extension $L/K$ (i.e. $dim_K L \leq \infty$) is algebraic.
You have stated that $a\in F[a_0,...a_n]$, which is a finite field extension of $F$ proving the claim.
Edit: Writing down the minimal polynomial for $a$ with coefficients in $F$ is not so easy, I think.


Sample size calculation for truncated normal distribution

Question: So, I am new here.
I need to perform a sample size calculation for a clinical trial. The study sample will be select according to criteria of person's height. Persons within the particular height range (female, 1.6m to 1.7m) will be invited to participate in trial. We know the expected sample standard deviation from previous trial. But my concern is that sample is not from a normal distribution. Usual power/sample size calculation need the assumption of normal distribution of test statistic under $H_0$ and $H_1$, but here I believe we have truncated normal distribution. So how may I modify power.t.test, or make some other calculation in R, to accommodate this? My colleague says to just rely on central limit theory and assume normal with 1.65 mean and known standard deviation, but I believe this is wrong due to the truncation. Any advice would be appreciated.
Comment: I would use simulation to calculate the power. Anyway, given the truncated nature of your data, the use of a t-test may be questionable (I'm assuming that you're going to carry out the t-test on your truncated variable. This is what I understand from your question).
Comment: What I would use, assuming you want to compare the mean of the height in two groups, is a permutation test http://en.wikipedia.org/wiki/Resampling_(statistics)
Comment: I am fairly sure the CLT is not applicable here.
Comment: Thank you @andrea . I mention t-test because that is what I do /if/ the sample is normal distribution. I would like to make a calculation using truncation distribution, or I also think uniform distribution is good in this case because sample near the mean of the population and range is small. Can I make sample size calculation with truncated normal distribution or uniform distribution ? I prefer calculation instead of the simulation. Please to know your further comment, and also to confirm the central limit theorem is wrong to use for here.
Comment: Andrea, truncation (within the center of the distribution) actually makes the t-test *more* applicable, not less applicable: the sampling distribution of the mean will be remarkably close to normal. P Sellaz, because the distribution will likely be close to uniform (and not very skewed), the CLT gives good insight even with samples as small as $5$ or so.  Joseph, your thinking is good.
Comment: Ops, sorry for my wrong comment :)
Comment: @whuber, I asked a (vaguely) related question here recently
http://stats.stackexchange.com/questions/25561/sampling-with-inclusion-exclusion-criteria-from-known-distribution
From that I found that the distribution of the sample was very far from normal - in fact it was close to uniform. I realise you are talking about the sampling distribution of the mean, but here, don't we just want to know what is the distribution of the sample ? I'm feeling quite confused :(
Comment: @P The distribution of the *sample* does not matter; what matters is the distribution of the *sample mean.*  For example, the mean of only five iid draws from a uniform distribution--which is distinctly non-normal--will be quite close to normal for practical purposes such as using a t-test.  Unless the tails are long, what matters the most for t-tests is the skewness: nearly-symmetric samples indicate the t-test will work well.  Because 1.6 to 1.7 m is near the center of the distribution of women's heights (in developed countries), it probably is not strongly skewed: this can be checked.
Comment: @whuber thank you. So for my case I can take mean=1.65 and SD=0.0675 (which is SD of adult female height known from previous study) and use
power.t.test with delta = 0.01, sd = 0.0675, sig.level = 0.05, power = 0.9, type = "two.sample", alternative = "two.sided", or I need to find SD of difference betwen height of adult females ?
Answer: Your colleague is correct.
In the US, 1.6 to 1.7 m is near the middle of the range of adult female heights.  According to Wolfram Alpha, which summarizes NHANES 2006 data, the height distribution in this range should look close to this:

This is extremely close to uniform: its mean is 1.649 m and its standard deviation is 0.0287 m (whereas a uniform distribution in this range would have a mean of 1.650 m and SD of 0.0289 m).  Its skewness coefficient is only 0.054.
Accordingly, independent samples drawn from this distribution will have means that are close to normally distributed.  Here, for instance, is a histogram of means of 10,000 samples of just four heights drawn (independently) from this distribution:

It is only very, very slightly non-normal (a Kolmogorov-Smirnov test rejects normality at p=0.94%, which is amazingly large given there are 10,000 data points).  For the purpose of planning comparisons of mean heights among random groups of women, the normal approximation will work well.  Standard power calculations ought to give good guidance.
Comment: thank you again. So I can use 0.0287 as SD in standard power calculation ? With example of following R code to detect 0.01 difference from control to intervention group ?

power.t.test(delta = 0.01, sd = 0.0287 , sig.level = 0.05 ,
power = 0.9 , type = "two.sample", alternative = "two.sided")

thank you more


Inserir os valores de Checkbox dentro de um uma Textarea

Question: Eu estou fazendo uma página que auxilia Operadores de Monitoramento (Monitoramento de carga), e eu preciso inserir vários formulários em uma mesma página. Veja o exemplo de um deles:

//Array que guarda a ordem em que os elementos foram inseridos
var listCheckedOptions = [];

function addToList(checkObj, outputObjID)
{
//Remove do array caso o elemento já esteja inserido
if (listCheckedOptions.indexOf(checkObj.value) >= 0) {
listCheckedOptions.splice(listCheckedOptions.indexOf(checkObj.value), 1);
} else { //Adiciona caso já esteja inserido
listCheckedOptions.push(checkObj.value);
}

//        alert(listCheckedOptions); //debug para verificar os elementos inseridos
document.getElementById(outputObjID).value = ""; //Limpa o textarea
document.getElementById(outputObjID).value = listCheckedOptions.join('\r\n'); //Adiciona no textarea

return;
}

function copiarTextotxt1() {
var textoCopiado = document.getElementById("txt1");
textoCopiado.select();
document.execCommand("Copy");
alert("Texto Copiado: " + textoCopiado.value);
}

<form name="form001">

<input type="checkbox" name="cabecalho[]" id="cabecalho" value="Informamos que o motorista não está cumprindo o procedimento correto pois o mesmo:
" onClick="addToList(this, 'txt1')"> Cabeçalho

<input type="checkbox" name="opcao1[]" id="opcao1" value="(X) Não informa início de viagem."  onClick="addToList(this, 'txt1')"> Não informa início de viagem

<input type="checkbox" name="opcao2[]" id="opcao2" value="(X) Não informa paradas."  onClick="addToList(this, 'txt1')"> Não informa paradas

<input type="checkbox" name="opcao5[]" id="opcao5" value="(X) Não informa reinício de viagem."  onClick="addToList(this, 'txt1')"> Não informa reinício de viagem

<input type="checkbox" name="rodape[]" id="rodape" value="
Solicitamos que o motorista seja orientado blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá..."  onClick="addToList(this, 'txt1')"> Rodapé

</form>

<textarea rows="10" cols="100" name="txt1" id="txt1" placeholder="Instruções de uso:

1° - Selecione a opção 'Cabeçalho'.
2° - Selecione o(s) procedimento(s) incorreto(s) do motorista.
3° - Selecione a opção 'Rodapé'.
4° - Clique no botão 'Copiar Texto'.   " style="color:#000000"  readonly></textarea>

<button onClick="copiarTextotxt1()">Copiar Texto</button>

O código para inserir os valores conforme são checados, eu encontrei aqui mesmo (Adicionar elementos a um textarea por ordem de checagem de checkbox).
Mas o problema é que quando eu crio um novo formulário dentro da mesma página, os formulários entram em conflito.
Eu preciso de um código que permita pegar os dados do formulário com id=x e insira no textarea com id=y, entende?
Ou qualquer outra solução é bem vinda, desde que eu consiga inserir vários formulários na mesma página sem que entrem em conflito.
Grato desde já.
Answer: O Problema ocorre pois a função addToList modifica sempre a mesma array e a função copiarTextotxt copia sempre o texto do mesmo textarea.
Para solucionar Você tornar as funções genéricas, para que aceitem modificações em qualquer array ou textarea.
como a seguir:
A função "addToList" agora recebe um parametro adicional, a lista de opções marcadas a qual você pretende modificar(ex a listCheckedOptions).
Você deverá criar uma array para cada form que for usar, no caso criei a listCheckedOptions e listCheckedOptions2
a função "copiarTextotxt" agora tambem recebe o id do textarea o qual você pretende copiar o texto.
adicione esses novos parametros na propriedade onClick nos checkboxes  e no Botão de "Copiar texto"  de cada form e voilá.
Eis um exemplo com 2 forms:

//Array que guarda a ordem em que os elementos foram inseridos
var listCheckedOptions = [];
var listCheckedOptions2 = [];

function addToList(checkObj, outputObjID,list)
{
//Remove do array caso o elemento já esteja inserido
if (list.indexOf(checkObj.value) >= 0) {
list.splice(list.indexOf(checkObj.value), 1);
} else { //Adiciona caso já esteja inserido
list.push(checkObj.value);
}

//        alert(list); //debug para verificar os elementos inseridos
document.getElementById(outputObjID).value = ""; //Limpa o textarea
document.getElementById(outputObjID).value = list.join('\r\n'); //Adiciona no textarea

return;
}

function copiarTextotxt(id) {
var textoCopiado = document.getElementById(id);
textoCopiado.select();
document.execCommand("Copy");
alert("Texto Copiado: " + textoCopiado.value);
}

<form name="form001">

<input type="checkbox" name="cabecalho[]" id="cabecalho" value="Informamos que o motorista não está cumprindo o procedimento correto pois o mesmo:
" onClick="addToList(this, 'txt1',listCheckedOptions)"> Cabeçalho

<input type="checkbox" name="opcao1[]" id="opcao1" value="(X) Não informa início de viagem."  onClick="addToList(this, 'txt1',listCheckedOptions)"> Não informa início de viagem

<input type="checkbox" name="opcao2[]" id="opcao2" value="(X) Não informa paradas."  onClick="addToList(this, 'txt1',listCheckedOptions)"> Não informa paradas

<input type="checkbox" name="opcao5[]" id="opcao5" value="(X) Não informa reinício de viagem."  onClick="addToList(this, 'txt1',listCheckedOptions)"> Não informa reinício de viagem

<input type="checkbox" name="rodape[]" id="rodape" value="
Solicitamos que o motorista seja orientado blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá..."  onClick="addToList(this, 'txt1', listCheckedOptions)"> Rodapé

</form>

<textarea rows="10" cols="100" name="txt1" id="txt1" placeholder="Instruções de uso:

1° - Selecione a opção 'Cabeçalho'.
2° - Selecione o(s) procedimento(s) incorreto(s) do motorista.
3° - Selecione a opção 'Rodapé'.
4° - Clique no botão 'Copiar Texto'.   " style="color:#000000"  readonly></textarea>

<button onClick="copiarTextotxt('txt1')">Copiar Texto</button>
<form name="form001">

<input type="checkbox" name="cabecalho[]" id="cabecalho" value="Informamos que o motorista não está cumprindo o procedimento correto pois o mesmo:
" onClick="addToList(this, 'txt2', listCheckedOptions2)"> Cabeçalho

<input type="checkbox" name="opcao1[]" id="opcao1" value="(X) Não informa início de viagem."  onClick="addToList(this, 'txt2', listCheckedOptions2)"> Não informa início de viagem

<input type="checkbox" name="opcao2[]" id="opcao2" value="(X) Não informa paradas."  onClick="addToList(this, 'txt2', listCheckedOptions2)"> Não informa paradas

<input type="checkbox" name="opcao5[]" id="opcao5" value="(X) Não informa reinício de viagem."  onClick="addToList(this, 'txt2', listCheckedOptions2)"> Não informa reinício de viagem

<input type="checkbox" name="rodape[]" id="rodape" value="
Solicitamos que o motorista seja orientado blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá blá..."  onClick="addToList(this, 'txt2', listCheckedOptions2)"> Rodapé

</form>

<textarea rows="10" cols="100" name="txt2" id="txt2" placeholder="Instruções de uso:

1° - Selecione a opção 'Cabeçalho'.
2° - Selecione o(s) procedimento(s) incorreto(s) do motorista.
3° - Selecione a opção 'Rodapé'.
4° - Clique no botão 'Copiar Texto'.   " style="color:#000000"  readonly></textarea>

<button onClick="copiarTextotxt('txt2')">Copiar Texto</button>
Comment: Tenho conhecimento básico em criação de páginas. Fiquei horas tentando solucionar esse problema que você resolveu de forma rápida e didática.

Quero lhe agradecer imensamente, pois você resolveu um problema enorme para mim. Agora poderei pôr em prática todo o meu projeto.

Muitíssimo obrigado! Abraço.


Derivative of an autonomous system of ODEs

Question:
Consider the $N$-dimensional autonomous system of ODEs
  $$\dot{x}= f(x),$$
  where a locally unique solution $x(t)$, starting from the initial condition $x$, is denoted as $x(t)=\phi(t,x)$. Show that
$$\Big(\frac{\partial}{\partial{x}}\phi(t,x)\Big)f(x)=f(\phi(t,x))$$

Here is my proposed solution.
We are given that $\dot{x}= f(x),$ so we know that
$$\frac{dx(t)}{dt}=f(x(t))$$
If we integrate both sides with respect to $t$, we will get
$$\int_{t_0}^{t}\frac{dx(t)}{dt}dt =\int_{t_0}^{t} f(x(s)) ds$$
Therefore,
$$x(t) = x_0 + \int_{t_0}^{t} f(x(s)) ds$$
where the integration constant is chosen such that $x(t_0)=x_0$. As $x(t)=\phi(t,x)$, we have
$$\phi(t,x) = x_0 + \int_{t_0}^{t} f(x(s)) ds$$
Hence,
\begin{equation}
\begin{split}
\frac{\partial\phi}{\partial{t}}(t,x) & = 0 + \frac{\partial}{\partial{t}}\int_{t_0}^{t} f(x(s)) ds \\
 & = f(x(t))\\
 & = f(\phi(t,x))
\end{split}
\end{equation}
where the second equality follows from the fundamental theorem of calculus. Next, we are given that

$\phi$ depends on $(t,x)$.
$x$ depends on $t$.

Therefore, by the chain rule,
\begin{equation}
\begin{split}
\frac{\partial\phi}{\partial{t}}(t,x) & = \frac{\partial\phi}{\partial{x}}(t,x)\frac{dx}{dt} \\
 & = \frac{\partial\phi}{\partial{x}}(t,x)f(x)\\
 & = f(\phi(t,x))
\end{split}
\end{equation}
Thus, $\Big(\frac{\partial}{\partial{x}}\phi(t,x)\Big)f(x)=f(\phi(t,x))$.
It does seem rather strange that I concluded that
$$\frac{\partial\phi}{\partial{t}}(t,x) = \frac{\partial\phi}{\partial{x}}(t,x)\frac{dx}{dt}$$
This must be because $\frac{\partial\phi}{\partial{t}}(t,x) = \frac{\partial\phi}{\partial{x}}(t,x)\frac{dx}{dt}$ instead of $\frac{\partial\phi}{\partial{t}}(t,x) = \frac{\partial\phi}{\partial{t}}(t,x)\frac{dx}{dt}$ because of the chain rule.
Is this approach correct? Please let me know if there are any better alternatives.
Answer: If you make the flow definition more specific, such as not re-using the simple $x$ in two different meanings, you could define the flow as
$$x(t)=ϕ(t;x_0) ~~ \text{ where } ~~ x(0)=ϕ(0;x_0)=x_0.$$

You need to invoke the autonomous nature of the ODE which has as consequence that $t\mapsto ϕ_t$ is a group action/representation of the additive group $(\Bbb R,+)$. This means that $ϕ_t\circ ϕ_s=ϕ_{t+s}$, or
$$
ϕ(t+s;x_0)=ϕ(t;ϕ(s;x_0))\iff x(t+s)=ϕ(t;x(s)).
$$
From your point-of-view the closest variant might be $x(t)= ϕ(t-s;x(s))$. Anyway, to get the $x$-derivative of $ϕ$ involved you need first some kind of explicit variability in the $x$-argument of $ϕ$ which is easiest done by moving the initial point along the solution curve.
Taking, in the first variant, the derivative for $s$ at $s=0$ then gives indeed by the chain rule
$$
f(ϕ(t+s;x_0))=\frac{∂}{∂s}ϕ(t;ϕ(s;x_0))=\frac{∂ϕ}{∂x}(t;ϕ(s;x_0))\cdot f(ϕ(s;x_0))\\
\overset{s=0}\implies
f(ϕ(t;x_0))=\frac{∂ϕ}{∂x}(t;x_0)f(x_0)\\
$$


Run function when a google sheet is selected

Question: I'm looking for a method to run a function in google sheets when a sheet is selected.
Actually I found some standard trigger but I was not able to identify which could be ok to do this.
The function I want to activate is feeding a dropdown menu with file editors and I need to have it filled only when the sheet is selected.
Thanks for helping.
Answer: You can do that with the onSelectionChange() simple trigger.
See onSelectionChange for a specific Google Sheets tab.


How to make PHP input methods(get and post) safe by a simple code?

Question: This is my basic code of a login.php. It contains a basic $_POST method to get the values from form. Someone said me it is insecure. It is prone to SQl Injection. I dont want to make it complex. Please tell me how to make it more secure by simple methods.
<?php

 session_start();
 require('connection.php');

    $email=$_POST['username'];
     $password=$_POST['password'];

     //variables in query will be in single quotes.

     $query="select * from user_info where email='$email' and password = '$password' ";

     //fetching result

     if($result=$con->query($query))
     {

         $row =$result->fetch_array(MYSQLI_NUM);

         if($row>0)
         {

             //creating session variables

       $_SESSION['loggedIn']=true;

           $_SESSION['email']=$row[1];
            $_SESSION['id']=$row[0];
         header("Location:profile.php");
         }

         else
         {
             echo "flag1";

            header("Location:index.php?loginerror=invalid login");
         }

     }
     else {
        echo "Failed";
     }

?>
Comment: Start by learning to use prepared statements with bind variables
Comment: **WARNING**: Writing your own access control layer is not easy and there are many opportunities to get it severely wrong. Please, do not write your own authentication system when any modern [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with a robust [authentication system](https://laravel.com/docs/5.2/authentication) built-in. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and never store passwords as plain-text.
Comment: Although it's always an ideal to avoid making something too complex, the flip-side of this is something too simple is often completely inadequate, as is the case of the code here.
Answer: Dangers for the database: SQL-Injections
Those are the dangers when using input data from the user to operate with the database. Some input might cause the sql-syntax to break, the database will get a badly formatted statement and run onto an error (if it was unintentionally) or even execute statements it was not supposed to (sql injection).
A possibility for unintended syntax breaking would be to ask the user for his name and he inserts something like O'Connor.
Way to treat them: How can I prevent SQL injection in PHP? tldr: prepared statements are king.
(+) I would guess most ORMs or abstraction layers between your application and your database would solve this problem on their own, should inform yourself about it tho - better safe than sorry.
Dangers for the frontend: XSS attacks
A user uses your form to input some JavaScript. When you are displaying it on your website it will get parsed and executed.
Way to treat them: use htmlentities() when displaying userdata.
(+) There are libraries like htmlpurifier which allow you to only sanitize specific elements. So if you want to let your users use HTML for a blogpost or whatever, you can a library like this which will allow certain elements and defuse the dangerous stuff.
Dangers for the filesystem: shell-injections (?)
When you are for some reason using user input to do something on your filesystem (creating a directory with the same name as the username or whatever..) someone could do the same as in sql - break your syntax and inject some commands.
Way to treat them: escapeshellcmd + Don't use user input for something like directory or filenames on your server! Put the names of the user into the database, use the id or a hash or something you generated as the filename.
Cross-Site-Request-Forgery:
Doesn't directly involve the data given to you, but I am adding it because it is something you should know about: Understanding CSRF
Remember: Treat the data based on the context in which you are using it!
There are different places for attacks and each one uses other weaknesses. So there is not the one solution to fix all the problems.
You just have to consider the context in which you are handling the data - are you saving it or displaying it.
When displaying it you want to take care of the JavaScript that might be hidden in the data so you want to escape the charakters which are special in html.
When saving data you worry only about the charakters which might break the syntax of your sql. Your database knows best which charakters to escape and how to treat which data, so just use the escaping and quoting functions provided by your database-api OR BETTER: Prepared Statements (just use them always when interacting with the database + userdata) as they work differently then normal queries and you don't have to think about escaping and quoting.
Comment: Worth noting that most frameworks have ways of mitigating all of this out of the box, so doing it the hard way and shunning those also comes with considerable risk. I'd also push the idea of prepared statements before all else, it's the most reliable, safest, cleanest way to add data to your query.
Answer: I would use PDO's. A very basic example;
<?php

 session_start();
 require('connection.php');

 $sError    = "";
 $sEmail    = "";
 $sPassword = "";

if(isset($_POST['Login'])){

    if(isset($_POST['username'])) $sEmail    = $_POST['username'];
    if(isset($_POST['password'])) $sPassword = $_POST['password'];

    if($sPassword != '' && $sEmail == ''){

        // create an instance of the connection
        $conn   = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );

        // prepare the sql
        $sSQL = "SELECT Email, Id from user_info where email=:email and password = :password ";
        $st   = $conn->prepare( $sSQL );

        // bind the input vars
        $st->bindValue(":email", $sEmail, PDO::PARAM_STR);
        $st->bindValue(":password", $sPassword, PDO::PARAM_STR);
        $st->execute();

        // if data is returned from calling fetch
        if( $row = $st->fetch() ){
            $_SESSION['loggedIn']   = true;
            $_SESSION['email']      = $row['Email'];
            $_SESSION['id']         = $row['Id'];

            header("Location:profile.php");
            exit;

        }

    }else{

        // must have empty input add to errror string
        $sError .= "[EmptyInput]";

    }

    // user hasnt been logged in set error
    $sError .= "[InvalidLogin]";

}

// detect anthign in error stirng
if($sError != ""){

    // do something

}
?>

Havent tested it but should work.
I would also salt and encrypt your passwords.
Additionally I would generate a code to use to identify the user publicly.


API request is taking too long

Question: I'm trying to make an API request , save some values to my database then render an ejs file using the results stored in my database. The problem is the request is taking too long. So when i render the page my database still have nothing. How can i fix this? should i add a delay or something? I'm using NodeJs request module
        request(url, function(error, response, body){
            if(!error&&response.statusCode==200){
               var parsedData = JSON.parse(body);
            }
            parsedData.forEach(function(element){
                Job.create({
                   //here I will save data to my DB
                }, function(err, newjob){
                    if(err){
                        console.log(err);
                    } else {
                        console.log(newjob);
                    }
                });
            });
        });

    Job.find({"location": { $regex: location, $options: 'i'}, "description": { $regex: description, $options: 'i'} }, function(err, jobs){
        if(err){
            console.log(err);
        } else {
            res.render("jobs", {jobs:jobs});
        }
    });

Answer: The API request may take some time ,
but you are not waiting for the insert to finish .
You can do something like this, with no extra packages:
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
      var parsedData = JSON.parse(body);
  }

  let cb_counter = 0;
  parsedData.forEach(function (element) {
      Job.create({
          //here I will save data to my DB
      }, function (err, newjob) {
          if (err) {
              console.log(err);
          } else {
              // another job inserted into db
              cb_counter++;
              // if we files done:
              if (cb_counter == parsedData.length){
                // now are are ready to find and render jobs
                // make sure res.render is in the scope , or pass it
                // to the function
                findJobs(res);
              }
          }
      });
  });
});

function findJobs(res){
   Job.find({ "location": { $regex: location, $options: 'i' }, "description": { $regex: description, $options: 'i' } }, function (err, jobs) {
    if (err) {
        console.log(err);
    } else {
        res.render("jobs", { jobs: jobs });
    }
  });
}

But I would suggest you use promises instead of callback,
it will make your code much readable.
try something like this:
and please verify with your library that you use if support promises
(most likely it does !)
request(url, function (error, response, body) {
   if (!error && response.statusCode == 200) {
       var parsedData = JSON.parse(body);
   }

   let promises = [];
   parsedData.forEach(function (element) {
       promises.push(Job.create({
           //your data to db
       }))
   });

   Promise
    .all(promises)
    .then(() => findJobs(res))
    .catch(err => {
       // handle error
    })
});

function findJobs(){
    Job.find({
        "location": { $regex: location, $options: 'i' },
        "description": { $regex: description, $options: 'i' }
    }).then(jobs => {
        // usualy you should validate that jobs is not an empty array
        res.render("jobs", { jobs });
    }).catch(err => {
        // hadle error finding data
    });
}

Please consider how more readable the second example is .
You can read more about promises every where out there.
I would suggest start here
Have fun :)

API request is taking too long


JavaScript - For loop vs forEach

Question: can someone explain how these two pieces of code achieve the exact same thing* or explain why they may appear to but do not?
  for (i = 0; i < xx.length; i++) {
    xx[i].classList.remove(...y);
  }

  xx.forEach(x => {
    x.classList.remove(...y);
  });

Comment: The second is primarily syntactic sugar afaik, and may have a very slight performance difference.
Comment: [`for` loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) explained, [`Array.prototype.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) explained
Comment: `.forEach()` only works with arrays. It will be slightly slower than the counting loop, but well worth the trade off in that `.forEach()` removes the need to manage indexes.
Comment: I think your first one might be better as `for (const i of xx) { i.classList.remove(...y); }`
Answer: forEach is a method on the Array prototype. It iterates through each element of an array and passes it to a callback function.
So basically, forEach is a shorthand method for the use-case "pass each element of an array to a function". Here is a common example where I think Array.forEach is quite useful, compared to a for loop:
// shortcut for document.querySelectorAll
function $$(expr, con) {
    return Array.prototype.slice.call((con || document).querySelectorAll(expr));
}

// hide an element
function hide(el) {
    el.style.display = 'none';
}

// hide all divs via forEach
$$('div').forEach(hide);

// hide all divs via for
for (var divs = $$('div'), i = 0; i < divs.length; i++) {
    hide(divs[i])
}

As you can see, the readability of the forEach statement is improved compared to a for loop.
On the other hand, a for statement is more flexible: it does not necessarily involve an array. The performance of a normal for loop is slightly better, because there is no function call for each element involved. Despite of this, it is recommended to avoid for loops when it can be written as a forEach statement.
Answer: Careful, if you declare "i" without "var" keyword it will be global.
You can check what forEach can do here:
forEach MDN
Comment: Very kind, but can't add comment under 50 rep. :)
Comment: That's not a reason to post a bad answer and it won't help you to get to 50 rep. Post good answers that will boost your rep.
Comment: Thanks but In my code I declare 'i' just above the for loop using 'let'.

JavaScript - For loop vs forEach


Performing operations on chunks of rows in SQL Server where the identifying column is of type nvarchar

Question: I'm looking to perform some operations on potentially large data sets in SQL Server 2014. I'd like to do it in chunks (say, ~1000 rows at a time) but the hitch here is that the identity column of the table is an nvarchar type (storing a UUID).
Breaking data into chunks where the IDs are ints is pretty trivial, but I'm left scratching my head on this one. Is there a clean way of doing this?
Answer: Just add an INT column to your SELECT like this:
;WITH CTE AS
(
    SELECT
        (your-usual-list-of-columns),
        RowNum = ROW_NUMBER() OVER (ORDER BY -some-column-here-)
    FROM
        dbo.YourTable
)
SELECT
    (your-usual-list-of-columns)
FROM
    CTE
WHERE
    RowNum BETWEEN 1001 AND 1999    --- or whatever batch you want to process


Find Centroid of Plane Figure and Centre of Gravity

Question:
A plane figure is enclosed by the parabola $y^2 = 4x$ and the line $y=2x$. Determine (a) the position of the centroid of the figure, and (b) the centre of gravity of the solid formed when the plane figure rotates completely about the x-axis.

So the figure i have to consider is the one enclosed here (inside the loop, that looks like an airfoil) :

from $x=0$ to $x=1$ ( when i find the points of intersection).
This is from a book, and it gives the Centroid $(0.4,1)$ and Center of Mass $(0.5,0)$.
I only managed to find the x ordinate of the Centroid. Here's what i have done.

Centroid$(\bar{x},\bar{y})$ is given by:
$$\bar{x}=\frac{1}{A}\int_{0}^{1} xy\ dx, \bar{y}=\frac{1}{2A}\int_{0}^{1} y^2\ dx $$

Where A is the area of the figure i want, given by: $ A=\int_{0}^{1} y\ dx $
To find the $y$ i figure that it's the $y$ of the curve minus the $y$ of the line from $0$ to $1$. So
$$y=\sqrt{2}\ x - 2x$$
So with all these i calculate $$A=\frac{1}{3},\ \bar{x} = 0.4,\ \bar{y}= 0.2$$

Center of Gravity $(\bar{x},\bar{y})$ is given by:

$$\bar{x}=\frac{1}{V} \int_{0}^{1} xy^2 dx$$
where $V$ $=\int_{0}^{1}y^2 dx$ is the volume generated.
and $\bar{y}=0$ here because the axis of rotation is the x-axis.
EDIT: The following line is wrong (i don't know how to strikethrough it)
So i calculate: $y^2= 4x+4x^2-8x^{3/2} \ , V=\frac{2}{15} $ and $\bar{x}=0.357$
So apparently the only thing i get right is the $\bar{x}$ ordinate of the centroid. What am i doing wrong? Please help. Thanks in advance.
Answer: I made some adjustments to the equations i used. There were mistakes. I have figured out the answer. My main mistake was that i took $y^2$ as the difference of the values of the two functions squared $(y_1-y_2)^2$ and not as the difference of the squares of two functions $ y_1^2-y_2^2$ (they are two separate functions acting on their own to derive the final result, it's not one function). I didn't have proper intuition about what i needed to do. This video also helped me (it has a similar example).
One other mistake is that i also divided by $π$ when the definitions already had that sorted out. That was a careless mistake. I edited this in the question.
So the area $A=\frac{1}{3}$, the volume is $V= \frac{2}{3} $(it's $V/π$ to be precise, because the $π$'s are cancelled out in the definition of the center of gravity). And as i said wherever we see $y^2$ we consider the superposition of our functions, i.e. the combined effect they have on the final result. In my case it is $y_1 - y_2$ (where $y_1=2\sqrt{x}\ ,\ y_2=2x $ ). I hope this is clear.
Considering all these i find the correct answers mentioned in the question, with not much trouble.


Rspec expect a yield

Question: I have a hash in Rails and one of the values is a yield.
{
  key1: 'foo',
  key2: lambda { |p| root_path(p) },
}

I am not entirely sure how I can expect key2 to receive this yield
I looked in to yield_control but I am not sure that is what I need.
I want to assert that key2 receives a yield and I also want to assert what that yield returns (root_path(p))
Comment: Then secend expect `expect(hash[:key2]["lol"]).to eq root_path("lol")`
Comment: Just for the records on @BroiSatse (I also believe is a good answer): An equivalent, and perhaps clearer spell is just `expect(hash[:key2].call("lol")).to eq root_path("lol")`. Longer, but shows explicitly that the test deals with a proc.
Comment: Would `expect(hash[:key2].arity).to eq 1` be ok?
Comment: I would need to know the exact route in the yield since there are more like this with different routes
Comment: Perfect, thanks. Add it as an answer and I can accept it
Answer: You want to be sure that key2 contains a lambda and you want to test what the lambda returns?
example of a test for a lambda
let(:my_hash)  = {
                   {
                     key1: 'foo',
                     key2: lambda { |p| root_path(p) }
                   }
                 }

expect(my_hash[:key2].try(:lambda?)).to be true

to test for result
expect(my_hash[:key2].call("foo")) to eq root_path("foo")

Rspec expect a yield


Is it possible to configure a Cisco router to serve as a Teredo relay?

Question: The router in question is a Cisco 871, show version as follows:
<code>Cisco IOS Software, C870 Software (C870-ADVIPSERVICESK9-M), Version 12.4(24)T8,
RELEASE SOFTWARE (fc1)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2012 by Cisco Systems, Inc.
Compiled Sun 09-Sep-12 09:09 by prod_rel_team
</code>
If so, what would a sample configuration for this scenario look like?  And would there be any particular problems in running it on a router which is already providing IPv6 to its "internal" network via a 6ot4 tunnel?
Comment: Don't bother with Teredo. It's a very unreliable technology that is likely to go away in the future in favour of native IPv6 connectivity or more stable transition technology like SixXS or Hurricane Electric tunnels.
Comment: @SanderSteffann Unfortunately, for now I don't have anything else to use (that I'm aware of) to connect back from a mobile device which can be behind arbitrary not-mine-to-control not-ICMPable-or-passing-protocol-41 NATs.  I'd use an HE tunnel if I could. :(
Answer: Simple answer: No.
Teredo is common on Windows PC as a work-around for the lack of a local ipv6 router.
ftp://ftp.rfc-editor.org/in-notes/rfc4380.txt details the protocol and operation.
Cisco has support for 6to4 auto-tunnels and 6rd, but alas no Teredo support.
More client info at http://en.wikipedia.org/wiki/Teredo_tunneling#Implementations
Comment: That applies as a relay, as well as as a client?  The router has native IPv6 as well as IPv4 - I just want it to act as a relay for a remote Teredo client.


PDO Exception Error - How to resolve this?

Question: After integrating Google Custom search in Drupal 7, I am getting this error page. What should I do to resolve this error?
Answer: Could be a MySQL configuration issue - see http://dev.mysql.com/doc/refman/5.5/en/too-many-connections.html
Or, quoting after http://drupal.org/node/930876#comment-4519490:

If MySQL connections are not closed
  properly, then you might have an error
  within the code somewhere, that leads
  the script to end prematurely.
In standard cases, connections are
  properly closed.
Look at the detailed error log of your
  server, or activate on page error
  reporting if you're on a develpment
  site. You might find something useful,
  such as a forgotten dsm() somewhere
  with the devel module not being
  activated.
The error might not be displayed and
  leads the site to look as usual, but
  the PHP process is not ended properly,
  leaving MySQL connections opened.

Start with checking your error logs and try to find out why this could be happening there.
Answer: This should also help:
DEADLOCK
Reading/surfing I found that InnoDB tables can have this problem. One of the causes is the very high traffic and loss of connections (but deadlock is even something different). Combined you may easily reach the max_users_connection limit and this will render your site useless.
Some Hints:

use cache, if you can
use throttle
use bad behaviour module (as this should shield you against spammers)
set interactive_timeout so that your connections expire quickly

I have made these changes to the database.mysql.inc - to the function mysql_connect
the old version:
$connection = mysql_connect($url['host'], $url['user'], $url['pass'], TRUE) or die(mysql_error());

the new version:
 $connection = mysql_connect($url['host'], $url['user'], $url['pass'], TRUE, MYSQL_CLIENT_INTERACTIVE) or die(mysql_error());
 mysql_query("SET SESSION interactive_timeout=120", $connection);

To get the timeout run phpinfo() and watch for the connection timeout inside your MySQL, and also timeout of your apache process (or IIS if you use IIS).
Basically, after the timeout, your script will be cut off, BUT the opened connection will be there eating out of your max_users_connections. If you set the interactive_timeout limit, it will be closed automatically (note: mysql has a global wait_timeout limit, but as a default there is often 28800 = 8 hours, the connection will expire in 8 hours!)
Answer: Try to edit your php.ini/php configuration in your cpanel.  I moved up to php5.5 from 5.4 and this problem was gone.


Covariance matrix for the random effect in mixed effects model

Question:
According to this post, matrix Omega and sigma are in the results of lmer when we fitting the mixed effect model. And here is my result.
Random effects:
Groups   Name Variance  Std.Dev. Corr
subject  X21  8.558e+00 2.925380
         X22  2.117e-03 0.046011 -1.00
         X23  2.532e-05 0.005032  1.00 -1.00
Residual      1.453e+00 1.205402
Number of obs: 100, groups:  subject, 20

Since my Omega is a 3x3 diagonal matrix, so the three numbers in the Variance should be the elements in the diagonal of Omega and the number on the Residual&Variance i.e. 1.453 should be my sigma^2.
Here is another post also confirms this.
However, the Omega I used to generate y is quite different from it. Here is my true Omega:
> Omega
          [,1] [,2] [,3]
[1,] 0.6181442    0    0
[2,] 0.0000000    0    0
[3,] 0.0000000    0    0

And my true sigma=1. I do not believe the difference is due to the estimated error since these two numbers differ so much.
Then According to this post, the accepted answer gave another way to get the covariance matrix Omega as
M1 <- lmer(ym ~ 0+XC1 + (0+X2 | subject))
rr <- ranef(M1,condVar=TRUE)

pv <- attr(rr[[1]],"postVar")
str(pv)

But when I use this method to get my Omega, I get
> pv[,,1]
              [,1]          [,2]          [,3]
[1,]  0.2913922395 -4.588735e-03  5.017337e-04
[2,] -0.0045887347  7.523883e-05 -8.101042e-06
[3,]  0.0005017337 -8.101042e-06  8.773362e-07

So, pv is an array with dimension 3x3x20, i.e. each pv[,,i] is the same 3x3 matrix with elements shows above.
If I take any pv[,,i] as my Omega, this will not the same as the Residuals in my lmer results, and none of these close to my true Omega.
Any help with this will be greatly appreciated!
Edit: here is my code to generate data and do the lmer fitting.
N=20          #number of subject
n=5           #number of observations per subject

sigma2 =1

#equally space point not include the start point
time <- function(from, to, length.out) {
    length.out <- length.out + 1
    result <- seq(from, to, length.out = length.out)
    result <- result[-1]
    return(result)
}

subject = matrix(0,nrow=N*n,ncol=1)
for(i in 1:N){
    for(j in (n*(i-1)+1):(n*i)){
        subject[j]=i
    }
}

X = array(0, dim = c(N, n, 3))#each X[i,,] is a nx3 matrix
for (i in 1:N){
    for (j in 1:n){
    X[i,j,] <-c(1,time(0,10,n)[j],(time(0,10,n)[j])^2)
    }
}

y = array(0, dim = c(N, n, 1))

Omega <- matrix(0,nrow=3,ncol=3)
Omega[1,1] = runif(1,0.01,1.01)#only omega1^2 is not equal to 0

beta <-rep(0,5)
beta[1]= rnorm(1,mean=0.01,sd=1) #mu0
beta[2]= rnorm(1,mean=0.005,sd=1) #mu1
beta[3]= rnorm(1,mean=0.0025,sd=1) #mu2

C1 = array(0, dim = c(N, 3, 5))
for(i in 1:N){
    C1[i,1,1]=C1[i,2,2]=C1[i,3,3]=1
}

muy = array(0, dim = c(N, n, 1))     #store the expextation of each yi
Cov = array(0, dim = c(N, n, n))     #store the covariance matrix of y

for (i in 1:N){
    muy[i,,] <- X[i,,]%*%C1[i,,]%*%beta
    Cov[i,,] <- X[i,,]%*%Omega%*%t(X[i,,])+ sigma2*diag(n)
    y[i,,] <- mvrnorm(n = 1, muy[i,,], Cov[i,,])
}

ym <- as.vector(y[,,1])

#change X into X2, which is in a matrix format, easy for compitation later
X2 <- rbind(X[1,,],X[2,,])
for(i in 2:(N-1)){
    X2 = rbind(X2,X[i+1,,])
}

XC1=matrix(0,nrow=N*n,ncol=5)
for(i in 1:N){
XC1[(n*(i-1)+1):(i*n),]=X[i,,]%*%C1[i,,]
}

M1<-lmer(ym ~ 0+XC1+(0+X2|subject))

Edit: According to the posted answer, I know why the VarCorr() and ranef() gave different solutions. But still, I am confused since VarCorr() should be the estimate of my $\Omega$ then, but they are quite different.
Answer: What you get from ranef() is not an estimate of the covariance matrix $\Omega$. For a more detailed explanation of the differences, check this post.
Moreover, you seem to be fitting a rather overly complicated model for the data you have simulated. Note that the optimization algorithms under the postulated model work under the premise that the covariance matrix $\Omega$ needs to be positive definite, meaning that the variances need to be positive. When the variance is actually zero, the shape of the log-likelihood can be rather unusual near leading to problems during the optimization. In your case, you have two variances that are zero making it a hard problem.
Finally, for another way to simulate from a mixed model check the code provided in this example - you will need to change the last line and use rnorm() instead of rbinom(), and specify as sd the $\sigma$ in your formulation.
Comment: Hi, the $\Omega$ is a `3x3` diagonal matrix. And we have different cases in which the elements in the diagonal will be specified as null or not. So I can't change the structure of $\Omega$. But I use `X[i,,]%*%Omega%*%t(X[i,,])+diag(n)` as the variance matrix of `y[i,,]` when we generating the data `y`, in which the variance matrix do not have 0 in the diagonal any more. So is there a way to deal with this situations?
Comment: According to your link, I know why the `VarCorr()` and `ranef()` gave different solutions. But still, I am confused since `VarCorr()` should be the estimate of my $\Omega$ then, but they are quite different.
Answer:
I am confused since VarCorr() should be the estimate of my $\Omega$ then, but they are quite different.

There seems to be a typo at ym.
    ym <- as.vector(y[,,1])

    # compared with:
    # ym <- as.vector(t(y[,,1]))

In addition, if the Omega is zeros everywhere except at Omega[1,1], only the first column of X has random effect. As shown in the equivalent simulation below, only alpha[1] is non-zero. Thus it is unlikely to see meaningful random effects from columns 2 and 3 of X.
for (i in 1:N){
    muy[i,,] <- X[i,,]%*%C1[i,,]%*%beta
    Cov[i,,] <- X[i,,]%*%Omega%*%t(X[i,,])+ sigma2*diag(n)
    # y[i,,] <- mvrnorm(n = 1, muy[i,,], Cov[i,,])

    # is equivalent to:
    alpha = mvrnorm(n = 1, rep(0,n), Omega)
    y[i,,] <- muy[i,,] +
              rnorm(n,sd=sqrt(sigma2)) +
              alpha[1] * X[i,,1] +
              alpha[2] * X[i,,2] +
              alpha[3] * X[i,,3]
}


I need help understanding a complex (or maybe compound) time signature

Question: I composed this song a few years ago originally using a tracker (an old-school, very freeform compositional workflow), and have been recently trying to transcribe it into a more modern DAW (Ableton Live). I'm struggling to find the "right" way of transcribing it, and in general have a rough time understanding more unusual timings and meters.
Listen to this stripped-down loop:
http://soundcloud.com/cinasaffary/dirty-water-simple-loop/s-zREjC
For reference, the full song is available here.
The way I count each loop is
1-2-3 4-5-6 | 1-2-3 4-5-6 | 1-2-3 4-5-6 | 1-2 | 1-2-3 4-5-6 | 1-2-3 4-5-6

Does that mean this is 32/8? I'm not sure it's correct to count the entire loop as one long measure and that time signature sounds ridiculous. Seems that the more likely answer is that it's a compound 6/8 8/8 signature, but that's only a guess. Plus I don't know how I'd go about setting that up in my DAW sanely. Also, I don't really know where the measure divisions would go.
Can anybody shed some light on this? The good news is I'm pretty sure the chorus of the song is considered straight 6/8.
Comment: If you make the soundcloud loop track "public", it will show directly here in the question body. See how to do it [here](http://meta.music.stackexchange.com/a/246/249).
Answer: I believe there are two things you are looking for here.  The analysis of the meter and how to translate that to a DAW, such as Ableton Live.  I think these could be two different answers.
I could analyze this fragment a few ways depending on what or whom it is for.  With the phrasing I hear, I would say the analysis that best describes the phrasing would be: 12/8 | 8/8 | 6/8 | 6/8 |  This is because I hear the first 4 beats as one measure and the last four beats feel broken into two pieces, where the first two beats are the echo of the bar of 8/8 and the second are a sort of turnaround.
If I were writing this out for players to read, I would have the bar of 12/8 separated into two bars of 6/8 to keep the changing of time signatures to a minimum, making it easier to read.  This would be: 6/8 | 6/8 | 8/8 | 6/8 | 6/8 |
For the DAW, the easiest way is going to be to keep it in 4/4.  The tempo in the loop you posted is aprox. 1/8 = 290, which means you would want to set the tempo at 1/4 = 145.  Your pattern neatly lines up with 8 bars of 4/4, so your loop will fit neatly in the grid and you won't have to map out the changes.  The biggest problem with this approach is that the metronome would not properly represent the actual beats.
I know that when I am programming/composing in a DAW with strange time signatures, I like to see everything how I think of it.  I also prefer to have a metronome when I record over programmed loops.  So I personally would map out the meter changes because it helps me see and hear exactly where everything is.  Even though I analyze the first four beats as one bar, I would probably map it in 6/8 because it is so closely related, I can think of it either way.  I use Logic Pro and it is relatively easy to map and you can copy sets of changes.  I'm not very familiar with Ableton Live but they certainly have a good reputation and I would be surprised if it were not versatile enough to copy time signatures.
Answer: You are right that this is somewhat a complex time signature.
The first measure sounds like some sort of prelude (it is basically the last 4 beats in the repeating pattern that follows). The time signature for this measure is 4/4:
1 2 3 4

The pattern that follows is one measure with time signature 3/4, followed by two 4/4 measures:
1 2 3 | 1 2 3 4 | 1 2 3 4

This pattern is repeated throughout the song.
The point is that the time signature does not have to be the same for the entire song, and this is an example of that. It would be possible to say it is 11/4 that has 4 beats as prelude before the first measure begins. But this is a quite slow beat, and it would be more natural to split it up. You might see other options to split it up, but that is up to you.
At first, I was thinking to split up the repeating pattern like this:
1 2 3 | 1 2 3 4 5 | 1 2 3

But then the first 4 beats in the prelude would not fit in. This is not a big problem. It is valid to say that the prelude was just the 5th beat from the measure in the middle, and then 1 2 3 before the full pattern starts.
In this case, if you follow the "rules" you should end the piece with a 5/4 measure that has only the first 4 beats in it.
This is because the 5th beat is in the beginning of the prelude.
How you choose to split it up is much a matter of taste, and where you want to emphasize the first beat.
Comment: @awe - Yes, I was aware - I disagree with the nomenclature of "prelude" as that refers to entirely different type of music. "Introduction" may be more accurate here.  One of the fun things about discussing and interpreting music is learning how everyone perceives what's going on, and there are of course, multiple ways of correctly notating the same heard sounds.
Comment: You could also say that the first 4 beats is the start of the pattern, so that you have `1 2 3 4 | 1 2 3 | 1 2 3 4` as the repeating pattern, but I feel that the musical phrase starts most naturally with the 3/4 measure.
Comment: I disagree here actually, after counting through the sample several different ways, I feel that 4/4 | 3/4 | 4/4 is the clearest representation of the meter.
Comment: I'm not so sure that 3/4 is correct for the middle measure. I think it's actually 8/8 because the last beat of the 3 is simple while the first two are complex.
Comment: I definitely would not analyze this using a 4 as the denominator for a few reasons.  1. The proposed bar of 3/4 is two eighth notes shy of the full bar.  2. All of the subdivisions played are in sets of three and I can't imagine why you would rather write endless triplets.  3. If you call it 4/4, then properly identifying the second bar would require a change of tempo.
Comment: @jjmusicnotes: You are aware that I see the first 4 beats as not the first measure in the pattern? If you count from the beginning, I see it as `1 2 3 4 | 1 2 3 | 1 2 3 4 | 1 2 3 4 `, where `1 2 3 | 1 2 3 4 | 1 2 3 4 ` is repeated after that.
Comment: @Basstickler - nice point, I redact my initial interpretation.  I'm not a fan of large compound signatures, so I definitely agree with breaking the 12/8 up.  I would probably also break the 8/8 up into 6+2/8. For some reason I subdivided the rhythms into 16th notes the first time 'round...guess I need to wake up first!
Comment: @jjmusicnotes - I would say that in the bar of 8/8 (as I interpret it) would not be well served by making a separate bar of 2/8.  To me, that would imply that the 2/8 is distinctly separate from the 6/8 before it.  In this case it is actually a rest or sustained notes, which to me, is directly connected to the beats directly preceding it.  I just can't think of a way that adding the bar of 2/8 to the equation is going to better explain what is happening.  It does spell out the beats but the most common form of 8/8 is 3+3+2, so I think it spells it out.
Comment: @Basstickler - all good points; to which I agree. However, I wrote 6+2/8 not *6/8+2/8* which as you pointed out, is a subtle difference.  Writing 6+2/8 illustrates how the measure should be divided / counted while keeping it nice and neatly together. (Again, this is just thinking as if the music were being written out.)
Comment: @jjmusicnotes - I see, like an additive meter.
Answer: It is not difficult. In simple time you have a certain number of regular beats. You can have beats of minims. You can have beats of crotchets. You can have beats of quavers. When a time signature becomes compound its beats become dotted notes.
So for instance 3/4 time is simple triple time. 9/8 is compound triple time. You went from three beats of crotchets to three beats of dotted crotchets. 9/8's grouping would be three groups of dotted crotchets
2/4 time is simple duple time. 6/8 is compound duple time. You have gone from two beats of crotchets to two beats of dotted crotchets. 6/8 time's grouping would be two groups of dotted crotchets.
4/4 time you have four beats of crotchets 12/8 time you have four groups of dotted crotchets.
Let us now try groups of minims.
2/2 is simple duple time with groups of minims. Compound time would be 6/4 time where you would have 2 groups of dotted minims worth of notes.
3/2 is simple triple time with groups of minims. 9/4 is compound triple time with groups of dotted minims.
4/2 is simple quadruple time with groups of minim. Its compound signature would 12/4 (Very Rare)
And lastly we have the groups of quavers.
2/8 is simple duple time with groups of quavers. Its compound time signature would be 6/16
3/8 is simple triple time with groups of quavers. Its compound time signature would 9/16
4/8 is simple quadruple time with groups of quavers. Its compound time signature would 12/16
Hope that helps.


SQl para ORM(sqlalchemy)

Question: Como transformar essa query de sql para orm?
<code>select cod_quest
  from questoes a
  where a.cod_quest not in (
     select cod_questao
       from respostascurso b
       where a.cod_quest is null = b.cod_questao
    and b.grr="grr3123"
  )
  order by(a.num_quest);
</code>
É um questionário, eu preciso acessar a tabela de respostas do usuário e ver qual questão ele ainda não respondeu em order crescente pegar a proxima questão.
Answer: resolvido, caso alguém precise segue a resposta.
db.session.query(Questoes.cod_quest).filter(~Questoes.cod_quest.in_(db.session.query(RespostasCurso.cod_questao).filter(Questoes.cod_quest.is_(None)==RespostasCurso.cod_questao, RespostasCurso.grr=="GR1234"))).all()

SQl para ORM(sqlalchemy)


How to stop divs moving under each other when zooming out

Question: I have the following HTML code to create a vertical navigation bar:

Hello

Hello

Hello

Hello

Hello

Hello

and the CSS:
body {
  font-family: Helvetica;
  color: #FFF;
  width: 960px;
  margin: auto;
  background-color: #CCC;
}

#nav {
  width: 239px;
  padding-top: 40px;
  float: left;
}
#nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: block;
}

#nav ul li a {
  border: 1px solid #000;
  border-bottom: none;
  border-right: none;
  padding: 10px 0 10px 20px;
  text-decoration: none;
  background: #1A6680;
  color: #FFF;
  display: block;
}

#stream {
  text-align: center;
  border: 1px solid #000;
  width: 719px;
  height: 550px;
  background: #007A5C;
  float: right;
}

While this normally works fine, if you zoom out, the #nav goes on top of the #stream, instead of side by side. How do I make sure that the #nav and #stream divs remain side by side and touching?
Answer: When "zooming out" in a browser, the browser attempts to compensate for border. You've set your border to 1px, but at 50% zoom, the border is actually rendered with a width of 2 pixels.
The reason for this is that when the browser reduces the size of the elements it is displaying it attempts to do this to the border. But as you've only specified a 1-pixel width border it will first calculate a width of less than 1. As you cannot show a portion of a pixel the browser attempts to compensate.
However it over-compensates and multiplies the original value with the scale of the zoom. So at 50%, the border is calculated at

1 * 0.5

This returns 1.5 and is scaled up to 2.
So, there will be several resolutions to this problem.

You can either adjust the width of your boxes and borders to
compensate for any modifications the browser will make.
You can use percentage widths to make the page responsive as suggested by Fahad.
Or you can use CSS3's box-sizing attribute (if you're not too concerned with fallback to older browsers);
#stream {
    text-align: center;
    border: 1px solid #000;
   -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    width: 719px;
    height: 550px;
    background: #007A5C;
    float: right;
}

Taken from Sunny's Answer

I'm sure there will be other resolutions to this, but I believe these to be your best three options.


How is a part consisting of 4 repeating chords called?

Question: E.g. in the INXS number Near Tear Us Apart there are 4 measures (in the intro/verse) that are repeated continuously (Am7 Fadd9 Dm F). However, in many songs verses/choruses are build up of a repeat of 4 measures.
How is such part of 4 measures called? (probably also could be more, or less for the definition point of view).
I guess it's not a 'riff' as there is not really a melody or typical notes inside, maybe a phrase?
(Actually I'm looking for the Dutch term, but I guess if I can find the English term I can translate/find it).
Answer: I have usually seen this referred to as a four-chord loop.
If you are interested in the phenomenon, the youtube channel 12tone has a lot of videos that deal with the theory and application of these loops.
Comment: @MichelKeijzers It's not really the right term here, but there is in fact a fancy Italian classical-music name for a simple musical element that's repeated throughout the entire work: [ostinato](https://en.wikipedia.org/wiki/Ostinato). (IMO a 4-bar chord progression is a bit too complex to use the word "ostinato"; it would typically be just a simple rhythm pattern or melodic riff.)
Comment: As far as I know, it's not a thing in classical music, so there's no need for a fancy Italian name for it :-) Now that I think of it, I believe jazz musiciancs call repeated chord progressions "vamps", so it would be a "four-chord vamp" (although the term seems to refer not just to chords, but also rhythmic figures etc. - similar to a "riff", I guess).
Comment: Seems to me that *ostinato* (related to the Dutch word *obstinaat*), or *vamp* are both correct.  The English-language Wikipedia page [Ostinato](https://en.wikipedia.org/wiki/Ostinato) includes "Vamp" as a section.
Comment: Thanks, I would expect there would be a dedicated term for it. I make music for about 30 years, but also don't know it, although I never had an official musical training.
Comment: @AndyBonner Thanks for the clarification ... it's not fully repeated through the entire song, but too several parts of it (intro, verse, not chorus).  But I can live with this word, thanks.
Comment: @Theodore - ostinato, to me, seems like a sustained rhythmic pattern 1 or 2 bars long, repeated. 'Vamp till ready' reminds me of the long intros we play, maybe using 4 bars, till the singer can remember the words...


Handling redundant factor variable levels for linear regressions in R

Question: Say I have two factor variables, X and Y, each with 3 levels. However, X==3 if and only if Y==3, while such a connection doesn't hold for X,Y==1,2. In this case, while X and Y are not redundant, my design matrix, when expanded, will contain the same column twice (0's everywhere, except 1's where X==Y==3). This is not good.
Theoretically, there is no problem: Just remove one of the redundant columns. However, I don't want to go ahead and re-implement the entire linear regression just for this case. Is there some technical or theoretical trick that will still allow me to use R's lm?
Answer: I believe lm already handles perfectly collinear variables and you don't have to worry about this.
#example
DF <- expand.grid(x=factor(1:2, levels=1:3), y=factor(1:2, levels=1:3))
DF <- rbind(DF, data.frame(x=factor(3, levels=1:3),y=factor(3, levels=1:3)))
DF <- rbind(DF, DF, DF)
set.seed(42)
DF$r <- rnorm(15)

lm(r~x+y, data=DF)

# Coefficients:
#   (Intercept)           x2           x3           y2           y3
#        0.6208       0.6928      -0.5514      -0.7585           NA

#design matrix
dm <- model.matrix(r~x+y,DF)
#remove duplicated column
dm <- dm[,!duplicated(t(dm))]

#fit linear model
lm.fit(dm,DF$r)
    #$coefficients
#(Intercept)          x2          x3          y2
#  0.6208076   0.6927758  -0.5513966  -0.7585111

However, there will be warnings if you use the rank-deficient fit in, e.g., predict:
predict(fit, newdata=data.frame(x="1", y="2"))
#          1
# -0.1377035
# Warning message:
#   In predict.lm(fit, newdata = data.frame(x = "1", y = "2")) :
#   prediction from a rank-deficient fit may be misleading

unname(fit1$coef[1]+fit1$coef[4])
#[1] -0.1377035

Comment: It's the same true for logistic with glm?
Comment: Try and see youself.


How to get value from input with dynamically changed value by jquery UI slider?

Question: I've input text with a dynamically changed value by jquery UI slider. How to get value from  $("#scope_input") by jquery? .change event working only from manual keypress on keyboard, on sliding doesn't getting any value:
$("#scope_input").change(function() {
    console.log($(this).val());
});

$("#scope_slider").slider({
    range: "min",
    min: 1,
    max: 100,
    value: 10,
    slide: function(event, ui) {
    $("#scope_input").val(ui.value);
    }
});

Comment: where's the code that links to slider??
Answer: You need to trigger the change event manually:
$("#scope_input").val(ui.value).change();

Answer: WHen you update the field within the slide event, trigger the change on the input
$("#scope_slider").slider({
    range: "min",
    min: 1,
    max: 100,
    value: 10,
    slide: function(event, ui) {
    $("#scope_input").val(ui.value).change();
    }
});

Answer: Did you try
$("#scope_slider").bind("slidechange", function(event, ui) {
    $("#scope_input").val(ui.value);
});


Derive the distribution of the ANOVA F-statistic under the alternative hypothesis

Question: Say we have $k$ samples of data, where sample $i$ is of size $n_i$ and we write it as $x_{i1}, ... , x_{in_i}$. Let the total sample size be $N$.
The ANOVA model is $X_{ij} \sim N(\mu_i, \sigma^2)$ independently. The null hypothesis is that the $\mu_i$ are all equal. The alternative hypothesis is that the null hypothesis is not true.
The ANOVA F-statistic is
$$F = \frac{S_2/(k-1)}{S_1/(N - k)},$$
where
$$S_1 = \sum_{i, j}(x_{ij} - \bar{x}_{i\bullet})^2$$
is the within samples sum of squares and
$$S_2 = \sum_in_i(\bar{x}_{i\bullet} - \bar{x}_{\bullet\bullet})^2$$
is the between samples sum of squares.
We know that $S_1$ and $S_2$ are independent and $S_0 = S_1 + S_2$ $(*)$, where
$$S_0 = \sum_{i, j}(x_{ij} - \bar{x}_{\bullet\bullet})^2$$
is the total sum of squares.
It is straightforward to show that under both the null and the alternative hypotheses, $S_1 \sim \sigma^2\chi^2_{N - k}$.
Also, under the null hypothesis, the $X_{ij}$ are identically distributed, and so $S_0 \sim \sigma^2\chi^2_{N-1}$. It follows from $(*)$ that under the null hypothesis $S_2 \sim \sigma^2\chi^2_{k-1}$ and thus $F \sim F_{k-1, N-k}$.
It is claimed that under the alternative hypothesis, $F$ follows a non-central $F$-distribution $F_{k-1, N-k}(\lambda)$, where $\lambda = \sum_in_i(\mu_i - \bar\mu)^2$ and $\bar\mu = \sum_in_i\mu_i/N$ — or equivalently, that $S_2$ follows a (scaled) non-central $\chi^2$ distribution, $\sigma^2\chi^2_{k-1}(\lambda)$.
My tentative approach to proving this is similar to the derivation under the null hypothesis — that is, it is sufficient to prove that $S_0$ follows a (scaled) non-central $\chi^2$ distribution, $\sigma^2\chi^2_{N-1}(\lambda)$.
I've shown that this would follow from a slightly more general statement, namely that if $Y_i \sim N(\mu_i, \sigma^2)$ independently (sample size $N$), then $S_0 = \sum_i(Y_i - \bar{Y})^2 \sim \sigma^2\chi^2_{N-1}(\lambda)$, where $\lambda = \sum_i(\mu_i - \bar\mu)^2$.
Is this the best approach? And what is the simplest proof of the final statement above?
Thanks.
Comment: How do you know that $S_1$ and $S_2$ are independent, even under the null hypothesis? A complete proof of the distribution of $F$ would need to prove that rather than simply assume it.
Answer: Consider $Y_i \sim N(\mu_i, \sigma^2)$ (independently) as a random vector with a multivariate normal distribution, $\vec Y \sim N(\vec\mu, \sigma^2 I)$.
The main idea is to consider this distribution with reference to a new coordinate system. We choose the first axis to be along $\vec 1 := (1, ..., 1)$. The projection of any vector $\vec y$ onto this axis is $\bar y \vec 1$. In particular the projection of $\vec \mu$ is $\bar \mu \vec 1$. We use this as the origin. (We choose any orthogonal set for the remaining axes.)
We can decompose $\vec Y - \bar \mu \vec 1$ as $(\bar Y \vec 1 - \bar \mu \vec 1) + (\vec Y - \bar Y \vec 1)$, where the first term is the projection along the first axis, and the second term is the projection orthogonal to the first axis.
Thus $|\vec Y - \bar \mu \vec 1|^2 = |\bar Y \vec 1 - \bar \mu \vec 1|^2 + |\vec Y - \bar Y \vec 1|^2$.
It is a fact about independent normal distributions with equal variances that for any choice of orthogonal coordinate system, the axes will still be independent. So the two terms on the right hand side are independent.
And it is easy to show that:
$|\vec Y - \bar \mu \vec 1|^2$ has a non-central $\sigma^2 \chi^2_N(\lambda)$ distribution, with $\lambda = |\vec \mu - \mu \vec 1|^2 = \sum_i(\mu_i - \bar\mu)^2$, and
$|\bar Y \vec 1 - \bar \mu \vec 1|^2$ has a central $\sigma^2 \chi_1^2$ distribution.
Finally, note $|\vec Y - \bar Y \vec 1|^2 =\sum_{i}(Y_i - \bar Y)^2 = S_0$.
It follows from the additive properties of independent non-central $\chi^2$ distributions that we must have $S_0 \sim \sigma^2\chi^2_{N-1}(\lambda)$.
Note: I think this is a specific application of the idea of Cochran's theorem.


Mudar a cor de uma palavra em um textarea ainda em edição

Question: Como faço para que toda vez que o navegador achar uma "palavra reservada" no textarea, ele automaticamente mude a cor dela.
Eu quero saber para fazer um destaque de sintaxe.
Comment: Até ao que sei não é possível dar estilo a partes de uma ``. A solução mais comum é utilizar uma `` com o atributo `contenteditable="true"`
Answer: Não é possível alterar partes do texto de um textarea (bem como de um input). Você consegue aplicar estilos (cor, fundo, tipo de fonte, tamanho etc.) ao texto por inteiro ou ao elemento, e não por partes dele. Isso porque o textarea não renderiza tags HTML, e seu conteúdo é tratado como texto puro.
O que você pode fazer é usar plugins WYSIWYG que substitui o textarea por uma div editável e aplicar listeners que irão detectar as palavras reservadas no texto e aplicar a cor desejada somente nestas palavras (trabalho um pouco complicado, diga-se de passagem). Para isso você terá que pesquisar a forma que o JavaScript trata as instâncias do plugin e fazer uma programação à parte.
Alguns plugins WYSIWYG disponíveis, dentre outros, são o TinyMCE e o CKEditor.
Answer: Apenas como complemento à resposta do @DvD, mostro um exemplo muito simplista (e com algumas falhas) de como poderia implementar mudanças de cor de determinadas palavras utilizando
 com contenteditable=true:

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

//palavras que se pretende substituir e a classe com o estilo para essas palavras
const sintaxe = [
  {
    palavra:"int",
    classe:"tipo"
  },
  {
    palavra:"if",
    classe:"base"
  }
];

$("#editor").on("keyup", function(){ //aplicar a troca para cada tecla digitada
  let cnt = $("#editor").html();

  for (s of sintaxe){ //para cada palavra aplicar a substituição no editor
    //fazer o troca da palavra por um span com mesma palavra e a classe certa
    cnt=cnt.replace(s.palavra+" ", `<span class="${s.classe}">${s.palavra}</span> `);
  }

  $("#editor").html(cnt); //colocar o texto substituido de volta

  //colocar o cursor no fim de novo
  placeCaretAtEnd(document.getElementById("editor"));
});
#editor {
  border:1px solid orange;
}

.tipo {
  color:darkBlue;
}

.base {
  color:purple;
}

Escreva algum texto como int x; if(x==10) {

A função de colocação do cursor no fim veio de uma resposta no SOen e é necessário para que e exemplo funcione corretamente, uma vez que quando há uma substituição do html do
 por javascript o cursor volta ao inicio.


Can a set of vectors be linearly independent in one vector space, but be linearly dependent in another vector space?

Question: For example,
let S = {$(x_1, x_1)| x_1 \in \mathbb R$} be a subspace of $\mathbb R^2$.
By definition, dim(S) = 1, and dim($\mathbb R^2$) = 2.
Then the set {(1, 1)} only has one vector, so is it linearly independent in S, but is linearly dependent in $\mathbb R^2$?
I know this doesn't make any sense, but we learned in class that a set of vectors can only be linearly independent if it spans the vector space that it is in.
Since (1,1) is in both S and  $\mathbb R^2$, but the set {(1, 1)} only spans S, how come it is not only linearly independent in S and linearly dependent in $\mathbb R^2$ (since {(1,1)} does not span $\mathbb R^2$).
Sorry for this stupid question
Comment: `we learned in class that a set of vectors can only be linearly independent if it spans the vector space that it is in` You must have misunderstood something. Two non-parallel vectors are linearly independent in $\,\Bbb R^3\,$, for example, but they certainly don't span $\,\Bbb R^3\,$.
Comment: If the set $\{v_1,\dots,v_n\}$ doesn't span $V$, then it need not be linearly dependent, *unless* $n=\dim V$. In your case the set consists of one vector and $\mathbb{R}^2$ has dimension $2$.
Comment: Vectors are linearly independent of other vectors in the same space so it doesn't make sense to discuss them in different spaces.
Comment: $\{ 1 \}$ is linearly independent in $\mathbb{R}$ with the usual vector $\mathbb{R}$-vector space structure; but if instead you use the vector space structure $x \oplus y = x + y - 1$, $\lambda \odot x = \lambda x - \lambda + 1$ then $\{ 1 \}$ is linearly dependent with respect to this structure.
Comment: Another possible example: if you consider $\mathbb{C}$ to be a vector space over $\mathbb{R}$, then $\{ 1, i \}$ is linearly independent.  However, if you consider $\mathbb{C}$ to be a vector space over $\mathbb{C}$, then $\{ 1, i \}$ is linearly dependent.
Comment: On the other hand, if $W$ is a subspace of $V$ and $S \subseteq W$, then $S$ is linearly independent as a subset of the vector space $W$ if and only if $S$ is linearly independent as a subset of the vector space $V$.
Answer: You said you "learned in class that a set of vectors can only be linearly independent if it spans the vector space that it is in." This isn't correct, unless "the vector space that it is in" means "the smallest vector space that it is in," which would not be a typical reader's understanding. But even with that understanding, the statement is not useful, because the fact is not special to linearly independent sets. Every set of vectors spans the smallest vector space that contains them: a set of vectors spans its span. (That's practically the definition of span.)
I suspect what you were supposed to learn in class was that "A set of vectors in a vector space $V$ can only be a basis for $V$ if the set spans $V$." (In addition, it must be a linearly independent set of vectors.)
In particular, the set $\{(1,1)\}$ is a linearly independent set, whether it is considered as a set of vectors in $\mathbb R^2$ or as a set of vectors in what you call $S$. The fact that $\{(1,1)\}$ does not span $\mathbb R^2$ does not tell you anything about the linear independence of the set. (And by the way, any set containing only one vector is a linearly independent set of vectors so long as that one vector is not zero.)
Comment: Ok.  I should have read it more carefully.   It gives an implication whose conclusion is always true.  Now I see.
Comment: Slight correction in first paragraph:   A set is not linearly independent if it spans the smallest space that it's contained in...
Comment: Chris: The OP's statement was that a space can ONLY be linearly independent if it spans the vector space that it is in. The word "only" reverses the implication. "P only if Q" means "if P then Q." It is true that a set of vectors is linearly independent ONLY if it spans its span, but as I note, that is not a useful fact.
Answer: Suppose $\{v_1,v_2,\dots,v_n\}$ is a basis of $V$. Then
$$
\{v_2,\dots,v_n\}
$$
doesn't span $V$, but it is linearly independent.
A set of vectors may fail to span $V$, but it can still be linearly independent.
The only case when you can infer linear dependence from the fact that a set fails to span $V$ is when the set has the same number of elements as the dimension of $V$.
In your case this condition is not satisfied, because $\{(1,1)\}$ consists of one element, but the dimension of $\mathbb{R}^2$ is two.
Answer: I think it's safe to say that if a set of vectors is linearly independent in one space, then it will be in any space that contains it.
This seems clear for any superspace, $W\supset V$...
Also,  when a different space contains our space...  For instance,  the spaces $V=x$-axis, $W=xy$-plane and $U=xz$-plane.  We simply get that $\{(1,0)\}$ is linearly independent in (actually)  all three spaces.
The reason is that the defining condition,  namely that only the trivial linear combination is zero, is independent of the surrounding space...
One could say, for instance,  that a set is linearly independent $\iff$ it is a basis for the space it spans.  Again,  notice there is no mention of any (larger) surrounding space.
As pointed out by @egreg, if there are $n$ vectors,  and if $\operatorname{dim} V=n$, then it is true (that the set is linearly independent iff it spans $V$).
In light of @Daniel Schepler's comments,  we should note that changing the base field,  or the vector space "structure", we can get some different results.   This shows your question may be a little better than you originally thought (though it was an error that led you to it)...
Answer: As egreg explained, your example is wrong.
Suppose $V$ and $W$ are both subspaces of a vector space $X$.
 Then any set of vectors $\{v_1, \ldots, v_k\}$ in the intersection $V \cap W$ that is linearly dependent as a subset of vector space $V$ is also linearly dependent as a subset of  $W$.  This is because both linear dependence statements are equivalent to the existence of scalars $c_1, \ldots, c_k$, not all $0$, such that $c_1 v_1 + \ldots + c_k v_k = 0$.
Answer: Firstly, the definition

... that a set of vectors can only be linearly independent if it spans the vector space that it is in.

is not correct.
A set $S$ of vectors is linearly dependent if there is some $v \in S$ that can be written as a linear combination of other vectors from $S$. It is linearly independent otherwise.
More formally, a set of vectors $S = \{v_1,\ldots,v_k\}$ is linearly independent if
$$\sum_{i=1}^{k}\alpha_iv_i = 0 \quad \Rightarrow \quad \alpha_1= \cdots = \alpha_k=0$$
That is, the only way we can make zero from vectors in $S$ is by multiplying every vector by zero.
It is easy to see that if we remove vectors from linearly independent $S$, it stays linearly independent. Conversely, if we add a vector to $S$, it may become dependent. The maximum cardinality (number of elements) of a linearly independent set of vectors in a $n$-dimensional vectors space $V$ is $n$ and this set is then called a basis for $V$. It has the property that it spans entire $V$, that is - every $v \in V$ can be represented as a linear combination of vectors from basis.
Note that the cardinality of a set of vectors tells us nothing precise about its linear (in)dependence.
example 1: $\{(1,1),(2,2)\}$ is linearly dependent in $\mathbb{R}^2$ because $2 \cdot (1,1) = (2,2)$.
example 2: $\{(1,1)\}$ is linearly independent in $\mathbb{R}^2$ but not a basis for $\mathbb{R}^2$ because $|S| = 1 \neq 2 = dim \mathbb{R}^2$..
example 3: $\{(1,1),(2,3)\}$ is linearly independent in $\mathbb{R}^2$ and also a basis for $\mathbb{R}^2$ because $|S| = 2 = dim \mathbb{R}^2$.
example 4: $\{(1,1),(2,3),v\}$ must be linearly dependent in $\mathbb{R}^2$, for any $v \in \mathbb{R}^2$.
example 5: $\{(1,1)\}$ is linearly independent in your space $S := \{(x_1,x_1)| x_1 \in \mathbb{R}\}$ and a basis for it.


Auto-submit exposed form

Question: I'm currently working on a views exposed form block. I want the form to auto-submit using AJAX, whenever an exposed filter is changed.
I have searched for this, but I couldn't find any tutorial or guide.
I cannot see any setting in the view, so I guess I have to implement  hook_form_alter. Is that correct, or am I missing something?
Answer: I actually found the answer myself. Using the Better Exposed Filters module did the trick.
From the module's description:

Provide instant feedback by updating the View using AJAX whenever an exposed filter is changed.

Auto-submit exposed form


Fundamental Theorem Of Calculus in an equation

Question: So as stated in the fundamental theorem of Calculus
$ ∫_b^x f(t) = F(x) $
How would the theorem apply to this question as when finding $ f(4) $ in this equation?
$ ∫_b^{x^2} f(t)dt = x\sin(π x) $
Answer: $$\int_b^xf (t)dt=F (x)\implies $$
$$F (x^2)=x\sin (\pi x) \implies$$
$$ F (x)=\sqrt {x}\sin (\pi\sqrt {x}) $$
and
$$f (t)=F'(t)$$
$$=\frac {\sin (\pi\sqrt {t})}{2\sqrt {t}}+\frac {\pi}{2}\cos (\pi\sqrt {t})$$
thus $$f (4)=\frac {\pi}{2} $$
Comment: So by applying the Fundamental theorem to the integral, you wouldn't have do differentiate both sides in order for F(t) to be F(x^2) and applying the chain rule to F(x^2)?
Comment: @Killimanjaro if you differentiate, you will get $f (x^2)2x=\sin (\pi x )+\pi x\cos (\pi x) $.
Comment: Would that be incorrect to do in this situation?
Comment: Yes.take $x=2$ to have $f (4) $.