Estimation of partitioning error in next-generation sequencing experiments

Question: [Edited: explanation of the partitioning error]
I would like to estimate how the initial number of molecules (or the level of gene expression) affects reproducibility between technical replicates of my sequencing experiment (one vial - one experiment).
Simplifying, we have $X$ different genes with $N_x$ RNA molecules for each gene. We take the genes one by one and partition $N_x$ molecules between $R$ identical vials. We assume that each vial has the same probability. Given the number of molecules ($N_x$), what is the expected partitioning error.
Partitioning error: If $r_1, r_2, ... , r_n$ are the number of molecules within each vial after partitioning, partitioning error is a spread of $r_1, r_2, ... , r_n$
Comment: Sorry, im not really well versed in genetics, Could you define what partitioning error means for this problem.
Comment: I added an explanation.
Comment: spread isn't a well defined statistical term. Do you mean variance? The ratio of correct to incorrect partitionings?
Comment: I am sorry, I am quite new to the field. I mean variance, of course.
Answer: Ok, I believe the way we can look at your problem with a multinomial distribution. Like the binomial models the sorting of N balls into 2 containers, the multinomial models the sorting of N balls into m containers. So in this case, take a gene (call it gene1), this gene has N_1 molecules. If you have an equal probability of these molecules ending up in each of the R vials, then on average, you will get $N_1 /R$ molecules in each vial. Now, since we hope that the partitioning acts the same for each gene, this means that we now have a probability model for this situation, ie independence between genes, the joint distribution is now the product of multinomials. This means that if $y_{ij}$ represents the number of molecules of gene i in vial j, we have the probaiblity model:
$$f(y_{11} .... y_{I,J}) = \prod_{i=1}^I \prod_{j=1}^J Multinomial(N_i, (1/2, ... 1/2)) =\prod_{i=1}^I \prod_{j=1}^J \frac{N_x}{y_{ij}!} p_{ij}^{y_{ij}} $$
Great, we now have a statistical model for this phenomenon. Now we can compute the variance. When we deal with just one gene, we have a multinomial $(y_{1,i}, ... y_{I,i}) \sim $Multinomial(N_i, (1/2, ... 1/2), so you can get right from the wiki that:
$$Var(Y_i) = n_i p_i (1-p_i) = N_i (1/2)^2 = 4 N_i$$
$$Cov(Y_i,Y_j) = -n_i p_i p_j =  -\frac{N_i}{4} $$
Now when we upgrade to the multiple gene situation, since we are assuming independnece between genes, this becomes the product-multinomial distribution. The variance matrix of the product-multinomial would give you what you are looking for.


JS: how to create optionally chainable methods

Question: JS newbie question here:
Let's say I have some simple methods for string manipulation, like these silly examples:
var prepend = function(str) {
  return 'foo ' + str
};

var exclaim = function(str) {
  return str + '!'
}

Now, I can use these like so:
var string = prepend('bar'); // 'foo bar'
string = exclaim(string); // 'foo bar!'

However, I think it would be really neat if I could also, optionally, make these methods chainable, so I could also do something like:
var string = "foo"
string.prepend().exclaim()

... and I'd still get "foo bar!" as my result.
It would be even better if I could also pass optional args into this chain, like:
var exclaim = function(string,char="!") {
  return string + char
};

So, my questions are:

So basic, but am I describing this correctly? What do you call a method that can be chained like this? And, what do you call the return of the previous method in the chain, the thing that this next method will operate on?
How do you set a variable to be either the return of the previous method in the chain, or else provided as an argument?

Thanks!
Answer: If you want to chain them, then you'll have to add these methods to the string prototype:
String.prototype.prepend = function() {
  return 'foo ' + this
};

String.prototype.exclaim = function() {
  return this + '!'
}

var s = "".prepend().exclaim();
console.log(s);

DEMO

WRT optional parameters, you can take advantage of the fact that in JavaScript, you can call a method without passing values for some of the parameters.  Those un-passed parameters will show up as undefined in the function.  Since null implicitly converts to undefined, that's often handled by checking those parameters for null
var exclaim = function(str, ch) {
  if (ch == null){
      ch = '!';
  }
  return string + ch
};

You'll often also see something like this:
var exclaim = function(str, ch) {
  ch = ch || '!';
  return string + ch
};

That's similar, but will overwrite any of the 6 "falsy" values: null, undefined, NaN, 0, false and '' (empty string).  So if you were to do that, and try to pass an empty string in for ch, it would be overwritten.
Comment: Awesome, very helpful examples. Thanks!
Comment: Hmm, is that kosher? Are there potential problems making something chainable by adding a method to a prototype?
Comment: @Andrew - adding methods to the prototype of built-in objects is not usually recommended, but if you really wanted to make these chainable, that's how you'd do it.
Answer: To avail chain-able method you should return an instance of the object that contains that method. In most case you'd return this.
See this MyString class for example
function MyString(s){
   this.str = s;
}
MyString.prototype.lower=function(){
   this.str = this.str.toLowerCase();
   return this;
}
MyString.prototype.upper=function(){
   this.str = this.str.toUpperCase();
   return this;
}
MyString.prototype.last=function(x){
   return this.str.substr(-x);
}
MyString.prototype.first=function(x){
   return this.str.substr(0,x);
}

MyString.prototype.get=function(){
   return this.str;
}

var ms = new MyString("Hello");
var s  = ms.lower().first(2); // s = 'he';

Answer: You could do this:
 var string = exclaim(prepend('bar'));

Or you could extend the String object so that you can use the .prepend() and .exclaim() syntax:
  String.prototype.prepend = function() {
       return 'foo ' + this
  };

  String.prototype.exclaim = function() {
      return this + '!'
  }


Two different trigonometric identities giving two different solutions

Question: Using two different sum-difference trigonometric identities gives two different results in a task where the choice of identity seemed unimportant. The task goes as following:

Given  $\cos 2x =-\frac {63}{65} $ , $\cos y=\frac {7} {\sqrt{130}}$, under the condition $0<x,y<\frac {\pi}{2}$, calculate $x+y$.

The first couple of steps are the same: finding  $\sin$ and $\cos$ values for both $x$ and $y$.
From $\cos 2x$ we have:
\begin{align*}
\cos 2x &=-\frac {63}{65} \\
\cos2x &= \cos^2x-\sin^2x = \cos^2x - (1-\cos^2x)=2\cos^2x -1 \\
2\cos^2x -1 &= -\frac {63}{65} \\
2\cos^2x &=\frac {-63+65}{65} \\
\cos^2x &=\frac {1}{65} \\
\cos x &=\frac {1} {\sqrt{65}}
\end{align*}
(taking only the positive value of $\cos x$ because $\cos x$ is always positive under the given domain)
\begin{align*}
\sin^2x &=1-\frac {1}{65} \\
\sin^2x &=\frac {64}{65}   \\
\sin x &=\frac {8} {\sqrt{65}}
\end{align*}
(again, only positive value)
From $\cos y$ we have:
\begin{align*}
\cos y &=\frac {7} {\sqrt{130}} \\
\cos^2y &=\frac {49} {130} \\
\sin^2y &=1-\frac {49} {130} \\
\sin^2y &=\frac {81} {130} \\
\sin y &=\frac {9} {\sqrt{130}}
\end{align*}
Now that we've gathered necessary information, we proceed to calculate value of some trigonometric function of $x+y$, hoping we will get some basic angle:
sin(x+y):
\begin{align*}
\sin(x+y) &=\sin x \cos y + \sin y \cos x =\frac {8} {\sqrt{65}} \frac {7} {\sqrt{130}} + \frac {9} {\sqrt{130}}\frac {1} {\sqrt{65}} \\
\sin(x+y) &=\frac {65} {\sqrt{65}\sqrt{130}} \\
\sin(x+y) &=\frac {\sqrt{2}}{2}
\end{align*}
Thus,
$x+y =\frac {\pi}{4}+2k{\pi}$  OR  $x+y =\frac {3\pi}{4}+2k{\pi}$
Since $x$ and $y$ are in the first quadrant, their sum must lie in first or second quadrant.
Solutions are:
$x+y= \{\frac {\pi}{4}, \frac {3\pi}{4} \}$
cos(x+y):
\begin{align*}
\cos(x+y) &= \cos x \cos y - \sin x \sin y =\frac {1} {\sqrt{65}} \frac {7} {\sqrt{130}} - \frac {8} {\sqrt{65}}\frac {9} {\sqrt{130}} \\
\cos(x+y) &=-\frac {65} {\sqrt{65}\sqrt{130}} \\
\cos(x+y) &=-\frac {\sqrt{2}}{2}
\end{align*}
Thus,
$x+y =\frac {3\pi}{4}+2k{\pi} $   OR   $x+y =\frac {5\pi}{4}+2k{\pi}$
Now we can only have one solution: $x+y=\{\frac {3\pi}{4}\}$
Similar happens with $\cos(x-y)$.
My question is: why do these two formulas give two different solutions? General insight would be great, since I found a lot of examples with similar problems. Thank you in advance.
Comment: It might be because in some steps you square both sides. Usually if that's one of your steps you might get an extra solution at the end that won't actually work with the original question. i.e. x+y=$\pi$/4 might not actually work. So if you substitute x = $\pi$/4 - y in your original two equations, you should get that x>$pi$/2.
Comment: Maybe because $\cos (x) = \sin (\frac{\pi}{2} + x)$, your solutions also differ by $\frac{\pi}{2}$ ?
Comment: BTW, your computation of $\sin y$ from $\sin^2 y$ is incorrect.
Comment: You wrote $\sin^2y = \frac{81}{130}$, then concluded that $\sin y = \frac{9}{\sqrt{\color{red}{65}}}$.  Happily, you corrected the error in your subsequent calculations.
Comment: @N.F.Taussig it is now corrected, thank you very much.
Answer: Andre already gave the answer, but let me explain the "generalities".
The main problem is the following:

After you reached the point $\sin(x+y) = \sqrt{2}/2$, you concluded that $x+y$ can take both values $\pi/4$ or $3\pi/4$.

You interpreted this to mean

BOTH $x+y = \pi/4$ and $x+y = 3\pi/4$ are solutions. (That is, the set of solutions is the set $\{\pi/4, 3\pi/4\}$.)

This interpretation is false! The correct interpretation is that

We have ruled out all numbers other than $\pi/4$ and $3\pi/4$ from being possible solutions. (Or, the set of solutions is a subset of the set $\{\pi/4, 3\pi/4\}$.)

There may be other constraints that rule out one (or both) of those values. In your case, knowing that $\cos x \approx 1/8$ should tell you already that $x$ is bigger than $\pi/4$.

Another way to look at this clearly is to look at the directions of implication. From the values of $\sin x$, $\sin y$ etc you can derive the value of $\sin(x+y)$. But just knowing the value of $\sin(x+y)$ you cannot derive the value of $\sin x$, $\sin y$, etc. So the implication going from the "necessary information" step to the "computing $\sin(x+y)$ and $\cos(x+y)$" step is one that loses information.
So that solutions to $\sin(x+y) = \sqrt{2}/2$ are not necessarily solutions to $\cos(x) = 1/\sqrt{65}$ etc.
Comment: This was very helpful. I'll make sure to collect every bit of information I can from description of the problem or at least plug my solutions back into the equation. Thank you very much.
Answer: In your  calculation of $x+y$ via $\sin(x+y)$, you wrote that $x+y=\frac{\pi}{4}$ is a possibility. It is not, since already $\sin y=\frac{9}{\sqrt{130}}\gt\frac{1}{\sqrt{2}}$, so $y\gt \frac{\pi}{4}$.
Remark: In this case, computing $\cos(x+y)$ is the better strategy, since the cosine here unambiguously identifies $x+y$. Computing $\sin(x+y)$ also works, but requires an extra step to disambiguate.
Answer: Simply: Solving for an angle using its sine value is ambiguous. (This is one reason that the Law of Cosines is preferred over the Law of Sines for determining angles from sides.)

Here's an analogous situation:
$$\begin{align}x^2 + 2 x = 35 \quad(1)\\
x^2 - 2 x = 15 \quad(2)
\end{align}$$
Adding $(1)+(2)$, we see that $2 x^2 = 50$, so that $x = \pm 5$. On the other hand, $(1)-(2)$ gives $4x = 20$, so that $x = 5$. Two valid approaches seem to give different solution sets. But note: in the first case, one of the proposed values of $x$ is extraneous. You can check this by substitution: $-5$ is not a solution to $(1)$ or $(2)$.

In your problem, you can likewise determine that one of the values from the sine-based solution is extraneous.
We're given that $\cos 2x$ is negative, while $x$ itself is strictly positive and acute; therefore, $2x$ must be strictly larger than a right angle, which implies that $x > \pi/4$. Since $y$ is also assumed positive, it cannot be that $x+y = \pi/4$. Thus, $3\pi/4$ is the only valid solution.

The lesson here is that some approaches to a problem introduce extraneous solutions. You should always double-check that proposed solutions actually work in the original equations.
Answer: To know which quadrant $x+y$ is in, you need to know the signs of both $\sin(x+y)$ and $\cos(x+y)$ In your case, $\sin(x+y) \gt 0$ and $\cos(x+y) \lt 0$. This puts $x+y$ in the second quadrant. So the solution is the one angle $x+y = \dfrac{3 \pi}4$.


Changing class from disable to active

Question: I'm having some issues changing my class to active when adventwindow <= day, I want it to change the class from disable to active when true. If anyone could help that would be amazing!

var day = 5;
var adventwindow = 1;

if (adventwindow <= day) {
  document.getElementsByClassName('disable').className = 'active';
}
.door {
  color: #fff;
  font-size: 70px;
  position: absolute;
  top: 0;
  left: 0;
  background-color: #91c1cc;
  box-sizing: border-box;
  border-top: 2px #eee dashed;
  border-right: 2px #eee dashed;
  border-bottom: 2px #eee dashed;
  border-left: 1px #eee solid;
  border-radius: 6px;
  padding: 15px;
  width: 130px;
  height: 130px;
  transform-origin: 0 40%;
  transition: all 0.4s ease-in-out;
  transform-style: preserve-3d;
  text-align: center;
}
a.disable {
  pointer-events: none;
  cursor: default;
}
a.enable {
  pointer-events: auto
}

1

Answer: getElementsByClassName returns a collection of elements with the given class name. You can access the elements by index which start from 0.
document.getElementsByClassName('disable')[0].className = 'active';

Changing class from disable to active


Is it possible to extend notes and also shift the 2nd 3rd etc notes offset from the first note?

Question: Is it possible to extend a set of notes (or a whole piece) while also updating its offset from the first selected note? For example, when I select 2 notes 1/4 apart and drag to scale them to 1/2 notes size I want to see 2 x 1/2 notes next to each other (not 1 x 1/4 and 1 x 1/2). This is a little tricky to explain but let me know if you need another example or picture illustration of what I mean.
Regards, Tom
Comment: Otherwise this is probably something the support of ableton could help you with.
Comment: Hi @Olli. I tried every key combination I could think of and did a lot of googling without any luck! I'll try to get in touch with the support team
Comment: I think i have seen how this could be done. But i am not sure if it was with ableton or some other DAW. Did you try to hold some keys on your keyboard while dragging the last note with your mouse? Maybe something like 'alt', 'control', 'shift' or some combination.
Answer: hey i figured this out.
you use time stretch in the top of the midi roll once you've selected the notes. its the little blue bar that appears with a marker on it. you move that marker


AirPlay Mirroring on iPhone 4

Question: My app uses hardware features of the phone not available on the simulator and i'd like to be able to demo the app for my client via screen sharing.  Using  AirServer, i can AirPlay to my Mac, but my iPhone 4 doesn't support video mirroring out of the box.  Is there any magic that would let me do this?  Since this is just for a demo, undocumented APIs are encouraged.
Thanks!
Answer: The official way to support external screens is simply to call
<code>[UIScreen screens]
</code>
to get a reference to available screens including the external screen. You could grap that feed with a bit of hardware for an awesome screencast.
The process is mentioned in this thread connecting iPad to external monitor. It works equally well on iPhone and iPod. Apples official UIScreen documentation is available here
Comment: Good answer, but the count of [UIScreen screens] is zero since it's not connected to another display and i can't enable AirPlay mirroring.  It's that last part (enable some type of AirPlay out) that i'm hoping to do with some black magic.
Comment: I know I'm a little late to provide an answer. At the moment, only the iPhone 4S supports screen mirroring via AirPlay. To test on an iPhone 4, you can buy an HDMI adapter from Apple to connect an external display, which has the same effect in the code as @Niels Castle described.

http://store.apple.com/us/product/MD098ZM/A?fnode=MTc0MjU4NjE

AirPlay Mirroring on iPhone 4


Preciso criar pasta mesmo que esteja no .gitignore

Question: Pessoal preciso que o conteúdo de uma pasta não seja enviado para o git (até aqui tudo bem eu uso o .gitignore) mas eu preciso que a pasta seja criada. Tem como fazer isso usando somente um .gitignore na raiz do projeto.
Comment: Relacionada: [Git - como ignorar arquivos dentro de uma pasta \[duplicada\]](https://pt.stackoverflow.com/q/356393/3774)
Comment: Relacionada: [Git - Ignorando arquivos com .gitignore](https://pt.stackoverflow.com/q/345899/3774)
Answer: Nesse caso não pode adicionar no .gitignore que está no nível "acima" da pasta.
Dentro da pasta que quer que apenas fique lá vazia, crie um outro .gitignore com "*" para ignorar tudo que tem nessa pasta, assim por exemplo:
*
*/
!.gitignore

Não esqueça de adicionar o arquivo com um git add.
E se sua pasta tiver subpastas, vai precisar acrescentar os nomes no .gitignore, ou criar o mesmo arquivo em cada subpaasta.
Por exemplo:
/src
   .gitignore <- esse não deve mexer
   /subpasta-que-quer-criar
       .gitignore <- esse que deve ter o "*"

Comment: Eu meio que ja estou usando desta forma, achei que tivesse uma forma mais simples com um .gitignore só.
Answer: Basta que tu coloques o nome da pasta no .gitignore. Por exemplo, tenho um projeto Node.js, e não quero subir a pasta node_modules dele. É só eu colocar no .gitignore isso:
node_modules/

a estrutura de pastas, pra saber a localização do .gitignore e da pasta ficaria assim
<projeto>
   .git (pasta oculta que indica que é um repositório git)
   .gitignore (arquivo com o que quero ignorar)
   node_modules (pasta que não quero subir no git)

Assim tu podes ignorar qualquer pasta local. Elas poderão existir na tua máquina sem problemas, suas mudanças não serão refletidas no git.
Comment: *"...mas eu preciso que a pasta seja criada." Leonardo, se fizer isso ao clonar ou fazer pull do repositório não vai criar pasta certo? não é o mesmo que já foi citado na pergunta ( *"até aqui tudo bem eu uso o .gitignore"* )?


A question about removing equality in predicate logic

Question: I'm currently taking a course on Mathematical Modelling, more specifically Advanced Predicate Logic, and we were talking about predicate logic when I was introduced to these 2 rules:
$$\frac{}{t = t}[=i]\qquad\frac{t_1=t_2\quad[x\Rightarrow t_1]\phi}{[x\Rightarrow t_2]\phi}[=e]$$
Then, when we went to apply it to prove
$$f(x) = g(x)\vdash h(g(x)) = h(f(x)),$$ we were given a solution that looked like this:
\begin{align*}
1.\quad &f(x) = g(x)\qquad&\text{premise}\\
2.\quad &h(f(x)) = h(f(x))\qquad&=i\\
3.\quad &h(g(x)) = h(f(x))\qquad&=e\ 1,2
\end{align*}
I want to ask about the third line of the solution, specifically how ${=e}$ can be used with lines 1 & 2 to create line 3.
For context, the professor who gave this assignment gave an answer that went something like this:
${f(x) = g(x)}$ because of the premise.
Let ${\phi}$ be ${h(y) = h(y)}$ for all $y$, then $h(f(x)) = h(f(x))$ is from substituing $y = f(x)$ into $\phi$. (i.e. $[y\Rightarrow f(x)]\phi$).
From the first two lines, we can see that $[y\Rightarrow g(x)]\phi$, but we only need to substitute 1 side of $\phi$, leaving us with $h(g(x))=h(f(x))$.
We haven't learned about anything relating to ${\forall}$ & ${\exists}$ yet so don't worry about ${h(y) = h(y)}$ for all $y$.
Thanks for your answers!
Comment: It does create a lot of bother; if your links break and the information is not in the question, nobody can later figure out what you meant to say with them. And that's presuming anybody trusts you enough to follow the links at all; I certainly don't, from a user without established reputation (in both senses).
Comment: Please transcribe the problem and solution; do not use images, given you clearly have a handle on mathjax.  The easier you make it for users to answer, with having to open two links in additional tabs, the more successful you'll be on this site.
Comment: @amWhy Thanks for your feedback. I haven't known much about Latex so I could only write that much. I wished I could embed pictures in my questions, but I haven't had enough reputation point to do so. Besides, I don't think clicking a link would bother the answering process by that much. But I'll try to keep what you said in mind for when I ask other questions.
Answer: Set $t_1 := f(x)$, $t_2 := g(x)$, and put $\phi$ as $h(y) = h(f(x))$, then rule $[=e]$ says
$$\frac{f(x) = g(x)\quad h(f(x))=h(f(x))}{h(g(x))=h(f(x))}$$


Binding a subdomain to a directory without apache (available through ssh)

Question: I know how to bind a domain/subdomain to a directory using apache, through virtualhost. I would like to do the same operation without using apache and http. Something that can work using ssh or git protocol. I can't find any data on the internet.
Especially, on github, to clone a repository, you can use "firstname.lastname@example.com:symfony/symfony.git", I'm pretty sure that users managing repositories aren't stored at / .
Any ideas ?
Thanks.
Answer: The way it can work with ssh is when you are using the ssh forced command mechanism which will call a script with:

your git command (clone, push, pull)
your repo name (deduced from the git command)

That script knows where the repos are.
One example of such an approach is done with gitolite (see how does gitolite works).
The .gitolite.rc it generates during its installation will put all the bare rpeos at ~/repositories:
$rc{GL_REPO_BASE} = "$ENV{HOME}/repositories";

Yet, with the appropriate ~/.ssh/config file on the client side, you would clone a gitolite repo with:
git clone gitolite:myrepo

More details at "users are asked for password while using gitolite".
Comment: Thank you for that quick answer. Obviously, I saw this kind of answer browing the internet. But the forced command was for sftp, i thought this was irrelevant for my case. Anyway, thank you, I'll study that right now.
Comment: @pataprout I have edited the answer with more details on gitolite. You can see my installation script for gitolite at https://github.com/VonC/compileEverything/blob/master/gitolite/install_or_update_gitolite.sh


Convertendo um algoritmo .NET para JS

Question: Amigos, estou com um pequeno problema na 'conversão' de um algoritmo.
No algoritmo em .net eu tenho a seguinte estrutura condicional:
if (')' == caracter){
    String item = pilha.Pop().ToString();
    while (!item.Equals("(")){
        resultado += item;
        item = pilha.Pop().ToString();
    }
}

Jogando tudo para javaScript ficaria do seguinte modo:
if (')' == caracter){
    var item = pilha.pop();
    while (item != '('){
        resultado += item; //Corrigido
        item = pilha.pop();
    }
}

No meu entender while (!item.Equals("(")){ seria o equivalente a um while (item != '('){
So que nessa condição ele está entrando em looping infinito, ou seja o algoritmo não está executando da maneira como deveria..... Alguem poderia me dar um Help sobre a função Equals e o operador ! em .net?
A minha interpretação foi "muito" errônea?
-------Interpretacao do codigo todo:
.NET
private String funcao(String expressao){
    String resultado = null;
    Stack pilha = new Stack();
    char caracter;
    int prioridade = 0;

    for(int i = 0; i < expressao.Length; i++){
        caracter = expressao[i];

        if(IsOperando(caracter)){
            resultado += caracter;
        }else if (IsOperador(caracter)){
            prioridade = ObterPrioridade(caracter);
            while((pilha.Count != 0) && (ObterPrioridade(Convert.ToChar(pilha.Peek())) >= prioridade)){
                resultado += pilha.Pop().ToString();
            }

            pilha.Push(caracter);
        }else if ('(' == caracter){
            pilha.Push(caracter);
        }else if (')' ==caracter){
            String item = pilha.Pop().ToString();
            while (!item.Equals("(")){
                resultado += item;
                item = pilha.Pop().ToString();
            }
        }
    }

    while(pilha.Count != 0){
        resultado += pilha.Pop().ToString();
    }

    return resultado;
}

Interpretado pra JS:
function funcao(){
    var arrayDeCaracteres = "((A + B) * C – (D – E)) ^ (F – G)";
    var pilha = new Array;
    var prioridade = 0;
    var caracter = ""; var resultado = "";

    for(i = 0; i < arrayDeCaracteres.length; i++){
        caracter = arrayDeCaracteres[i];

        if(operando(caracter)){
            resultado += caracter;
        }else if (operador(caracter)){
            prioridade = obterPrioridade(caracter);
            aux = pilha.pop();
            aux2 = obterPrioridade(aux);
            pilha.push(aux);
            while((pilha.length  > 1) && (obterPrioridade(aux2 >= prioridade))){
                resultado += pilha.pop();
            }
            //Insere o objeto no topo da pilha
            pilha.push(caracter);
        }else if ('(' == caracter){
            //Insere o objeto no topo da pilha
            pilha.push(caracter);
        }else if (')' == caracter){
            var item = pilha.pop();
            while (item != '('){
                resultado += item;
                //Recupera e remove o objeto do topo da pilha
                item = pilha.pop();
            }
        }
    }

    while(pilha.length > 1){
        resultado += pilha.pop();
    }
}

Funções ObterPrioridade, IsOperando e IsOperador em .NET:
private int ObterPrioridade(char caracter){
    int retorno= 0;
    String pri2 = "+-";
    String pri3 = "*/";
    if('(' == caracter){
        retorno = 1;
    }else if(pri2.IndexOf(caracter) >= 0) {
        retorno = 2;
    }else if(pri3.IndexOf(caracter) >= 0){
        retorno = 3;
    }else if ('^' == caracter){
        retorno = 4;
    }
    return retorno;
}

private bool IsOperando(char caracter){
    String letras = "ABCDEFGHIJKLMNOPQRSTUVXZ";
    return (letras.IndexOf(caracter) >= 0);
}

private bool IsOperador(char caracter){
    String operadores = "+-*/^";
    return (operadores.IndexOf(caracter) >= 0);
}

Funções obterPrioridade, operando e operador em JS:
function operando(caracter){
    var regex = /^[a-zA-Z]+$/;
    if(regex.test(caracter)){
        return true;
    }else{
        return false;
    }
}

function operador(caracter){
    var regex = /^[*+-–/]+$/gi;
    if(regex.test(caracter)){
        return true;
    }else{
        return false;
    }
}

function obterPrioridade(caracter){
    var retorno= 0;
    var regex1 = /^[+-–]+$/gi;
    var regex2 = /^[*/]+$/gi;

    if('(' == caracter){
        retorno = 1;
    }else if(regex1.test(caracter)){
        retorno = 2;
    }else if(regex2.test(caracter)){
        retorno = 3;
    }else if ('^' == caracter){
        retorno = 4;
    }
    return retorno;
}

EXPLICAÇÃO DO ALGORITMO:
O algoritmo prevê a conversão de uma expressão matemática InFixa em PosFixa....
O que ser uma expressão InFixa?
Expressões naturais, como normalmente são escritas, tipo: ( a + b ) * ( c - d )
O que ser uma expressão PosFixa?
Expressões onde os operadores são posicionados após as operações de forma que os parenteses não são necessáriosa, tipo a b + c d - *
Tem regra de prioridade de operadores e tudo o mais, é bem complicadinho, mas o algoritmo é um tanto quanto simples
Comment: Pode dar um exemplo? Qual é a `pilha.length`? Se um dos elementos dessa array não tiver o `(` esse loop vai ser infinito mesmo
Comment: O que tem essa array `pilha`?
Comment: está empilhando operadores do tipo " +-*/ " alem de caracteres " () "
Comment: Cara, rodei os dois aqui e deu certo. Só tem q tomar cuidado se alguma vez vai aparecer o '(', pq ai entra num loop infinito.
Comment: Então, `!item.Equals("(")` seria o mesmo que `item != '('` mesmo?
Comment: Sim... a mesma coisa.
Comment: @MarceloBonifazio esse código parece-me frágil. Daí eu pedir exemplos para ajudar a optimizar. De resto a sua "tradução" entre linguagens parece-me correta tirando o facto de `resultado` na sua versão ter somente o valor da ultima iteração e não uma concatenação das iterações.
Comment: So complementando o que eu disse antes, é a mesma coisa para este tipo de aplicação.
Comment: Na verdade o que vai acontecer ai é que quando a pilha não tiver o caractere que você está comparando, um hora, o loop vai pedir o pop() de uma lista vazia e, então, vai dar erro.
Comment: Vou passar o algoritmo completo pra teste
Comment: Pronto.... tem algumas funções de .Net como o Peek(que bem se não me engano, inclusive, é uma classe extra) que não são nativas do JS, por isso fiz meio que uma gambiarra ali, e preferi trabalhar com `RegEx` pra descobrir se é operando ou operador
Comment: A, e @Sergio valeu pelo toque, corrigi ali a ultima iteração pra concatenar o valor do item
Comment: Equal é usado para comparar objetos enquanto o operador !=
é usado para comparar tipos Primitivos.
Answer: Se você estiver usando o IE ou alguns outros browsers que não implementam corretamente isso, esta expressão não vai funcionar:
 caracter = expressao[i];  // nem sempre funciona

O resultado desta expressão no IE é undefined.
Em Javascript, você deve usar a expressão:
 caracter = expressao.charAt(i); // sempre funciona

Também, invés de construir arrays assim:
 var pilha = new Array; // funciona, mas não é legal...
                        // alguém ainda vai editar e dar um
                        //  new Array(32) ou Array(32, 3) e entender tudo errado!

Faça assim:
 var pilha = []; // funcionar e você pode inicializar tranquilamente!

Quem está acostumado com javascript, a segunda expressão é muito mais simples e legível. Também você verá que é muito comum iniciar arrays em javascript com valores já. Usar a primeira expressão new Array() com parâmetros leva a muitos resultados errôneos, pois a ordem e quantidade de parâmetros usam construtores nada óbvios!
No mais a "tradução" está ok!

Convertendo um algoritmo .NET para JS


Why is hawkeye not allowed to automatically correct a wrong call?

Question: At tennis tournaments with hawkeye, a player is allowed 3 challenges to a call made as to whether a ball was in or not, and losing one challenge each time they are wrong.
I can understand limiting the ability for a player to make a challenge, but every call made is seen on the computer by the hawkeye technicians.
What is the reasoning behind the ATP rules for not allowing hawkeye to interfere whenever a wrong call is made? And moreover, why not scrap linesmen and simply have hawkeye alert the umpire?
Answer: At present the problem with not allowing Hawkeye to automatically correct a wrong call is the cost of installation. Many articles suggest the cost is $60,000-$100,000 per court. The price will go down as the technology improves but it is too high to be installed at every place as of now.
Another thing associated with cost is the likelihood of technical problems or electronics failures, and backups would add on that cost.

There are other issues that make it unlikely that linesmen would be replaced altogether.
Geoff Pollard said "We might have electronics failure," (if that happened) where do you find 350 linesmen at short notice?"

and

Paul Hawkins of Hawkeye Innovations said he believed the ITF was looking only to use the machines for replays of disputed points.
"I think that's what they want," he said. "I think with machines deciding every point it would become too sterile."

Blockquote of Pollard and Hawkins was obtained from The Age article by Richard Hinds in source given below.

As of now only bigger tournaments are able to employed this technology even with backup but that doesn't justify scrapping a linesman altogether. But we can't neglect the idea that this won't happen in future, when price is justified.

Sources used for this answer: The Age, Reuters, USA Today, The Atlantic, Sports Illustrated, The Guardian and rediff.
Comment: I believe you've made it factual and referenced. Personally, I would have expected exactly those factors to be the block: traditionalism and redundancy and cost.
Comment: While this explains what Hawkeye is, it doesn't address the question.
Comment: @Nij changed as much as I could but not sure if it's still sound as opinion.
Comment: @Nij traditionalism is mentioned in many articles but I didn't find a proper way to mention in the answer.
Answer: Well, it seems that your wish will come true in near future. ATP will try a new system with no line referees on NEXTGEN Finals in November. They will have automatic hawkeye to signal any out during the game instantly. Source: tennisproguru.com, or here if you understand Swiss German.


Programmatically add items to the menu - not hook_menu

Question: We're redesigning our site and getting rid of the sidebar. The main reason for the sidebar to exist was to hold Organic Menus (og_menu), which we have hundreds of groups, each with 2 or 3 menus. I want to move OG menus to the main menu.
What I would like to do is when a user visits a particular OG

load the menus for that OG (trivial)
programmatically make the menu's name the top level links linked to # (Trivial - we use bootstrap)
add the menu's links below those top level links (this is where it gets tricky)
and append them to the main menu as the last to links (no clue)

So the top level would look like this only when the user hit the group
Home Communities Forum Group-Menu-1 Group-Menu-2
Home, communities and forum are always there the group menus are appended when they're in that group. I don't need code I just need direction on which parts of the API will facilitate this.
Answer: I solved this by just appending my links to the menu tree with hook_preprocess_menu_tree
<?php

function my_module_preprocess_menu_tree(&$vars) {

  if($vars['theme_hook_original'] != 'menu_tree__primary') {
    return;
  }

  $node = menu_get_object();

  //Check to see if this is a group node or group content and return the group_node
  $group_node = my_module_check_for_group_node($node);

  if($group_node) {

    global $user;

    $vars['tree'] = str_replace('last leaf', 'leaf', $vars['tree']);

    $result = db_query('SELECT menu_name FROM og_menu WHERE gid = :nid ORDER By weight', array(':nid' => $group_node->nid));

    $menus = $result->fetchAll();

    foreach($menus as $menu) {
      $tree = menu_tree($menu->menu_name);

      if(!empty($tree)) {
        // render the organic group menu as HTML
        $tree = drupal_render($tree);

        $tree = str_replace('menu nav', 'dropdown-menu', $tree);

        $menu_array = menu_load($menu->menu_name);

        //format
 and top-level  for bootstrap
        $li = '
'.$menu_array['title'].''.$tree.'
';

        $vars['tree'] .= $li;
      }
    }

    $vars['tree'] .= $li;
 }
 ?>


Como criar um sidebar menu com ícone de hamburger?

Question: Estou começando a usar Intel XDK agora e tenho uma dúvida quanto ao desenvolvimento de menus, gostaria de criar um menu lateral com o ícone de hambúrguer e após abrir o menu, ele se torne um X para fechar.
Segue exemplos:

http://codepen.io/atelierbram/pen/bHlBD
http://callmenick.com/files/2015-02/style2.png

Gostaria de saber se é possível e como devo proceder.
Answer: Olá,
Criei um app no xdk recentemente, nele usei o side bar, mas o sandwich com uma imagem :/
HTML do botão:
<button onclick="openNav()"></button>

HTML do side view

Opções

              Itens salvos por você!
              Pesquisar!

CSS do botão (para manter ele fixo na direita)
.btn-menu{
    font-size: 60px;
    color: #fff;
    width: 100px;
    height: 80px;
    left: 85%;
    position: fixed;
    z-index: 2;
    margin: 30px 10px 0 0;
    border-radius: 200px;
    border: none;
    background-color: #76b72a;
    opacity: 0.6;
    outline: none;
}
.btn-menu:hover{
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.4);
}

CSS do slide menu
.slide-menu{
height: 100%;
    width: 0;
    position: fixed;
    z-index: 5;
    top: 0;
    left: 0;
    background-color: #fff;
    overflow-x: hidden;
    padding-top: 60px;
    transition: 0.3s;
    border-right: 2px solid;
    border-color: #000!important;

}
.slide-menu a{
    padding: 40px 5px 0px 30px;
    text-decoration: none;
    border-bottom: 2px solid;
    font-size: 50px;
    font-family: museosans;
    color: #606060;
    display: block;
    vertical-align: middle;
}
.slide-menu h1{
    padding: 20px 5px 0px 30px;
    font-size: 90px;
    font-family: caviar_dreams;
    color: #000;
    display: block;
}
.slide-menu a:hover, .offcanvas a:focus{
    color: #afafaf;
}

JS
function openNav() { //quando o botão é clicado
    document.getElementById("mySidenav").style.width = "60%";
    document.getElementById("main").style.opacity = "0.2";
}
function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.opacity = "1";

}
document.addEventListener("click", function(){ // quando o user toca na tela ele chama o closeNav e o syde menu volta a posição inicial.
    if ($("#mySidenav").innerWidth() == 0){
       // nothing
    }else{
         closeNav();
    }
});

Espero que te ajude!
basta trocar a img do botao pela animação css que deu de exemplo.


Oracle SEQUENCE.Currval problem in CodeIgniter

Question: I have a sequence named WCOMP_SEQ in oracle to generate auto increment column ON WCOMP table. When I insert a row to WCOMP table in SQLPlus, the row inserted and I can get the auto increment value using
SELECT WCOMP_SEQ.currval FROM dual

But when I ran insert a row using Database Class in CodeIgniter, the row inserted but when I ran the query above to get auto increment value I got Exception:
Exception: Undefined Index currval in E:...

How to fix this?
Comment: BTW.. where do you execute this? In SQL command prompt or within some application? In any case, what is the full ORA error message?
Answer: You can not fetch the SEQUENCE current value without issuing NEXTVAL (see here). So, if you do not want to increment the sequence value (by using NEXTVAL), you should instead query USER_SEQUENCES.
Something like this:
select Sequence_Name
, Last_Number
from user_sequences
where sequence_name = 'WCOMP_SEQ'
/
SEQUENCE_NAME   LAST_NUMBER
-------------   -----------
WCOMP_SEQ                20

Hope this helps.
Answer: In order to get currval on the sequence you will need to have at least one reference to the corresponding nextval for the sequence in the current user session. This is what causes it to set the currval value which would belong to the session.
If you are using it outside, it defeats the purpose which value could it return if there were other sessions active.
Answer: There is a way to get the value automatically assigned to a column: it is the RETURNING clause.
So, here is my sequence:
SQL> select emp_seq.currval from dual
  2  /

   CURRVAL
----------
      8140

SQL>

I'm going to use it in an INSERT statement:
SQL> var seqval number
SQL> insert into emp
  2  (empno, ename, deptno, sal, job)
  3  values
  4      (emp_seq.nextval, 'JELLEMA', 50, 4575, 'PAINTER')
  5  returning empno into :seqval
  6  /

1 row created.

SQL>

I returned the EMPNO into a SQL*Plus variable which I can print, and it has the same value as CURRVAL:
SQL> print :seqval

    SEQVAL
----------
      8141

SQL> select emp_seq.currval from dual
  2  /

   CURRVAL
----------
      8141

SQL>

Your next question is, "does CodeIgniter support the RETURNING sysntax?"  I have no idea, but I suspect it does not.  Most non-Oracle frameworks don't.
There is always the option to wrap the INSERT statement in a stored procedure, but that's an architectural decision whoch many people dislike.


Minimum number of random vectors needed to span a space

Question: I am working with $\mathbb{R}^{nm}$ for some $n,m\geq3$.
What is the minimum number of random vectors I need for them to span $\mathbb{R}^{nm}$ (in terms of $n$ and $m$)?
I'm happy for this to involve any sampling distribution (whichever is more convenient), but Uniform would be preferred.
Comment: Isn't the probability that you pick a hyper coplanar vector $0$, since until the end the hyperplanes in which you pick vectors have measure $0$. Maybe a 3d example will illustrate it better. When you pick your first vector everything's fine, when you pick your second the probability that it is collinear is $0$ since the line has measure $0$ wrt to your volume pdf, then when you pick your third vector the probability is once more $0$ for it to be coplanar with the others, yielding that you'll always get vectors that span the whole space.
Comment: Thanks @lightxbulb, I dont know why I didn't think of that.
Answer: Just so that you can mark it as answered:
Isn't the probability that you pick a hyper coplanar vector 0, since until the end the hyperplanes in which you pick vectors have measure 0. Maybe a 3d example will illustrate it better. When you pick your first vector everything's fine, when you pick your second the probability that it is collinear is 0 since the line has measure 0 wrt to your volume pdf, then when you pick your third vector the probability is once more 0 for it to be coplanar with the others, yielding that you'll always get vectors that span the whole space.
Note that due to machine precision (since you're effectively sampling a discrete probability in a computer) you may get a degenerate basis with a very small probability if you implement this on a computer.


Tirar foto na aplicação android e salvar em uma pasta dentro do projeto (No drawable por exemplo)

Question: Sou novo em programação android e estou desenvolvendo um projeto simples onde o usuário tira uma foto qualquer. Assim que a foto for tirada e o usuário tiver confirmado, queria que salvasse em uma pasta dentro do projeto mesmo (talvez na pasta drawable por exemplo), e salvasse no banco de dados com o nome da imagem para ser usado mais pra frente.
Answer: Até onde eu sei não é possível escrever nada no drawable ou em qualquer outro diretório da aplicação pois fica dentro do APK. O ideal seria salvar esta foto no armazenamento do aparelho. A documentação do android explica como fazer isso.


How to programmatically submit a form that has a file-field using drupal_form_submit()?

Question: I'm working to allow the submission of an existing form via REST using the Services module and drupal_form_submit(). Though this is reasonably routine, the form in question takes a file-upload which is a required field.
To avoid embedding extra logic in the form itself to handle files differently under programmatic submission than under manual submission, is there a trick for getting Drupal to accept a file submitted "headlessly" via REST?
Most of this is not relevant to the answer, but for completeness, here's how I'm set up:
function mymodule_my_resource_create($data) {
    $form_state = array();
    $form_state['values'] = $data + form_state_defaults();
    drupal_form_submit('mymodule_form',$form_state);

    $errors = form_get_errors();
    $status = '200 OK';
    if (!empty($errors)) {
        $status = '400 Bad Request - submission caused errors';
    }
    drupal_add_http_header('status',$status);

    return (object)array(
        'message' => $status,
        'errors' => $errors,
    );
}

function mymodule_form($form,&$form_state) {
    return array(
        'spreadsheet' => array(
            '#type' => 'file',
            '#title' => 'Spreadsheet file',
            // '#required' => 1,
            // ^ there have been issues with this since 4.x...
            // https://www.drupal.org/node/59750
            // so this is done manually in the '#validate' function
        ),
        'reason' => array(
            '#type' => 'textfield',
            '#title' => 'Why file is being submitted',
            '#required' => 1,
        ),
        'submit' => array(
            '#value' => 'Submit',
            '#type' => 'submit',
            '#validate' => array('mymodule_form_validate_upload'),
        ),
    );
}

function mymodule_form_validate_upload($form,&$form_state) {
    if (!isset($_FILES['files']['name'] || !isset($_FILES['files']['name']['spreadsheet'])) {
        form_set_error('spreadsheet','File must be provided');
    }
}

function mymodule_services_resources() {
    return array(
        'my_resource' => array(
            'create' => array(
                'callback' => 'mymodule_my_resource_create'
                'args' => array(
                    'name' => 'post_data',
                    'type' => 'struct',
                    'description' => "Should match contents of $form_state['values'] when submitting through the UI.",
                    'source' => 'data',
                    'optional' => FALSE,
                ),
            ),
        ),
    );
}

function mymodule_actools_plugin_api($owner,$api) {
    if ($owner=='services' && $api=='services') {
        return array(
            'version' => 3,
            'file' => 'mymodule_services.inc',
            'path' => drupal_get_path('module','wos2'),
        );
    }
}

function mymodule_default_services_endpoint() {
    $endpoint = new stdClass();
    $endpoint->disabled = FALSE;
    $endpoint->api_version = 3;
    $endpoint->name = 'my_rest';
    $endpoint->server = 'rest_server';
    $endpoint->path = 'my_rest';
    $endpoint->authentication = array();
    $endpoint->server_settings = array();
    $endpoint->resources = array(
        'my_resource' => array(
            'operations' => array(
                'create' => array(
                    'enabled' => '1',
                ),
            ),
        ),
    );
    $endpoint->debug = 0;
    return array($endpoint);
}

Answer: This wasn't as hard as I expected; Drupal has different handling for fields with '#type' => 'file' as opposed to other types. There are two ways of solving the problem. One is simply adjusting the request-payload, expressed here as a curl command:
curl -i \
    'https://example.com/drupal/my_rest/my_resource' \
    -H 'Accept: application/json' \
    -H 'Content-Type: multipart/form-data' \
    -F "files[spreadsheet]=@my_spreadsheet.xlsx" # note the weird field-name
# This automatically uses the POST method, so Drupal reads it as a 'create'

Drupal munges file-field-names by default apparently apparently to match the file.inc code. This is stated expressly in comments:
if (!isset($element['#name'])) {
    $name = array_shift($element['#parents']);
    $element['#name'] = $name;
    if ($element['#type'] == 'file') {
        // To make it easier to handle $_FILES in file.inc, we place all
        // file fields in the 'files' array. Also, we do not support
        // nested file names.
        $element['#name'] = 'files[' . $element['#name'] . ']';
    }

If you want to API-endpoint users from the implementation shown above, the other solution is to explicitly provide a '#name' value for the file-field in question, as should be obvious:
return array(
        'spreadsheet' => array(
            '#type' => 'file',
            '#name' => 'spreadsheet_file', // <-- adding this prevents name-munging
            '#title' => 'Spreadsheet file',
            // ...

Note of course that the above might have consequences for other sections of code if the file used to be expected under the old name.


Find surrounding element of source iframe in addEventListener

Question: I have a shell page that contains a number of sandboxed iframes.
e.g.

When I receive a message from one of the iframes I'd like to know the parent div (i.e. #sb1 or #sb2).
I have tried the following but it doesn't work:
function receiveMessage(event)
{
  // Follow line results in : Uncaught DOMException: Blocked a frame with origin ...
  var parentDiv = $(event.source).parent();
}

window.addEventListener("message", receiveMessage);

Is there a way to determine the iframe's parent without having to pass an id in the message from the iframe?
Comment: Probably not, seeing as the iframes are blocked by the same-origin policy.
Comment: You can look over the `iframe`'s in the document to find the one with the matching `window` object.
Answer: Lately i needed to know the id of the button that toggled a modal. 'relatedTarget' worked for me, it might work in your case as well.

    function receiveMessage(event)
    {
     var id = event.relatedTarget.id;
    }

    window.addEventListener("message", receiveMessage);
Comment: relatedTarget is not defined for me.
Answer: I was able to get this to work based on "Alexander O'Mara" comment.
function receiveMessage(event)
{
  var parentDiv = $($('iframe').toArray().find(
      function(f) {
        return f.contentWindow === event.source;
      }
    )).parent();
}

window.addEventListener("message", receiveMessage);


Neural network vectorization, no convergence

Question: 2I am trying to implement a fully vectorized neural net following this example Stanford. I am using C# with Math.net numerical library of which the binaries can be downloaded here NuGet. Because the Stanford example is not complete (bias backpropagation and gradient descend missing), I had to try and define these myself from the theory that is linked in the text. As a test I use a simple XOR function that creates input-output sets. In the end I have code that compiles and runs, but it doesn't converge to an answer. It stays at 0.5 for all 4 different input-output sets, so something is wrong.
I am new to Cross Validated. Typically I would post on StackOverflow with a C# tag, but my question is not really a C# question, it's more related to understanding how to implement backpropagation and gradient descent in a vectorized manner.
I am a bit reluctant to dump the whole source code, even though it's a small program (160 lines), so I'll start with the main body. If someone wants to try it I can provide the rest too.
Notations are as per the Stanford example, except that I've used capitals for Matrices. The input X is a matrix of 2 x mSets, where mSets are 4 possible input series of the XOR. W1, W2, b1 and b2 are randomly initialized between 0 and e, where e = 0.01.
I have also tried stacking the biases on top of the inputs to the hidden and export layers, but this creates dimensionality problems in the back-propagation. Or, in other words, I don't know how to do it.
My guess is I have the gradient descent wrong. I am hoping that anyone who has been here before will easily spot my mistakes.
UPDATE: I have solved the problem. There are two main issues, one is fundamental: 1) it is not possible to solve the XOR problem with 2x2x1 network without bias, 2) the other has to do with how to implement the bias. The problem is that by introducing the bias, the dimensions are increased, yet during backpropagation, you need to reduce this dimension again. This is shown in the updated code below: remCol() removes the last column from the matrix.
There are 2 sources that helped me: Stephen Welch has a nice series of videos on Youtube which is very similar to the Stanford code, but does not address bias, however Ryan Harris does! His code is in Python, but in chapter 3 (Youtube) he mentions that it is important not to pass back the bias during backpropagation. That was the trick.
// run the network
for (int i = 0; i < maxIter; i++)
{
    // forward propagation
    Z2 = W1 * X.Stack(b1);                   // add a row of 1's at the bottom for bias
    A2 = Z2.Map(SpecialFunctions.Logistic);
    Z3 = W2 * A2.Stack(b1);
    H = Z3.Map(SpecialFunctions.Logistic);

    // backpropagation
    J = 0.5 * sum(power(Y-H, 2)) / X.RowCount + lambda / 2.0 * (sum(power(W1, 2)) + sum(power(W2, 2)));   // cost function
    delta3 = pointWise(H - Y, Z3.Map(inverseLogistic));                                 // delta output layer
    gradW2 = delta3 * transpose(A2.Stack(b1)) / X.RowCount + lambda * W2;               // grad = partial derivatives, divide by X.Rowcount for scaling and add regularization term
    delta2 = pointWise(transpose(remCol(W2, nHid)) * delta3, Z2.Map(inverseLogistic));     // delta hidden layer, remove last column from matrix (bias)
    gradW1 = delta2 * transpose(X.Stack(b1)) / X.RowCount + lambda * W1;

    // gradient descent
    W1 -= alpha * gradW1;
    W2 -= alpha * gradW2;

    if (i % 100 == 0)
        Console.WriteLine("Error J " + J.ToString("E4"));
}

Comment: If you have figured out how your problem is solved, consider a full, documented answer by yourself (and accept it, to visualize this for other users - otherwise all people treat this question as unanswered (unless they read your edit)). Another thing: since we're not on stack overflow here, consider supplying pseudocode rather than real code. As you said, your problem was not code related but a semantical one.
Comment: Good point, I did answer my own question and marked it as answered, but it was deleted by whuber, here's the quote:

Updated post with explanation how problem was solved and updated code.
shareeditundeleteflag
deleted by whuber♦ Feb 4 at 20:30
Why was your post deleted? See the help center.
Comment: Maybe your answer was too specific, too "cryptic", too short or just not correct? However, I've added a general explanation for vectorized feedforward activation and backpropagation. I hope this helps you and future readers of your post to clarify any misconception with the vectorized concepts.
Answer: I do not get why you say your bias is increasing your dimensions so I am supplying a general answer although you mentioned you already have solved your problem (but not delivered a clear answer yourself?!).
Therefore I've added a general explanation for network architecture and vectorized feedforward activation as well as vectorized backpropagation. I hope this helps you and future readers of your post to clarify any misconception with the vectorized concepts

Architecture:
Most implementations I know (including my own one's) implement the bias via a vector $\vec{b}$ with the same dimension of the corresponding layer. So if layer $l_1$ has, e.g., 10 neurons then your bias vector $\vec{b_1}$ would have a dimension of $(1, 10)$: 1 row and 10 columns - a flattened 10D vector. Input layer $x$ and output layer $y$ normally are not "counted", just the hidden layers get an enumeration.
If you have an XOR-Solver you would end up with a dimension of (1, 2) for $x$, one hidden layer $l_1$ with (1, 10) in our example and a scalar or (1, 1) / 1D vector (based upon your implementation) for $y$.
Totally your network would have 2 input neurons, 10 hidden neurons, 1 output neurons and 10 bias neurons for your hidden layer.
Your weight matrices would be of dimension $(2, 10)$ for $W_{1}^{x}$ between layer 1 and input layer as well as $(10, 1)$ for $W_{y}^{1}$ between the output layer and layer 1. Weight matrices always have a dimension of (input_size, layer_size).

Vectorized feedforward activation:
The output vector $\vec{s}$ of one layer $i$ would be the activation vector $\vec{h}$ of this layer "normalized" by a transfer function $\varphi$. In your setup $\varphi$ is the logistic/sigmoid function. $\vec{h}$ is the current layer's weight matrix $W_{i}^{i-1}$ multiplied with the output vector $\vec{s}_{i-1}$ of the parent layer (layer $i-1$). After this the bias vector $\vec{b_i}$ is added. So for an arbitrary layer $i$ you get the following vectorized feedforward calculation:
$\vec{s}_{i}(\vec{h}_{i}) = \varphi(\vec{h}_{i}) = \varphi(W_{i}^{i-1} * \vec{s}_{i-1} + \vec{b}_i)$
As you can see, no altering of the dimensionality is needed. The bias vector is simply added.

Vectorized backpropagation:
The error on the output layer $y$ is usually calculated via:
$\delta_{y} = \varphi'(\vec{h}_{y}) * (\vec{y}_{teach} - \vec{y}_{out})$
This is often altered to (see: l1 / l2 loss for absolute and squared error functions):
$\delta_{y} = \left|\vec{y}_{teach} - \vec{y}_{out}\right|\quad$ or $\quad\delta_{y} = (\vec{y}_{teach} - \vec{y}_{out})^2$
Less common in basic MLPs but also very efficient is the cross entropy (see: cross entropy):
$\delta_{y} = -\bigl(\vec{y}_{teach} * log(\vec{y}_{out}) + (1 - \vec{y}_{teach}) * log(1 - \vec{y}_{out})\bigr)$
For backpropagating this error you alter your weights and bias by:
$\Delta W_i^{i-1} = \epsilon * \delta_{i} * \vec{s}_{i-1}$
$\Delta \vec{b}_i = \epsilon * \delta_{i}$
Where $\epsilon$ is your learning rate which is typically something in the interval [0.0001, 0.01] - based on your problem, network architecture, ...
So basically you calculate the error on the last layer, alter its weight matrix and bias by some delta ($\Delta W_i^{i-1}$ and $\Delta \vec{b}_i$) and propagate this until you reach the first layer.


Is a policy $\pi(s)$ on Markov decision process a random variable?

Question: Citing Wikipedia:

The goal in a Markov decision process is to find a good "policy" for
the decision maker: a function $\pi$  that specifies the action
$\pi(s)$ that the decision maker will choose when in state $s$.   Once
a Markov decision process is combined with a policy in this way, this
fixes the action for each state and the resulting combination behaves
like a Markov chain (since the action chosen in state $s$ is
completely determined by $\pi(s)$ and $\Pr(s_{t+1}=s'\mid
> s_{t}=s,a_{t}=a)$ $\Pr(s_{t+1}=s'\mid s_{t}=s,a_{t}=a)$   reduces to
$Pr(s_{t+1}=s'\mid s_{t}=s)$ $Pr(s_{t+1}=s'\mid s_{t}=s)$, a Markov
transition matrix).

A policy that maximizes the function above is called an optimal policy and is usually denoted $\pi^*$. A particular MDP may have multiple distinct optimal policies. Because of the Markov property, it can be shown that the optimal policy is a function of the current state, as assumed above.
Can the policy be considered a random variable?
Comment: The answer is in the question: "the optimal policy is a function of the current state".
Comment: A function of a random variable is a random variable?
Answer: The policy is a function you define to act in an environment, it's not a random variable.


Degree of maps on the sphere

Question: Given a map $f:B^n \to S^n$, where $B^n$ is the unit ball and $S^n$ is the unit sphere, is it true that the degree of $f|_{S^n}$ is always 0, where $f_{S^n}$ is the restriction of $f$ to $S^n$? If so, why?
Thanks!
Comment: Do you perhaps want that $f$ is continuous? And also, just by way of clarification: is $S^n$ the boundary of $B^n$ (I personally would write it $S^{n-1}$, but it is just a matter of convention...)
Comment: It's not *just* convention, the superscripts denote the dimension of the manifold!  Which makes it really, really confusing to write anything besides $\partial(B^n)=S^{n-1}$...
Comment: Yes for both questions,
Answer: This is just a bit more of an explanation of Mariano's answer:
The homotopy class of a map between spheres of the same dimension is completely determined by its degree, that is, two maps $f,g: S^n \to S^n$ are homotopic if and only if they have the same degree. Now you can compute, using which ever definition you like, that the degree of the constant map is 0. A map out of a sphere is null homotopic, ie. homotopic to a constant map, if and only if it can be extended to a map of the whole unit ball. Since the map in question, $f|_{S^n}$, can indeed be extended to a map on the whole unit ball, namely $f$, it must be null homotopic. So by the above it must have the same degree as the constant map.
Again, this is just an elaboration of Mariano's answer.
Answer: The degree is zero because the restriction of $f$ to the boundary of $B^n$ (which most humans write $S^{n-1}$! :) ) is homotopic to to a constant map.

Degree of maps on the sphere


Is there a proof of the spherical law of sines?

Question: I know that the spherical law of sines is $\frac{\sin A}{\sin a}=\frac{\sin B}{\sin b}=\frac{\sin C}{\sin c}$ but how does one prove this rule?
Comment: No, it is an unsolved conjecture ...
Comment: @Henry There better be, otherwise is not a "law" but at best "A good shot" or a "What are the odd this time it won't work?" guess
Comment: You can see here: http://isites.harvard.edu/fs/docs/icb.topic246919.files/March-07.pdf
Comment: Thanks @EmilioNovati, that's perfect
Answer: Choose a coordinate system so that the three vertices of the spherical triangle is located at
$$(1,0,0),\quad (\cos a,\sin a,0)\quad\text{ and }\quad(\cos b, \sin b\cos C, \sin b\sin C)$$
The volume of the tetrahedron formed from these 3 vertices and the origin is  $\frac16 \sin a\sin b\sin C$. Since this volume is invariant under cyclic relabeling of the sides and angles, we have
$$\sin a\sin b\sin C = \sin b\sin c\sin A = \sin c \sin a \sin B
\implies\frac{\sin A}{\sin a} = \frac{\sin B}{\sin b} = \frac{\sin C}{\sin c}$$
Comment: Hi, but the above has no known geometrical meaning.


I broke my terminal trying to set up PATH environment to bin the JAVA directory and now nothing works, no bash commands, etc. Can I reset?

Question: Basically I was just trying to set up a PATH environment variable that pointed to the /bin directory inside the main Java directory.
I did this by doing: sudo nano /etc/paths.
But then couldn't get the path to save so got frustrated and just did some keyboard bashing... Which then closed the sudo nano path.
And now nothing is working. No bash commands, etc. I have tried restarting several times and every time I open terminal I get the following message:
Last login: Tue Jan 7 08:41:08 on ttys000
Fatal Python error: initfsencoding: unable to load the file system codec
LookupError: no codec search functions registered: can't find encoding
using OSX on Maxbook
Please help..
Comment: You can use absolute paths, when you execute commands: `/usr/bin/sudo /usr/bin/nano /etc/paths`.
Answer: Not knowing anything about the content of your /etc/paths file I would suggest you locate a known-good /etc/paths file (from a working Mac I suppose) and re-edit yours to match.  If that works you can again attempt to make the change you need if editing your /etc/paths file is really the best solution for doing so.
(My Ubuntu machine has no /etc/paths file so that could be unique to Mac or due to the fact that Mac uses a very old bash or... )
My Mac /etc/paths:
$ cat /etc/paths
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin

(Also, to save in nano it's ctrl-o (write Out) and to quit is ctrl-x.  You will want to sudo nano /etc/paths or you won't be able to save.)


Is the dominant tone of a major scale halfway in frequency between the tonic and octave?

Question: Is the dominant tone of a major scale halfway in frequency between the tonic and octave?
If so is this why it functions as it does? ... because it's sounds less dissonant to the tonic?
Answer: Yes, that is true†. For instance,

A3: 220 Hz
A4: 440 Hz
E4: 330 Hz ≡ (220 Hz + 440 Hz)/2 ‡

I don't think however that this can satisfyingly explain why a dominant acts, well, dominant.

The Ⅴ tone itself is actually contained in the tonic triad as well, and there it clearly does not evoke any urge to resolve it to the Ⅰ or somewhere else. In fact I daresay because it is so consonant, it does not act as a dominant...
...unless you add extra leading tones. A dominant chord contains at least a (high-intonated) third, which leads up to the tonic's octave. It very often also contains the 7 (sometimes "dominant chord" and "dominant-seventh chord" are considered synonyms!), and that's a dissonance which strongly suggests resolving it.
That effect still works when the Ⅴ tone is not even part of the chord, as exemplified by diminished seventh chords.

†At least in an analytic sense. As Dave remarks, our ears actually perceive pitch rather logarithmically than linearly, and on a logarithmic scale the Ⅴ is further that half-way between the Ⅰ and its octave.
‡The 330 Hz figure is derived from just intonation, i.e. a Pythagorean fifth. JI is the conceptual underpinning of pretty much all Western harmony prior to atonality. Many instruments approximate JI with the 12-edo tuning system, in which the fifth is defined as 27⁄12 instead of 3⁄2; that comes out to almost exactly the same: the 12-edo E4 is 329.628 Hz, i.e. within 0.5 Hz of 330 Hz. This difference can pretty much only be noticed when superimposing both frequencies over a time of multiple seconds and listening to the beat, but not when listening to the tones in succession. Thus, for the question of whether the fifth lies in the middle of the octave, it is irrelevant whether we're talking about the JI or 12-edo fifth.
Comment: @RandyZeitman That is because a major second is a much more complicated relationship than the simple fifth. Because of (I'm assuming) wave cancellations, two notes (say C and D) generate a beat ( especially audible for a minor second), which is usually interpreted as dissonance.
Comment: It just seems to be that when I strike a I and then V they are simply not dissonant whereas the I & II are far more.
WWWH
Comment: @leftaroundabout- what do you mean by a "high-intonated" third?  I find the resolution of a just dominant chord to its tonic- say 12/15/18 to 8/16/20, to be just as convincing, and with less cringeworthy dissonance.  But maybe that's just me....
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/108065/discussion-on-answer-by-leftaroundabout-is-the-dominant-tone-of-a-major-scale-ha).
Answer: I'll just provide some historical context to this question, particularly why the "dominant" note first became prominent in scales.  It has to do somewhat with the idea of a "halfway point," but it's a bit more involved.
Let's go back to ancient Greece and the Pythagoreans.  They loved math, and the created the mathematics of proportions partly to create music theory.  They also came up with several ways of measuring the average (sort of halfway point) between two numbers.  The three primary ways are still known as the Pythagorean means.
Suppose you have a string that is 12 units long and divide it in half.  If you pluck the 6-unit length and then the whole 12-unit string, they will sound an octave apart, with the longer string having twice the length and thus half the frequency.  (The Greeks had no way of measuring frequency directly, so they could only deal in lengths of strings.)
Okay, let's say you want to find a halfway point or a "middle"/mean between these two notes and their string lengths.  The Pythagorean means gave three possibilities:

The arithmetic mean.  This is what we now usually think of as "average," where you simply add the two numbers together and divide by 2.  In this case, you do (12+6)/2 and end up with 9.  (I should note in all of these cases, I'm explaining a modern algebraic method of calculating the means; the Greeks had more intuitive ways of saying how the numbers related to each other that would be more complicated to explain here.)
That creates a perfect fourth above the lowest note (12:9 = 4:3) and a perfect fifth between the middle note and the high note (9:6 = 3:2).
The harmonic mean.  To the Greeks, this was often the key one for musical intervals (hence the term "harmonic" which is still used in math today).  In this case, you take the reciprocals of the two numbers, find their average, and then take the reciprocal again.  So, in this case, [(12-1+6-1)/2]-1.  That gives the number 8, which creates a perfect fifth above the bottom note (12:8 = 3:2) and a perfect fourth between the two upper notes (8:6 = 4:3).  This is, in some ways, the earliest origins of the concept of a dominant note as an important step or interval placed within the scale.
The geometric mean.  In most cases, the Pythagoreans didn't like this one.  In modern mathematical terms, you multiply the two numbers and take the square root.  Hence, here you get sqrt[12*6] = 6*sqrt(2), which is roughly 8.485.  To the Pythagoreans, this number didn't really exist -- it was literally irrational.  But some ancient mathematicians saw the musical utility of this type of mean or halfway point, literally dividing the interval into two equal intervals.  In modern terms, this would divide the octave into two tritones.

With modern frequency ratios, the means work a bit backwards from what they do with string lengths.  Thus, the arithmetic means of two frequencies an octave apart will locate the dominant, while the harmonic mean locates the perfect fourth above the bottom note.  (The answer to the question in the title is therefore YES, the dominant is the arithmetic mean of frequencies.)  Still, they essentially serve as two types of "means" (i.e., middles) between the end notes in an interval.  The geometric mean of frequencies still creates a tritone.
Fast-forward about 1500 years.  Medieval music theorists loved classifying scales for chants, and they recognized this structure established by the ancient Greeks building up fifths and fourths using the various means.  Thus, octaves were classified using "species" that generally divided them up into fifths and fourths.  The note a fifth or fourth above the final (the final being a kind of "home note") in chants was frequently given special importance.  In earlier theory, it was sometimes given the name tenor (from the Latin tenere -- "to hold"), as it was a note that tended to be emphasized and held on to in contrast to the final note.  Later, these notes eventually came to be known as dominant, and eventually in the 18th century they were split into two categories: the dominant (perfect fifth) and subdominant (perfect fourth above tonic).  (I'm skipping over a lot of details here.)
By that point, the dominant note had also acquired harmonic functions too beyond its critical role in scale construction and melodies.  In particular, it served as a stable harmony to leading tones, which had come into prominence for resolutions at cadences in medieval times.  This is probably why the fifth overcame the fourth and became the "dominant" note in music theory.
However, the ultimate reason why that note was originally placed in scales and was given prominence does date back to the ancient concept of "means" and the various ways to locate a sort of halfway point within an octave when tuning intervals on strings.
(Note about tuning, as there are some comments recently about this: the question doesn't specify JI vs. ET, so I'm not even going to go down that road of discussion here.  Historically, the dominant concept emerged by reference to JI.  ET fifths are so close that they are practically indistinguishable in most circumstances.)
Comment: I respectfully disagree.
Comment: @hft: I probably shouldn't ask, but *what* do you disagree with?  Comments on SE are supposed to contribute positively toward improving answers.  See guidelines [here](https://meta.stackexchange.com/q/19756/627435).
Comment: I disagree that the answer to the question is "yes." I think the answer is "no."
Answer: In one way you could say that a perfect fifth is halfway between root and octave. The relationship in frequency is 3:2, which is equivalent to 1.5:1. At first glance this looks like halfway. This is a very simple and consonant interval. But it doesn't quite hold. Two perfect fifths is not an octave, but a ninth! The true halfway interval is the tritone/augmented fourth/diminished fifth as two of them stacked equal an octave. Mathematically, in equal temperament the relationship of a tritone is 2^(1/2):1, or approximately 1.415:1 . Here you already see that by taking the square of it you get 2, which is the frequency relationship of an octave. No, it's not that beautiful sounding, at least not in western culture. It is what it is.
Comment: The OP asked specifically about the interval "halfway in frequency," not the "halfway interval".
Comment: The relationship is not 3:2 it is 2^(7/12):1.
Comment: @AlexBasson he didn't. He asked about the "dominant tone"
Comment: @mkormanThe original question is "Is the dominant tone of a major scale halfway in frequency between the tonic and octave?", and not "Which interval is halfway between the tonic and octave?", which is the question this post answers.
Answer: There is a sense in which the equal tempered (ET) augmented 4th or diminished 5th is the "middle" of the octave.  Note how on a piano keyboard if you move up 6 semitones, and then move up 6 more, you'll get to the key that is an octave above your starting point.  This has to do with the fact that we perceive pitch differences logarithmically.  In a perceptual sense, the relationship between A2 and D#2 is the same as the relationship between D#2  and A3 (in equal temperament), while the the interval from A2 to E2 is perceptually distinct from the interval between E2 and A3.
Comment: And halfway arithmetically between a note and 2 octaves above is the third in the top octave eg C2 to C4 average to E3.
Answer: The dominant is not "halfway" between the tonic and the octave in "equal temperament" tuning. Here, by "not halfway" I mean that the frequency of the dominant is not 3/2 times the frequency of the tonic (in "equal temperament" tuning). If it were truly "halfway" then the ratio of the dominant to the tonic frequency would be 3/2 and the "cycle of fifths" would never repeat (but it does repeat after 12 fifths: C, G, D, A, E, B, F#, C#, G#, D#, A#, F, C).
In modern western music the "equal temperament" choice was made that the "half step" interval was to be obtained from the note below by multiplying the frequency below by a factor of 2 raised to the power (1/12). Thus after 12 half steps the octave is reached. Since the dominant is 7 half steps above the tonic, the ratio of the dominant frequency to the tonic frequency is 2 raised to the power (7/12). Note that 2 raised to the power (7/12) is 1.498307..., which is approximately 3/2, but not exactly.
For example, A3 = 220Hz, E4 = 329.6275561...Hz, A4 = 440Hz.
For more details, see the paper here.

Note that the exactness of the numbers given (e.g., 329.6275561...Hz given to 7 decimal places) does not really apply to any physical instrument, since there will always be tuning errors for any physical instrument. For example, an accredited piano tuner must be able to tune a note to within one hundredth of a half step of the tuning fork (A.K.A. "one cent," which is approximately 0.075 Hz at C below middle C and approximately 0.185Hz at E below concert A). While the difference we are arguing about is fairly small it is still about two cents, so a piano tuner should be able to tell the difference--Unfortunately, I don't know any piano tuners I can ask about this, but would be interested to hear from them.
Furthermore, any physical instrument produces a spectrum of frequencies and the peak at the fundamental frequency has an instrument- and environment-dependent width that further complicates any ultra-precise tuning to "one frequency."

These additional comments I added mostly to point out that I'm not addressing physical instruments, nor realistic tuning scenarios, and I've not said anything about how the ear perceives notes (which since the ears is also a physical analog object will also depend on a further full-spectrum response function of the ear).
Rather, my comments apply to the mathematical theory only. And my point is nothing more than the fact that:

Let X be any frequency (e.g. the "tonic")
Let Y = X * ( (3/2)**6 ) * ( (3/4)**6 )
Y is not equal to X (but is close to X)
The above Y is generated by progressing through the entire circle of fifths assuming that every fifth is always 3/2 times the tonic (and mapping back to a single octave).
If one progresses through the circle of fifths (mapping back to a single octave) then after twelve steps one should arrive back at the same value.
"5" above is incompatible with every fifth always being 3/2 times the tonic.

Thus the "circle of fifths" is incompatible with the fifth being 3/2 times the tonic, in general.
This in not really a problem in practice because of the properties of physical objects (some of which are discussed above). But, nevertheless, for a mathematical theory of music this is an annoyance and it is annoying enough for me to prefer to say that the fifth is not 3/2 times the tonic. So, in this context, I would not say that the fifth is "halfway" between the tonic and the octave. Or, to put it another way, I would not say that every fifth is exactly halfway between the tonic and the octave.
Comment: The question was"halfway in frequency".
Comment: Sorry, I attached my comment to the wrong answer. :(  Although I do think that the distinction between 1/2 and 2^(7/12) is restricted to keyboards. Violinists and wind players get it right, especially when they are playing within chords.
Comment: People still use just tuning and the functional value of the V existed long before the 12-th root of 2 was applied.  This is a poor answer.
Comment: I'm not sure what you mean by your comment.
Comment: People may still use just tuning and people may still use Pythagorean tuning and people may still use mean-tone temperament... but so what? The commonly known tuning in our day is the 12 tone equally spaced tuning.
Comment: The question asked was about the major scale. I consider the major scale to be composed of whole steps and half steps where the half steps are 2**(1/12) above prior frequency. I consider this to be the most applicable and reasonable interpretation of what the OP means when he asks about the major scale. If he means something else then I would argue he should have explained since the ordinary meaning of the major scale is how I have explained it. Given this meaning to the OP's question I believe that the answer that I critiqued as being "flat out wrong" *is* wrong.
Comment: I'd argue that the answer I've given is correct in the context I have just explained. You may consider it to be a "poor answer" in some other context (per your current fancy). But, in the context I've just described, my answer is clearly correct. There is a chat about this that was created based on the OP question comments if you care to read more.
Answer: As for the numerical reasons, the other comments have answered.
As for the function of the dominant, as a triad from the scale degree V, the tones contribute to create a strong "leading" force to the tonic...
Example in the key of C:
Root of the dominant is G, which pulls toward the tonic, not due to the individual harmonic relationship, as the G is contained in the C tonic, and as noted by the above answers, is very consonant due to it's ratio. However, the pull is created by the expectation of music listeners, due to its historic and massively-present frequency in all of Western music. The note is pulled not due to instability, but due to the listener's expectation only.
Third of the dominant is B, which is very unstable, collapses on the tonic as it is the nearest note (B->C is a half step), and strongest dissonant-consonant relationship in proximity (Maj 7th -> Unison). [Note that the root of the vii chord also exhibits this relationship, but it is tempered by the function of the B as root of the vii chord.]
Fifth of the dominant is D, which is a peculiar case. The D is an equal distance between the C and the E, so resolution to either would require the same distance. However, when given the choice between a completely consonant resolution (D->C) and a partially consonant resolution (D->E), it requires less force, and resolves more dissonance in the D->C motion. Also, the symmetric movement to the B->C contributes to a less forceful resolution, adding to more consonance. Along with these functional reasons, the historic reason mentioned in the discussion of the root note also applies.
Given the above voice-leading and historic (expectation) reasons, the dominant chord continues to function (and strengthen) in its role as the precursor to resolution to the tonic.
Answer: Rand Zeitman,
It would help if you defined what you meant be "half way".  In terms of linear distance we can generalize one of the answers.
f_1/2 = (f1 + f2)/2 = (f1 + 2*f1)/2 = 3*f1/2
This matches the definition of the V in Just tuning.  This is also commensurate with one of the natural harmonics of a linear vibrating string or resonance tube with fixed node at the ends as boundary conditions.  The n = 3 harmonic is an octave and a 5th above the fundamental.  It is this fact that may have a stronger influence on the importance of the V in western music.  The notes in a "perfect" interval share more harmonics than any other and this is what contributes to the perception of dissonance versus consonance from a physic based analysis.  This was determined by Herman Helmholtz in the late 1800s and written about in his text "On the Sensation of Tone" which is still available.  Beware that he discusses the variation of the speed of light relative to moving observers (Einstein hadn't produced his work at this point in time).  According to the theory (a water down version) when two notes are played together and share overtones these overtones support each other and do not conflict.  When the overtones do not match we hear a "beating" between them.  Other phenomenon contribute to this.  One is the ability to distinguish two pitches versus hearing a combined pitch with beats.  Intervals that are judged dissonant have overtones that not only do not match but are close enough to create this interference.  It is postulated that this is what causes dissonance.  The degree of dissonance is to some extent related to the density of non-matching overtones that fall within a "critical band" for pitch discrimination.  You might think that this can be removed by removing harmonics but you cannot to this in theory or practice because the human ear is non-linear and creates harmonics when excited.  So, in some sense we have evolved to hear and distinguish these two characters, dissonance and consonance.  I cannot say what evolutionary benefit it serves.
In my honest opinion the theory is somewhat flawed.  The physics is indisputably true but the attempt to use physics to decide once and for all what is judged as pleasant versus unpleasant is infused with ethnocentric bias.  We knew the answer we wanted before the analysis was applied.
On to other definitions of "half way".  With the development of 12TET tuning the perfect 5th, 3/2, disappeared and is replaced with a measure of 7 half steps, f = (2)^(7/12)*f1.  This is close enough to 3/2 to serve its purpose (1.5 compared to ~1.498...).  Whether or not this can be heard depends on the sensitivity of the human system.  Some people claim to be able to hear this.  As for resonances in musical instruments and beating inside the human ear?  Well, all systems have damping and that broadens the response curve.  So it is possible for 1.498 to trigger all the same sympathetic resonance as 1.5 and I know very little about the human ear other than a few basic facts so I do not know if it and/or the brain is sensitive enough to hear the diff.  However it is not an even division of the octave into steps.  12 1/2 steps make an octave and the 5th is at 7.  The flat 5 is at 6, a perfect split of the octave in to equal ratios (we typically describe frequency relations as ratios and not diffs).  This has earned the dim 5th the title of the perfectly symmetric interval in some circles.  It was also banned by the church for a while.
To get to an answer to your original question perhaps no one is qualified to answer.  Whatever music is now has developed over 1000s of years and your question is kind of a chicken versus egg question.  Is this relationship what makes the V functionally important?  To some extent perhaps it does.  Perhaps the fact that we are programmed to hear dissonance and consonance and even create it in our own ears and that vibrating systems have a naturally occurring harmonic at what we now call the V is significant.  Perhaps that is why we give so much significance to V.  However not all cultures do this.  For your question to be fair I think you should investigate eastern music, African, and other cultural music and see if the same choices have been made.  It might that from a global perspective the importance of the V is a red herring even if there are physics based reasons to favor it.
Answer: Not sure exactly what do you mean by halfway in frequency, but yes you can expect a dominant 7 to have a ~150% frequency of the tonic.
On the other hand, an octave above the tonic is ~200% of the original tonic frequency.
This relationship is also precisely the reason why an octave or dominant 7 sounds so consonant because the sound waves for both notes fit predictably.
As to the tone that is exactly halfway from the tonic to its next octave (in terms of tone not frequency), it would be the tritone. Both are 6 intervals away from each other.
The reason why tritones, although they have the same intervals but don't have the same frequency between the tonic and octave, was due to the non-linearity of growth in wavelengths. Remember the frequency doubles at every octave, the lower you are at the key, the less increase in the frequency of the next.


Can't bind to 'timetable' since it isn't a known property of 'app-timetable'

Question: this is my student-profile.component.html
enter image description here
this is my timetable.component.ts
enter image description here
this is my student-profile.ts enter image description here
ERROR->
enter image description here
After trying every possible way to debug this error, i am still getting the same error.
I have a file, data.json file and i wanted to output that data to my html page but not able to show the ouput of the json file on the webpage but still getting the output in my VSCODE console.
Comment: providing images will not help and will suffer with down votes so please provide [minimal-reproducible-example](https://stackoverflow.com/help/minimal-reproducible-example)  and go through [why-should-i-not-upload-images-of-code-data-errors](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors)
Answer: When you use a component (TimetableComponent)app-timetable in you standalone components HTML, then you need to add it to the imports array of StudentProfileComponent
...
@Component({
  ...
  standalone: true,
  imports: [RouterOutlet, TimetableComponent],
  ...
})
export class StudentProfileComponent {
    ...


On the sum of random coin flips

Question: If I toss a (fair) coin $N$ times, I expect to see an excess of tails/heads by roughly $\sqrt{N}$. Is this true? If yes, according to what theorem? If no, is there a way to quantify a bound for such possible excess?
(linked)
Comment: Relevant: [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution) and [central limit theorem](https://en.wikipedia.org/wiki/Central_limit_theorem).
Comment: $\sqrt{N}$ is not a bound, but instead the standard deviation of the distribution of the signed  difference between Head and Tails.  The bounds are $\pm N$, and the most likely signed difference is $0$ or $\pm1$ depending on whether you have an even or odd number of tosses.  These change with absolute differences, but the expected value is about $\sqrt{\dfrac{2N}{\pi}}$ for large $N$, and the most likely values are $2$ or $1$ depending on parity.
Comment: This also falls under the rubric of a 1D balanced random walk.
Comment: Is it the Law of Iterated Logarithm? $S_N\approx\sqrt{N\ln(\ln N))}$?
Answer: Number of heads when tossing a coin $N$ times is a binomial random variable, $\sim B(N,p)$. The variance of a binomial is $Npq, q=1-p$. Given a coin is fair, $p=q=1/2$, the expected  value of (absolute) difference of heads and tails is 2 standard deviations, it is $$2 \sqrt{N/4}=\sqrt{N}$$
So you are correct.

On the sum of random coin flips


Perdi Conexion MV desdpues de restablecer Firewall de windows

Question: hola buenas tardes quisiera ver si alguien me ayuda pues he perdido conexion con mi instancia por Escritorio remoto despues de restablecer el firewall, ya no me puedo conectar, lo mismo me paso cuando le instale un antivirus. que fue kaspersky y tuve que hacer la instancia de nuevo favor si me pudiecen ayudar a poder retomar el control de la maquina sin la necesidad de eliminarla y crearla de nuevo se los agradeceria muchas gracias.
Answer: hola buenas tardes quisiera ver si alguien me ayuda pues he perdido conexion con mi instancia por Escritorio remoto despues de restablecer el firewall, ya no me puedo conectar, lo mismo me paso cuando le instale un antivirus. que fue kaspersky y tuve que hacer la instancia de nuevo favor si me pudiecen ayudar a poder retomar el control de la maquina sin la necesidad de eliminarla y crearla de nuevo se los agradeceria muchas gracias.


Subring of a finitely generated Noetherian ring need not be Noetherian?

Question: A common example showing that a subring of a Noetherian ring is not necessarily Noetherian is to take a polynomial ring over a field $k$ in infinitely many indeterminates, $k[x_1,x_2,\dots]$. The quotient field is then obviously Noetherian, but the subring $k[x_1,x_2,\dots]$ is not since there is an infinite ascending chain of ideals which never stabilizes.

Is there an instance of a finitely generated Noetherian ring over some ground ring $R$, that has an intermediate ring which is not finitely generated over $R$, and hence not Noetherian either?
Comment: In last sentence, I think that "hence not Noetherian either " doesn't make sense ,,because Noetherian property should be checked over itself ring. (not over $R$)
Comment: This is answered by [Mariano's answer here](http://math.stackexchange.com/questions/105164/are-intermediate-rings-of-finite-ring-extensions-also-finitely-generated/105218#105218). That question did not have a Noetherian condition, but it's clearly satisfied in the example.
Comment: Oh yeah, Hilbert's basis theorem shows the Noetherian condition. Should I delete this somehow?
Comment: I actually don't know what the interface for asking questions is like, but if you want to then that seems fine: no one has written an answer, or anything.
Comment: By Eakin - Nagata theorem, converse is true.
Answer: To get this question off the unanswered list, I copy Mariano's example from here.
The polynomial ring $k[x,y]$ is Noetherian (by Hilbert's basis theorem), but the subring generated by $\{xy^i:i\geq0\}$ is not finitely generated over $k$.
Comment: Nice, simple example.


WCF Data Services GUI performance and filtering with ICollectionView

Question: I have simple test (WPF - MVVM) client (for WCF oData service) app:
ViewModel
public class MainViewModel : ViewModelBase
{
    private MyEntities context;

    public ICollectionView Collection { get; private set; }

    private string searchString = "";
    public string SearchString
    {
        get { return searchString; }
        set
        {
            searchString = value;
            Collection.Refresh();
        }
    }

    public MainViewModel()
    {
        context = new MyEntities(new Uri("http://localhost:3780/Live.svc"));

        Collection = new CollectionView(context.Clients);
        //Collection = new CollectionView(context.Clients.ToArray());

        Collection.Filter = (o) => (o as Client).FullName.ToString().StartsWith(SearchString);
    }
}

and View

<ListBox ItemsSource="{Binding Collection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding FullName}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

<TextBox Grid.Row="1" Text="{Binding SearchString, UpdateSourceTrigger=PropertyChanged}" />

I have two questions:

Why the movement of the ListBox slider slows down S_O___M_U_C_H (I
have only 40 clients in the collection)?
Why, if I change this
Collection = new CollectionView(context.Clients);

to this
Collection = new CollectionView(context.Clients.ToArray());

so to break "connection" with the context through IEnumerable shell
(it helps with UI performance problems) - stops working filtering! I
do not understand why the disconnection of the collection from data
context damage the filtering...

So, my final question is - is it possible to avoid GUI performance problems and at the same time implement filtering? And if so, how?
Any suggestions are welcome!
Answer: Ok, guys, I solved my problem. I should just pay attention to the message In the VS Output window:
Using CollectionView directly is not fully supported.  The basic features work, although with some inefficiencies, but advanced features may encounter known bugs.  Consider using a derived class to avoid these problems.
The solution was simple:
I changed this
Collection = new CollectionView(context.Clients);

to this
Collection = new ListCollectionView(context.Clients.ToList());

and then there are no GUI performance problems and filtering works as expected!
The result code was:
ViewModel:
public class MainViewModel : ViewModelBase
{
    private MyEntities context;

    public ICollectionView Collection { get; private set; }

    private string searchString = "";
    public string SearchString
    {
        get { return searchString; }
        set
        {
            searchString = value;
            Collection.Refresh();
        }
    }

    public MainViewModel()
    {
        context = new MyEntities(new Uri("http://localhost:3780/Live.svc"));

        Collection = new ListCollectionView(context.Clients.ToList());

        Collection.Filter = (o) => (o as Client).FullName.ToString().StartsWith(SearchString);
    }
}

and View:
<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <ListBox ItemsSource="{Binding Collection}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding FullName}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <TextBox Grid.Row="1" Text="{Binding SearchString, UpdateSourceTrigger=PropertyChanged}" />
</Grid>

WCF Data Service:
public static void InitializeService(DataServiceConfiguration config)
{
    config.SetEntitySetAccessRule("*", EntitySetRights.All);
    config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

    config.UseVerboseErrors = true;
}

Comment: That's not at all what I'd have expected - is it a code base you can share?
Comment: @MarkStafford-MSFT I added a little more code. Now better? :)


Return the datatype of a property based on entity name and property name

Question: I am trying to retrieve the data type of a property based on the name of an entity and name of a property; both of which are declared as a string.
Take the following entity for example
public class Client
{
    public string Name { get; set; }
    public string Phone { get; set; }
}

From "Client" and "Phone" I would like "string" to be returned.
Answer: It can be done like so:
System.Reflection.PropertyInfo nameProp = typeof(Client).GetProperty("Name");
Type nameType = nameProp.PropertyType; // nameType  will be System.String

If you don't know the exact type then use:
var type = Type.GetType("Namespace.ClassName, Assembly");

Comment: What if I am unable to declare _typeof(Client)_ and instead type is passed through as a string? _typeof("Client")_
Comment: Then type = Type.GetType("MyNamespace.MyEntity, MyEntityAssembly")
Comment: @TrystanWilcock Did my answer help with your issue?
Answer: For Type.GetType, we need to pass the full name, if you prefer shortname like Client instead of Namespace.Client, you could try code below to retrive the types from assembly.
Assembly assembly  = Assembly.GetExecutingAssembly();
var type = assembly.GetTypes().ToList().FirstOrDefault(t => t.Name == "Client");
System.Reflection.PropertyInfo nameProp = type.GetProperty("Name");
string typeName = nameProp.PropertyType.Name; // nameType  will be System.String


Pumping Lemma works on language, but language is not regular

Question: So i am given this language:
L = { $c^ma^nb^n $ | $m≥ 1 $ and $n≥ 0$ } U { $a^mb^n$ | $m,n≥ 0$ }
And i have to prove that the pumping lemma property works on L.
Although pumping lemma can work, i then have to prove that L is not a Regular language.
Can anyone help me into proving this thing? And how is it possible that L would not be regular, but pumping lemma property worked?
Comment: The pumping lemma *cannot* be used to prove that a language is regular.  It can _only_ be used to prove that a language is _not_ regular.  This is because the pumping lemma has the form: "Every regular language has the following property…."  The way you use it is that you show that some language does not have the necessary property; that proves that the language is not regular.
Comment: I have edited the question, maybe now you get what i am trying to say. I'm quite new to these stuff and that's why I'm struggling
Answer: The easiest way to show that $L$ is not regular is probably to use the Myhill-Nerode theorem, i.e. we have to show that the equivalence relation
$$w \sim w' \text{ iff for all } x \in \Sigma^\ast, wx \in L \Leftrightarrow w'x \in L$$
has infinitely many equivalence classes.
Towards this, consider the words of the form $w_n = ca^n$.
Now for $n \neq m$ we have that $w_nb^n \in L$ but $w_m b^n$ is not, so in particular we have $w_n \not\sim w_m$, i.e. all equivalence classes associated to the $w_n$ are pairwise distinct for all $n$, and hence the language is not regular as the Nerode relation has infinite index.
Another way would be to assume that $L$ is regular and showing that any DFA $\mathcal A$ for $L$ could be modified to be a DFA $\mathcal A'$ for the language
$$ L' = \{c a^n b^n \mid n \in \mathbb N\}$$
which is non-regular, which is (probably) provable using the Pumping lemma.
This is a contradiction and hence $L$ cannot be regular.
Comment: another way to see the second claim without going through DFAs is to use that $\{c a^n b^m \mid n,m\geq 0\}$ is regular and using the closure properties of $\mathsf{REG}$