How to click unopened tabs where the numbers change

Question: How do I click all the unopened tabs pages where the value changes when you click tabs? (see image below)
Take the following script, based off of this question with the following approach:
       clickMe = wait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, path + '[%s]' % str(index - 1))))

Works great for the large majority of pages, however I cannot see how it can be used in this case.  Any idea how you can get around this issue?
The reason it does not work is because as soon as you click an unopened tab, the number values change.  This means the job is trying to click elements that used to exist, but the number values changed when you opened a closed tab. This is better illustrated in the image below.
Say you had //div[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"][1]
In the picture below, you can see that the above selector will change based upon when the job itself clicks tabs and upon loading the webpage.  The webpage has a habit of randomising opened and closed tabs.  So this explains why it will click some elements and then completely break or if you add try except, click only some elements and finish.
output:
1
2
3
4
#Stops working

Desired
1
2
3
4
etc,, (Clicks all the pages)

The above images are both:
//div[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"][1]`

You can see how this will cause issues later on.  The image on the right would not be able to locate //div[@class="KambiBC-collapsible-container KambiBC-mod-event-group-container"][11]  where a the one on the left could based on the order of tabs clicked.
outerhtml
Answer: Rather than using an index to reference these "tabs", you need an alternate way to uniquely identify each one.
One solution is to work with the developers of the site to get them to add an id or name attribute to the "KambiBC-collapsible-container" for each tab.
Another solution, if you're using the Page Object Model approach, would be to create a method on the page that provides a list of the available tabs that you can then reference by the header text.  Then you just keep track of which ones you've opened.
Yet another solution would depend on the functionality of the site.  You may be able to leverage the fact that if a tab has been opened it looks like the container has a class "KambiBC-expanded".  If a tab will stay open until you explicitly close it, you could simply get a list of all of the containers that do not have the "KambiBC-expanded" class and pick one to expand, repeating until there are no more to expand.


Replacement of missing values by median for all variables in R

Question: I have to replace the missing value by the median for all variables.
I know how to do it for each variable separately.
df$x1=ifelse(is.na(df$x1),median(df$x1,na.rm=T),df$x1)

But i have 21 variables and replacing must be performed for 20 variables from x1-x20.
How to replace missing value for 20 variables at once?
I don't want create 20 strings.
Comment: Can't say exactly unless you post sample data, but you could likely gather it into long-shaped data, group by some variable, and do this operation once.
Answer: You can use dplyr::mutate_at to replace missing values with median for that column. The mutate_at provides the flexibility (using start_with) to select columns starting with starting with X, for which rule will be applied.
library(dplyr)

df %>% mutate_at(vars(starts_with("X")), funs(ifelse(is.na(.),median(., na.rm = TRUE),.)))

#    ID X1   X2
# 1   a  1 21.0
# 2   b  2 22.0
# 3   c  7 23.0  << X1 was missing
# 4   d  7 24.0  << X1 was missing
# 5   e  7 25.0  << X1 was missing
# 6   f  6 26.0
# 7   g  7 24.5  << X2 was missing
# 8   h  8 24.5  << X2 was missing
# 9   i  9 29.0
# 10  j 10 30.0

Sample Data:
df <- data.frame(ID=letters[1:10], X1 = 1:10, X2 = 21:30)
df$X1[3:5] <- NA
df$X2[7:8] <- NA

df
#    ID X1 X2
# 1   a  1 21
# 2   b  2 22
# 3   c NA 23
# 4   d NA 24
# 5   e NA 25
# 6   f  6 26
# 7   g  7 NA
# 8   h  8 NA
# 9   i  9 29
# 10  j 10 30

Comment: MKR, what if my last variable is text? Will this code work?
Comment: @San.O You can add additional condition as `ifelse(is.na(.) & is.numeric(.) ,median(., na.rm = TRUE),.))`. I have not tested it but should work.


Installation of imagemagick with BREW

Question: My problem is really simple :)
<code>schovi@Saskia:~/tmp $ brew install imagemagick
Error: You must install
brew install git

schovi@Saskia:~/tmp $ brew install git
Warning: Formula already installed: git

schovi@Saskia:~/tmp $ brew install imagemagick
Error: You must install Git:
brew install git
</code>
Any idea? :)
Comment: What's the output of `which git`?
Comment: Also, did you install homebrew to `/usr/local` ?
Comment: And PATH is `/Users/schovi/.rvm/gems/ruby-head/bin:/Users/schovi/.rvm/gems/ruby-head@global/bin:/Users/schovi/.rvm/rubies/ruby-head/bin:/Users/schovi/.rvm/bin:/opt/local/bin:/opt/local/sbin:/usr/local/mysql/bin:/Users/schovi/.gem/ruby/1.8/bin:/opt/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin:/usr/X11/bin`
Answer: Install git from http://git-scm.com/
Comment: Better. I thought that brew is some kind of magic apps that can gandle everything :D
Comment: Actually, it's likely that it did, but wasn't installed in a location on your path.

Installation of imagemagick with BREW


How to find the integral value of hypergeometric functions

Question: We know that,
1.
$$
\int_0^1 t^{b-1} (1-t)^{c-b-1} (1-tz)^{-a} dt
= \beta(b, c-b) ~\,_2F_1~(a, b, c, z)
$$
2.
$$
\int_0^1 t^{a-1} (1-t)^{b-1} e^{ct} dt
= \beta(a, b) ~\,_1F_1~(a, b, c)
$$
where $\beta(\cdot, \cdot)$, $\,_2F_1~(\cdot, \cdot, \cdot, \cdot)$, $~\,_1F_1~(\cdot, \cdot, \cdot)$
are Beta function, Gauss Hypergeometric function and Confluent Hypergeometric function respectively.
Then, how to find the following integrals?
3.
$$
\int_0^{\theta} t^{b-1} (1-t)^{c-b-1} (1-tz)^{-a}~dt
= ?
$$
4.
$$
\int_0^{\theta} t^{a-1} (1-t)^{b-1} e^{ct}~dt
= ?
$$
where $0 < \theta < 1$.
Answer: Fist of all, Welcome to the site !
The first antiderivative is given in terms of the Appell hypergeometric function of two variables
$$I=\int t^{b-1} (1-t)^{c-b-1} (1-tz)^{-a}\,dt$$ $$I=t^b \left(\frac{F_1(b;b-c,a;b+1;t,t z)}{b}+\frac{t F_1(b+1;b-c+1,a;b+2;t,t
   z)}{b+1}\right)$$
The second one seems to be much more problematic (because of the exponential) and I should try a series expansion
$$J=\int t^{a-1} (1-t)^{b-1} e^{ct}\,dt= \int t^{a-1} (1-t)^{b-1}\left( \sum_{n=0}^\infty \frac {c^n}{n!} t^n\right)\,dt$$
$$J=\sum_{n=0}^\infty \frac {c^n}{n!}\int t^{n+a-1} (1-t)^{b-1}\,dt=\sum_{n=0}^\infty \frac {c^n}{n!}\,B_t(a+n,b)$$
Comment: Thank you @Claude Leibovici


Show that $\mbox{O}(V,\beta)\subset \mbox{GL}(V)$.

Question: Let $V$ be a finite dimensional vector space over $\mathbb{R}$ and $\beta:V\times V \rightarrow \mathbb{R}$ be a non-degenerate symetric form on $V$. Let $$\mbox{O}(V,\beta)=\left\{A\in\mbox{End}(V)|\beta(Au,Av)=\beta(u,v)\mbox{ for all }u,v\in V\right\}.$$
Show that $\mbox{O}(V,\beta)\subset \mbox{GL}(V)$.
Remark: I'm not sure my question makes sense, I also think that the definition of $\mbox{O}(V,\beta)$ may have an error, I think this because in several books $\mbox{O}(V,\beta)$ is defined in $\mbox{GL}(V)$ not in $\mbox{End}(V)$. I want someone to give me some suggestion or some reference to some book.
Answer: Since $V$ is finite dimensional, you have to show that if $A\in O(V,\beta)$, $A$ is injective in order to show that $A$ is invertible. Suppose that $A(x)=0$ for every $y\in V, \beta(A(x),A(y))=\beta(x,y)=0$. Since $\beta$ is nondegenerated, $x=0$.


If the quadratic equation $x^2+(2-\tan\theta)x-(1+\tan\theta)=0$ has two integral roots,

Question: If the quadratic equation $x^2+(2-\tan\theta)x-(1+\tan\theta)=0$ has two integral roots,then find the sum of all possible values of $\theta$ in interval $(0,2\pi).$

The given quadratic equation is $x^2+(2-\tan\theta)x-(1+\tan\theta)=0$.
So $x=\frac{\tan\theta-2\pm\sqrt{\tan^2\theta+8}}{2}$
I am stuck here.I do not know what is the condition for two integer roots.
Comment: $a^2-b^2=8$,how many possible $(a,b)$? find this and you will get answer.
Comment: Note that $\tan\theta$ must also be an integer
Comment: May be if $x \in \mathbb Z$, then $\tan^2 \theta +8 -$ perfect square.?
Answer: Let $t=\tan \theta$. We need that $t^2+8$ be a perfect square, so $$t^2+8=s^2\qquad(*)$$
When $\theta\in (0,2\pi)$, the value $t$ can be all real but if $t$ and $s$ must be integers we have $s=t+h$ where $h$ is a positive integer. It follows $$2ht+h^2=8\qquad (**)$$ An obvious solution of $(*)$ is $t=1$ so for $(**)$ we have to solve $$2h+h^2=8$$ whose only solution is $h=2$ but for $t>1$ there are no solutions for $(**)$
So the only values to be considered are $\frac{\pi}{4}$ and $\frac{5\pi}{4}$ which correspond to $t=\tan \theta=1$
Comment: The answer given in the book is that sum of the roots is $4\pi$,i think $t=-1$ is also the solution which gives $\theta=\frac{\pi}{4},\frac{3\pi}{4},\frac{5\pi}{4},\frac{7\pi}{4}$
Comment: I have seen $t=-1$ but this correspond to the angle $\frac{-\pi}{4}$ which is not in $(0, 2\pi)$ so I have discarded this negative value. Was I wrong? But the other values you give here I think are truly valid.
Answer: As roots are integers tan has to be an integer .  so $$\tan(x)=\sqrt{n^2-8}$$ thus $3,-3$(keeping in mind the graph of $n^2$ i have concluded it.) are only two integers who give a perfect squares thus now $x=\pi/4$ now again tan is positive in third quadrant so $x=5\pi/4$ thus sum of all such theta is $3\pi/2$


$.post retornar 2 valores

Question: Tenho seguinte código:

Porém no user.php ele retorna vários echo dentros de condições if. Então se eu tenho no PHP, por exemplo, echo "sucesso"; e outro echo "sucesso"; ele retorna sucessosucesso.
Eu gostaria de saber como eu faço para pegar cada um desse retorno separadamente?
Answer: Para resgatar cada informação desse retorno, utilize a função json_encode e retornar somente um echo para o seu Javascript.
Exemplo:
$resposta['status'] = 'success';
$resposta['line'] = 1;

echo json_encode($resposta);

Depois de executado esse echo tem um formato JSON:
{"status":"success","line":1}

No retorno do seu javascript faça:
jQuery.post()

Ou seja, retorna um dado(s) no formato JSON, para que o seu Javascript, trabalhe com a informação de retorno. Também pode ser recebido uma lista de informações.
Referências:

Trabalhando com JSON em PHP
Pass PHP Arrays to JSON and JS with json_encode
Passing Multidimensional Arrays from PHP to JavaScript
JSON with PHP
Comment: Excelente! Funcionou perfeitamente após adicionar o 'json'. Obrigado!
Comment: João, eu fiz isso que que você passou e ele retornou no formato JSON: {"status":"success","line":1} porém eu não estou conseguindo pegar a condição no javascript com o retorna.status.
Comment: @rhundler  tenta assim > var dados = jQuery.parseJSON(retorna); depois dados.status
Comment: @rhundler faltou um configuração no seu javascript agora que vi, já fiz a edição! olha lá não precisa converter nada viu! No final da `function(retorna){}, 'json');` para que ele entenda que o retorno é um json
Comment: @rhundler `The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).` faltou especificar o retorno! link: https://api.jquery.com/jquery.post/. fiz a edição na minha resposta

$.post retornar 2 valores


Web Service teste dos Correios - erro SSL

Question: Alguém já teve esse problema ao referenciar a web service para testes e implementações dos correios.
Preciso efetuar algumas validações mas não consigo executar nenhum método sem que ocorra erros de ssl.
Answer: Os dois métodos abaixo servem para aceitar qualquer certificado que os web services estejam utilizando
<code>    private static void SetCertificatePolicy()
    {
        // Código necessário para acessar serviços remotos
        // Evita o erro HTTP 417
        ServicePointManager.Expect100Continue = false;

        ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
    }

    private static bool RemoteCertificateValidate(object sender, X509Certificate cert, X509Chain chain,
        SslPolicyErrors error)
    {
        return true;
    }
</code>
Comment: Como eu poderia aplicar isso dentro do meu contexto ? Mesmo com esse erro, consigo importar todas as classes e métodos da web service. Só que quando tento executar um método especifico da um erro de ssl.
Comment: Tente chamar o SetCertificatePolicy() antes de instanciar a sua classe do webservice e efetuar as chamadas.. e me avise se der certo!
Comment: Funcionou perfeitamente !!!!!! Estou muito feliz. Muito obrigado !!!!! Consegue me explicar resumidamente (não precisa se não quiser) como isso funciona ? Conceitos mesmo.
Comment: Fala amigo, fico muito feliz de ter dado certo, aconselho você a criar uma classe de útils para guardar esse cara pois no decorrer da sua integração com o webservice podem surgir outros métodos. No código acima basicamente eu seto um callback  na validação do certificado, e o mesmo sempre retorna True, retornando sempre como se seu certificado fosse válido :)
Comment: Valeu (-; ......
Answer: O problema está no certificado do webservice. Provavelmente o certificado é auto-assinado, o que faz com que ele seja marcado como 'falso' pelos navegadores/aplicações.
Não há muito o que fazer. Você pode tentar forçar sua aplicação/servidor a aceitar o certificado falso, porém não é garantido que funcione.


#each blog post not displaying

Question: I have a collection that contains blog posts and I'm trying to get them to display on the page. The code below doesn't list out all the blog posts and I'm not sure why. As far as I can tell it is publishing.
Path: blog.html
{{#each Blog}}

{{details}}

{{/each}}

Path: blog.js
Template.blog.onCreated(function() {
    var self = this;
    self.autorun(function(){
        var id = FlowRouter.getParam('id');
        self.subscribe('blog', id);
    });
});

Path: Blog mongoDB example
{
  "_id": "JvLqxFisXc3PLeqSh",
  "details": "Test three",
}

Path: publish.js
Meteor.publish('blog', function (id) {
  check(id, String);

  return Blog.find({});

});

Answer: I need to add a helper.
Template.blog.helpers({
    blogPost: ()=> {
        return Blog.find({});
    }
)}

Path: blog.html
{{#each blogPost}}

{{details}}

{{/each}}

#each blog post not displaying


What is the terminology for these two techniques on piano?

Question: Disclaimer: I don't know music terminology, as I don't play any instruments.
The channel Sheet Music Boss on YouTube has two videos in which I've heard what I perceive to be two different techniques of some sort being played on a piano. I'd like to know if these techniques have any specific terms so that I can search for more, because it gives me goosebumps.
In the first video titled: IEVAN POLKKA (LOITUMA POLKKA) - Piano Tutorial at about 2:03 to 2:18 the music seem to change character, and becomes, for lack of a better term "magical". It looks to me as if the melody is still being played with the right hand, but something changed with the left I believe.
In the second video titled: When Johnny Comes Marching Home - Piano Tutorial at 0:57 to 1:20 it's pretty clear that the melody is being played with the left hand, while the right hand is playing what I assume would have been the bassline if it had been played with lower notes.
Answer: Ievan Polkka
There are two things happening here:

In the preceding section, the left hand is playing pairs of notes simultaneously. However, beginning at 2:03, the left hand plays broken chords. Broken chords, also called arpeggios, are when notes forming a single unit (a chord) are played individually.
The right hand plays the melody with ornamentation, meaning that decorative notes are added to the basic melody. In this specific case, you can hear occasional faster notes that were not previously heard. This is also sometimes called elaborating the melody. It can also be considered a variation, which is a technique by which a melody is restated in a modified form.

When Johnny Comes Marching Home
In this recording, the right hand plays broken chords (see above), while the left hand plays the melody. This technique of exchanging ("swapping") the roles of the two hands -- or more generally, having two instruments or "voices" change musical roles -- is called voice swapping.
Comment: The main thing that happens in the middle section of the polka is that the music moves into the upper range of the piano and has a lighter texture.  The heavy polka rhythm in the low notes is cut out for a bit.


UPTADE em php, não estou conseguindo

Question: Sou iniciante em php e estou tentando fazer um CRUD... no botao editar eu fiz uma funcao em js para aparecer os inputs e redirecionar para editar.php?id=echo $row['id']; Porém ele apenas pega o ULTIMO id cadastrado..

        CRUD - ALUNOS

        Aluno
        Nota
        Turma

        while($row = mysqli_fetch_assoc($listarAlunos)){
            $id = $row['id'];
            $nome = $row['nome'];
            $nota = $row['nota'];
            $turma = $row['turma'];
    ?>

            <?php echo"$nome"?>

            <?php echo"$nota"?>

            <?php echo"$turma"?>

            <button onclick="abrirEditar()">Editar</button>

            <a href="remover.php?id=<?php echo $row['id'] ?>">
            <button>Remover</button>

    <?php
        }
    ?>

editar.php
include 'conexao.php';
$id = $_GET['id'];
$novoNome = isset($_POST['novoNome']) ? $_POST['novoNome'] : '';
$novaNota = isset($_POST['novaNota']) ? $_POST['novaNota'] : '';
$novaTurma = isset($_POST['novaTurma']) ? $_POST['novaTurma'] : '';

echo $id;
$sql = "UPTADE tbaluno SET nome = '$novoNome', nota = '$novaNota', turma = '$novaTurma' WHERE id = $id";

$editarAluno = mysqli_query($conexao, $sql);

Answer: Olá pode ser problema na montagem do sql, tente assim:
$sql = "UPDATE tbaluno SET nome = '" . $novoNome . "', nota = '". $novaNota ."', turma = '" . $novaTurma . "' WHERE id = " . $id;

Coloque o script para fora do while e da seguinte forma:

E o editar da seguinte forma:
  <button onclick="abrirEditar(<?php echo $row['id'] ?>)">Editar</button>

Comment: Não eh isso :( , o problema eh que ele pega o ultimo id cadastrado, ele até edita, porém edita o ultimo
Comment: n deu certo :d.
Answer: Gustavo, pelo que eu entendo está faltando logo no começo do seu código já declarar que haverá a opção de uso do id. Já faça a declaração da conexão e do id logo no começo, depois, sempre que usar a busca pelo id, será o mesmo. Se estiver usando SESSION melhor ainda, pois pode declarar essa busca de id através da SESSION.
Exemplo:
$id = $_SESSION['db_login']['id'];

Comment: Ou essas ações:

 <a href="read_one.php?id=<?php $_SESSION['db_login']['id'] ; ?>
Comment: Qual é o erro que tem apresentado? Mas, tente essas ações que eu indiquei.
Answer: Olá Gustavo Tudo bem? então... eu recomendaria voçe a ultilizar esta função de tabela apenas com php e html, ate mesmo pelo fato assim como eu de ser iniciante, abaixo possui um codigo que pode lhe ajudar, basta replicar.
Conexão.php
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

mysqli_set_charset($conn, 'utf8');

USERS.php

          #
          Nome
          Nota
          Turma
          Actions

        <?php
        $result = mysqli_query($conn, "SELECT * FROM table ORDER BY id DESC");
        while($row = mysqli_fetch_assoc($result)){ ?>

          <?php echo $row['id']; ?>
          <?php echo $row['nome']; ?>
          <?php echo $row['nota']; ?>
          <?php echo $row['turma']; ?>

            <a href="edit.php?id=<?php echo $row['id']; ?>" class="btn btn-info btn-xs">
             Edit

      <?php } ?>

Edit.php
if (isset($_POST['enviar'])) {

    $id      = $_POST['id'];
    $nota    = mysqli_real_escape_string($conn, $_POST['nome']);
    $nota   = mysqli_real_escape_string($conn, $_POST['nota']);
    $turma = mysqli_real_escape_string($conn, $_POST['turma']);

    $sql = "UPDATE `users` SET `nome` = '$nome',`nota` = '$nota',`turma` = '$turma' WHERE `id` = '$id'";
    $ssl = mysqli_query($conn, $sql);

    header("Location: USER.php");
    exit();
}

Recomendo que ultilize o mysql_real_escape para evitar SQL Injection.

UPTADE em php, não estou conseguindo


If the resolution of human hearing is approximately five cents, how can musicians play works with intonation changes of less than five cents?

Question: Sources1 suggest that the frequency resolution of humans—our ability to discriminate differences in pitch—is limited to around five cents.
If this is the case, how can musicians play an excerpt like the following (listen here, and be sure to check out 0:22!), which demands intonation changes of as small as two cents? (The numbers written above/below the pitches are the changes, in cents, for the tuning of each pitch.)

This is spectralist music, so the intonation changes (at least in the first five measures or so) are based on the harmonic series. As such, the first violin may not be thinking of moving the F down two cents, but rather creating a justly tuned minor third with the cello. In other words, the first violinist isn't just tuning their single pitch down two cents, but they're tuning the interval itself. This all makes sense to me, and explains how a musician could hear this particular difference of under five cents.
But if all of this is true, then it seems to suggest that the first violinist can't actually play their part alone without the aid of a tuner. Am I missing something?
1 Just to limit these sources to SE sites, see here, here, and here.
Comment: Wow, I didn't expect such a negative reaction to the piece. I think it's a fantastic work!
Comment: @Tetsujin I'm sorry, but I suspect many people listening to that will share my feeling that although it may sound slightly out of tune from time to time it is still sounds much better than when I practice.
Comment: 0:28 sounds - weird! When was this written? (And don't say after a few pints!)
Comment: I got to 30s & just had to switch it off. That hurts. It starts feeling a bit 'just' which is fine by me, but then at 0.22  simply sounds out of tune for no reason. By 0.30 it's no longer bearable.
Comment: It's better than my local karaoke pub, I'll give you that;) I honestly don't understand what it's… for. tbh, I don't know whether I can identify categorically 5 cents - it depends on context as to whether a pitch bothers me - blues, flat 7, fine & dandy. 3rd… gotta be more careful to the overall tonality. I can't abide sharp 3rds, they're just painful & my tolerance for those is pretty small.
Comment: @Tetsujin Fair point, and that's certainly a worthwhile argument. (I don't have absolute pitch, for what it's worth.)
Comment: Oddly, I can ignore it on non-western, middle-eastern or gamelan etc. I have a friend who once famously said at a less-than spectacular rehearsal we'd been invited to, "I can either read the score or listen to the choir. I cannot do both at once."
Comment: There comes a time when composers like this need to be locked in a room with a loop-tape playing Yanni.    But anyway,  this kind of piece would be far better handled with some digitized string instrument notes which are then pitch-shifted digitally; the entire piece performed from a synth rather than live humans.
Comment: Sorry Richard, I just have very very small tolerance to things being "out of tune" whether intentional or not. I have some kind of internal pitch-meter which has wild tolerance for absolute pitch, but not for relative within a piece. It literally becomes unlistenable after a few seconds.
Comment: If this were an LP recording I'd suggest that the motor needed fixing…
Answer: With a bit of training, a good musician can hear differences of 2 cents, and with significant talent and/or a lot of practice, 1 cent.
I base the above statement on my personal experience with developing ear training software for musicians. For example, I have been working on an app for training musicians to tune a guitar or a piano, purely by ear. This software is not published yet, but I can tell you that with some practice both myself and a few other beta testers have been able to routinely reach a precision of 2 cents. On a good day, we can occasionally hit one cent.
So, answering your question: the sources that put the limit at 5 cents are not correct. 5 cents is not a difficult interval to hear (with some training) and I would put the limit at no more than 1 cent for people with a good musical ear.
And by the way, Ben Johnston performers are known to practice for years and years before being able to record a good take of his compositions, so while it's possible, it's not exactly easy... :)
(Should anyone be interested in beta testing the upcoming ear training app, write me privately)
Comment: Just had to react to the last comment here. Of course you can improve your ear. To take an example from something else than music: when you're learning a language it's very common not to be able to distinguish between specific sounds that are very distinct for people who speak the language. And after enough training you start distinguishing the sounds. Why wouldn't this be possible for pitches?
Comment: To me, it sounds as though they need several more years practice to be able to record a good take...
Comment: "... and a lot of practice" According to [Wikipedia](https://en.wikipedia.org/wiki/Psychoacoustics), the human ear has a resolution of about 3.6 Hz in the octave 1000-2000 Hz. This means that the ear won't report smaller differences in the pitch to the brain. 3.6 Hz equals 6.2 cent at 1000 Hz and 3.1 cent at 2000 Hz.
Comment: @Martin, with all the respect for Wikipedia, I speak from experience. I can normally tell 2-3 cents apart, and on a good day, 1 cent. And I'm not so special, I know plenty of good musicians who can do it better than me.
Comment: I doubt about the "*lot of practice*" part: Unlike muscles, which you can improve by training, you cannot improve your ear by doing something. If your ear reports only differences of 20, 10, 5 or 2 cents to your brain, you cannot improve this by training or practice. If you can hear 2 cents, you are lucky: I just checked it and found out that I can't hear the difference between 1000 and 1005 Hz (8.6 cents) nor the difference between 440 and 443 Hz (11.8 cents - although I can hear the difference of 10.6 cents between 1000 and 1006 Hz).
Answer: At one point I did some exercises in pitch difference and could usually hear whether a second note was lower, higher or the same when the difference was 5 cents. I struggled with a 2 cent difference but eventually learnt to "feel" a difference. The odd thing is I couldn't hear the second note as being different but there was a subtly different feel if it was lower, higher or the same. I gradually learnt to trust that subtle feeling even though I couldn't actually hear the difference as such. On a good day I would get 100% right. On a not so good day I wouldn't have sufficient sensitivity. It's very subtle. It was certainly an interesting exercise
Answer: I agree with answer given by topo Reinstate Monica.  I would also add that in addition to the pitch discrimination threshold being frequency dependent and NOT absolute, this explains a person's ability to judge the difference of two notes played separately.  A whole new set of acoustic and mechanical phenomenon occur when harmony is involved.  When listening to notes played together one will be better able to judge slight variations in pitch against the harmonic background.  The use of contrast here is a very common device in music and art.  As an extreme example consider tuning a musical instrument like the guitar.  We play the fifth fret harmonic of the low E string and attempt to match it with the seventh fret harmonic of the A string, both being an E.  As we tune the A string we will hear beats between the two notes.  The two notes are in tune relative to each other when the beat period is infinite (something we never really achieve).  The point is, at that point we are not hearing two notes but a fused tone and its envelop.  Our ability to judge the envelop as being flat is, as far as I know, only limited by our life span (if you are willing to sit that long, and the acoustic energy does not dissipate).  When listening to harmony we will hear similar phenomenon in the interaction of the harmonics of each note.  So, hearing A followed by A (+2) in a lab may not be perceived as different.  But hearing the interval (A, E) and (A(+2), E) may be noticeable.
Comment: @Tetsujin - I've been tuning guitars and basses using harmonics for decades. It seems to work for me, even though some say it can't be done. What you do is similar to violinists, but using fourths and third in place of their fifths.
Comment: The 5th fret will not match the true 5th, but then again the guitar is not a Just instrument.  Many can hear the resonance of a 5th or 4th.  I was taught to tune my violin by ear, playing two consecutive strings and listening for the resonance of a 5th.  At the end of the day we will have to make adjustments for the 12TET nature of fretted instruments.  My point about the tuning was to illustrate by example how beats work.
Comment: That's an interesting way to think of it - but I cannot tune guitars by harmonics, they go out across the fretboard. I find the best, simplest & most reproducible way to tune them is just play 6 open strings one after the other. The wrong ones are obvious to me & I re-tune them as I go; I guess because I "know" those pitches, but I couldn't explain it any better than that.
Comment: I get the same if I do the 5th fret/open thing too. I drift out as I cross the fretboard. Just listening to the open strings I can do it in two passes, rough it in, then hone it 2nd time. I've been doing it for so long it's just become 'the way I do it'.
Answer: The feeling of the interactions between two notes is pretty much different. Even if you can not differ each cent, if you play them simultaneously, you can hear the frequencies clashing. Personally I can say if there are differences of 3 cents with some ease, less than that it starts to sounds muddy


How do I get posts of a content type on node writing

Question: I have three content types: endorse, deals, and recommends. Recommends has three nodes.
How do I show those three nodes from the recommend content type on the deals content type using a field on the deals content type writing panel?

Answer: You can use the References Module, that can be used as a node reference of any other content type. After installing the module, go to deals content type manage fields, select the node reference to field to recommends content type and while configuring field make it as unlimited, and now go to deals content type writing panel, here you can see the multiple field and can access the node id or name of the references content type nodes.
You can list the selected nodes of references under deals node in views using relationship.


Setting up an init function in jQuery

Question: Just a quick question here, I wanted to find out how I could set up these into an init() function then have the function run on document.ready.  This code is being used in a separate main.js file.  Does it need to be called from the index page?
$('#main_right_line_one').click(function(){
    $('#main_regular_layover, #main_deep_layover').fadeOut('slow', function(){
        $('#main_light_layover').fadeIn('slow');
    });
});

$('#main_right_line_two').click(function(){
    $('#main_light_layover, #main_deep_layover').fadeOut('slow', function(){
        $('#main_regular_layover').fadeIn('slow');
    });
});

$('#main_right_line_three').click(function(){
    $('#main_light_layover, #main_regular_layover').fadeOut('slow', function(){
        $('#main_deep_layover').fadeIn('slow');
    });
});

Any help is appreciated.  I'm really trying to wrap my head around this, but I can't seem to find any good tutorials that explain init() well enough for my specific code.
Comment: http://api.jquery.com/ready/
Comment: So would I use get() to retrieve the divs?  I'm not sure exactly what I would be loading before this would be initialized.
Comment: $("#main_right_line_one") is the selector to get the div (as a jq object). So, that div has to already be present in your HTML. therefore, you will want to run this in the init.
Answer: No need for special "calls", include it on the page with  and just wrap your code as below to make sure that it is executed after the dom is ready (and the elements present).
$(function () {
   // your code goes here

});

$( a_function ) is short for $(document).ready( a_function ); more about ready handlers in the documentation.

The reason why $(document).ready(...)/$(...) is needed at all is that jquery selection like $('#main_right_line_one') only sees elements that are present at the execution time in the DOM tree. However,

You're right in that it's good practice to wrap all your code in an object and call that with an init() function. So in you main.js, you could have:
$(document).ready(function() {

    myPage.init();

});

And then below that, you can define your page object like so:
var myPage = (function() {

    var that = {};

    that.init = function () {

        $('#main_right_line_one').click(function(){
            $('#main_regular_layover, #main_deep_layover').fadeOut('slow', function(){
                $('#main_light_layover').fadeIn('slow');
            });
        });

        $('#main_right_line_two').click(function(){
            $('#main_light_layover, #main_deep_layover').fadeOut('slow', function(){
                $('#main_regular_layover').fadeIn('slow');
            });
        });

        $('#main_right_line_three').click(function(){
            $('#main_light_layover, #main_regular_layover').fadeOut('slow', function(){
                $('#main_deep_layover').fadeIn('slow');
            });
        });

    }

    return that;

})();

Comment: this is a much better answer than the one selected.
Comment: This adds a whole heap of confusing indirection. The init function would work fine by just being a procedural script, as you wouldn't really want to run that method more than once. The main.js script is the last item in the body so it doesn't even need to wait for document ready. As a bonus there would be no extra global myPage variable and the garbage collector can clean up all the no longer needed objects.

Setting up an init function in jQuery


OpenVZ and VMWare Server 1.x on the same Server

Question: Has any used a server to run both OpenVZ and VMWare Server?  Are there any issues with doing this I should be aware of?
Comment: @Matt Simmons: Well they are NORAD machines for missile launch.  But since some of the machines are old Windows 3.1 machines, I thought it would be easier to visualize them.  They all have low memory requirements....
Comment: At least tell me it's a lab environment ;-)
Answer: I've run OpenVZ and VMware Server 1.x (and 2.x) on the same system in a lab environment, and there were no apparent problems.  The base system was CentOS 5.x.  The OpenVZ instances were used for web and samba file sharing.  The VMware server was used for Windows test servers, as well as alternative distro testing.  The networking was "interesting" on OpenVZ, but that was more due to the fact that this system was tagging packets, so these problems weren't related to the dual-virtualization setup.
I have actually moved on to a KVM setup for my current lab setup.  The OpenVZ/VMWare dual setup was too labor intensive to keep going.  Mostly kernel updates would be the most headaches, as you needed an OpenVZ kernel.  Headers had to be available for VMWare to recompile.  It seemed that some issues would crop up, so it would be a few days before everything was stable again.


How to get raw signal from a divided or hexaphonic pickup

Question: I have been looking for a way to get a truly divided signal from each string on an electric guitar.
The problem is I don't want the signal to be in a midi format because midi throws away a lot of useful information in the signal.
I'm looking into getting a guitar with a divided pickup (like the Roland GK-3), also known as a hexaphonic pickup, and I was wondering if there was any way to get the "raw" (non-midi) signal from a pickup like this while keeping the signal divided.
I would prefer a solution that doesn't require cutting into any wires or hacking together some circuitry myself ... because lets face it, this thing is expensive.
Is this possible? (please note: it doesn't have to be with a Roland GK-3).
Anything that will get me the result I'm looking for would be acceptable.
Comment: Related: http://music.stackexchange.com/q/25045/12202
Answer: It has been done, in several different pickup designs. These are called hexaphonic pickups, meaning "six separate sounds" or six audio signals, one for each string by itself.
There were a couple of commercial products offered in the last ten years or so by Gibson Guitars and Keith McMillen Instruments that did exactly what you are looking for, but they are no longer being sold. See below.
You can purchase hexaphonic pickup systems from Fishman and Graph Tech that might be capable of being wired up according to your idea. These systems are in the form of six separate piezoelectric pickups installed within an electric guitar bridge -- with a separate pickup under each of the six independent bridge saddles. The Fishman PowerBridge offers this, as does the Graph Tech Ghost system. Each of these require purchasing a bridge-and saddle assembly, and wiring each of the six separate bridge piezo pickups into an internal or external six-channel preamplifier. (These kinds of pickups also are "Roland-compatible" and can use the Roland DIN-13 output jack like the Roland GK-3 you mentioned.)

Graph Tech Ghost piezoelectric bridge elements to be installed in a Stratocaster-style bridge

Graph Tech Ghost internal preamplifiers and wiring kit for their bridge pickup system
The Keith McMillen company used to market the StringPort, a six-channel preamp and analog-to-digital converter that could accept the "Roland-ready" DIN-13 pin output from a hexaphonic piezoelectric bridge pickup, convert all six discreet channels of analog signal into digital audio, and send them all to a DAW in a computer for processing or recording each string's signal on its own separate track. But this product is no longer offered.
Gibson also used to make a Les Paul guitar with a hexaphonic piezoelectric bridge pickup and similar capability, sold with an outboard preamplifier and an external interface box with six separate analog audio output channels. One model was called the Dusk Tiger; the original model in the line was called the "Gibson Robot Guitar". [Note that Gibson has used confusing nomenclature: more recent Gibson instruments called "Robot Guitar" refer to guitars equipped only with an automatic string-tuning system, and not with the original hexaphonic audio output system.]

Diagram of the six-channel "breakout box" for the original Gibson Robot Guitar with its hexaphonic piezoelectric bridge pickup
Brian Moore Guitars make electric guitars that come from the factory with a hexaphonic piezoelectric bridge pickup, and a Roland DIN-13 connector installed internally. I don't know if Brian Moore is using Fishman, Graph Tech, L. R. Baggs or RMC piezo bridge pickups these days, but they should all work about the same. If you had a Brian Moore guitar you'd still need a hexaphonic preamplifier with six audio outputs to plug it into.
Note however that all of the systems described above use piezo-electric pickups, the same kind of pickup used in under-saddle bridges for acoustic guitars. Therefore the sound these pickups produce is of the "acoustic" variety. You would have to use a lot of signal processing to try to make these pickups sound like a conventional magnetic pickup on a conventional electric guitar. You would have to have six separate channels of signal processing (e.g. six separate distortion boxes), whether in the analog or the digital domains.
It would be possible to build six single-string pickups using conventional passive electric guitar single-coil pickup technology, which means winding thousands of windings of hair-thin copper cable around a permanent magnet, but this would be awkward to create. I remember reading about just such inventions back in the crazy days of the 1970s -- there were some prototypes made, but they were never mass-produced and never became popular.
In particular, the Hamer company made such a design for bass guitars, using four separate magnetic pickups, one for each course of string. This would have been easier than a similar design for a guitar, because on the bass the strings are farther apart and there would be more room for those large magnetic coil pickups.

The Hamer Quad Bass as played by Jon Entwistle of The Who
Note the built-in four-channel "mixing board", leading to four separate outputs, one for each string
In the mid-1980s the Kramer guitar company made some guitars called the Ripley line that had hexaphonic pickups that mixed down into a two-channel, stereo output, with a pan-pot for each string. I'm not sure if these were all piezoelectric designs or if there were magnetic pickups involved as well. You can read about them here.
http://www.vintagekramer.com/ripley.htm
Update:
After a Google search I found a one-man company that sells a more conventional magnetic hexaphonic pickup for electric guitars. The company is called Ubertar Hexaphonic Guitar Pickups. I know nothing about them or their products.
http://www.ubertar.com/hexaphonic/index.html
UPDATE TO THE UPDATE
Much to my astonishment I found a current product that does exactly what you want (assuming it is indeed still being manufactured). It's the RMC Pickup Fanout Box. RMC Pickups has been around for many years. You ought to be able to plug any guitar with a piezoelectric hexaphonic bridge pickup and a Roland-Ready DIN-13 pin output into this device. (RMC sells piezoelectric hexaphonic bridge pickups, though these days it seems their kits are only for acoustic guitars, not electric. Have a look around their website.)
http://www.rmcpickup.com/fanoutbox.html
Comment: Many years ago I had a Brian Moore iGuitar (a cheap Korean one) with a hexaphonic piezo bridge pickup. But I used it for MIDI only, plugging it into a Roland MIDI converter and an Axon MIDI converter. However, I remembered that there were some gizmos for processing hexaphonic audio. The Gibson Robot Guitar to the Dusk Tiger were rather impractical because Gibson only put this technology on high-end, expensive guitars, and I knew it wouldn't last.
Comment: The Keith McMillen system looks to be the most promising. It also came with a suite of custom software for hexaphonic signal processing on Mac OS X. But McMillen doesn't make them anymore -- they got into unusual MIDI keyboard and foot pedal and keypad controllers for keyboardists and DJs and those are selling briskly.
Comment: RMC is a small company that built in small batches. They used to own the hexaphonic bridge pickup market, but when Fishman and Graph Tech got into that space they took much of RMC's business away. Since the RMC website, ancient though it is, is still up, I'm hoping they are still in business, but I don't know for sure.
Comment: It turns out that with divided pickups that have a 13 pin output, 6 of the pins will carry the individual signals to each string so what I want to do is completely possible!  I will look into many of the options mentioned in your post.  Thanks for the very detailed answer!
Comment: Another item to add to the list of not-available-any-more kit is the *ARP Avatar*
Comment: That RMC fanout box does look like exactly what I need! Unfortunately I can't seem to find one. I may just have to make one, or something similar myself.


criteriaBuilder selectCase in aggregate function throw QuerySyntaxException

Question: I want to do a select case in a aggregate function but it throw a QuerySyntaxException :
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: case near line 1, column 125 : [select new com.dev.entity.User(generatedAlias0.id, generatedAlias0.name, generatedAlias0.date, generatedAlias0.mode, count(case when generatedAlias0.id=:param2 then :param3 else :param4 end)) from com.renault.dev.User as generatedAlias0]

like if the case function is not recognized :/
There is the criteria query
Expression<String> idCountCase = builder.<String>selectCase().when(builder.equal(userRoot.get(User_.id), "id01"), "EXISTS").otherwise("NOT EXISTS");
Expression<Long> idCount = builder.count(idCountCase);
criteriaQuery.multiselect(userRoot.get(User_.id), userRoot.get(User_.name), userRoot.get(User_.date), userRoot.get(User_.mode), idCount);

Any advices please ?
Thank you very much
Answer: Resolved. I just updated Hibernate version and it works now . I guess condition in aggregate function was not supported in previous version...


How can I derive this fast-converging series formula for $\zeta(4)$?

Question: Let $\zeta(n)$ denote the Riemann Zeta function for positive integers $n>1$ as usual by:
$$
\zeta(n)=\sum_{m=1}^{\infty}m^{-n}.
$$
There are fast-converging series for $\zeta(2)$ and $\zeta(3)$, but not others. In the spirit of Apéry's
$$
{\displaystyle {\begin{aligned}\zeta (3)&={\frac {5}{2}}\sum _{k=1}^{\infty }{\frac {(-1)^{k-1}}{{\binom {2k}{k}}k^{3}}}\end{aligned}}},
$$
quick numerical computations show that

Conjecture 1. $$ {\displaystyle {\begin{aligned}\zeta (4)&={\frac {36}{17}}\sum _{k=1}^{\infty }{\frac {1}{{\binom
{2k}{k}}k^{4}}}\end{aligned}}}.$$

However, I am unable to prove this statement. I have tried using
$$
2(\sin^{-1}x)^2 =\sum_{k=1}^{\infty}{\frac{(2x)^{2k}}{{\binom {2k}{k}}k^{2}}},
$$
but to no avail. Any help is appreciated.
Comment: This conjecture was proved over 30 years ago by Bombieri and van der Poorten, and the auxiliary series you mention played a role. See pages 2 and 3 of their paper "Continued Fractions of Algebraic Numbers", including the footnote on page 3. This paper is freely available online.
Comment: @KCd Thank you. You may post this as answer and I will accept it.
Answer: $$\sum_{k=1}^{+\infty}\frac{(-1)^{k+1}x^k}{k^2\binom{2k}{k}}=2\,\text{arcsinh}^2\left(\frac{x}{2}\right)\tag{1}$$
due to the Maclaurin series of the squared arcsine, hence the computation of the series appearing in your conjecture is equivalent to the computation of the following integral:
$$ I = \int_{0}^{1}\frac{2}{x}\text{arcsinh}^2\left(\frac{x}{2}\right)\log^2(x)\,dx.\tag{2} $$
In 1981 Leschiner pointed out a nice consequence of creative telescoping:
$$\begin{eqnarray*}\sum_{n\geq 0}\left(1-\frac{1}{2^{2n+1}}\right)a^{2n+2}\zeta(2n+2)&=&\sum_{n\geq 1}\frac{(-1)^{n+1}}{n^2-a^2}\\&=&\frac{1}{2}\sum_{k\geq 1}\frac{1}{k^2\binom{2k}{k}}\cdot\frac{3k^2+a^2}{k^2-a^2}\prod_{m=1}^{k-1}\left(1-\frac{a^2}{m^2}\right)\tag{3}\end{eqnarray*}$$
and in 2006 Bailey, Borwein and Bradley pointed out that similarly
$$\begin{eqnarray*}\sum_{n\geq 0}\zeta(2n+2)a^{2n}&=&\sum_{k\geq 1}\frac{1}{k^2-a^2}\\&=&3\sum_{k\geq 1}\frac{1}{\binom{2k}{k}(k^2-a^2)}\prod_{m=1}^{k-1}\frac{m^2-4a^2}{m^2-a^2}\tag{4}\end{eqnarray*} $$
holds. By comparing the coefficients of $a^0$ in the LHS and RHS of $(3)$ we get the well-known
$$ \frac{1}{2}\zeta(2)=\frac{3}{2}\sum_{k\geq 1}\frac{1}{k^2\binom{2k}{k}}.$$
The coefficient of $a^4$ in the LHS of $(3)$ is
$$ \frac{7}{8}\zeta(4) = \frac{1}{2}\sum_{k\geq 1}\frac{1}{k^2\binom{2k}{k}}\left[\frac{4}{k^2}-3 H_{k-1}^{(2)}\right]$$
and the series
$$ \sum_{k\geq 1}\frac{H_{k-1}^{(2)}}{k^2\binom{2k}{k}} $$
can be computed from $(4)$ or from the Maclaurin series of $\arcsin^4(x)$ (identity $(20)$ here), proving
$$ \sum_{k\geq 1}\frac{\color{red}{1}}{k^4 \binom{2k}{k}} = \frac{17}{36}\zeta(4).\tag{5}$$
Comment: @PierreTheFermented: correct, this answer is about $\sum_{k\geq 1}\frac{1}{k^4 \binom{2k}{k}}$.
Comment: Quality answer, as always Jack
Comment: For info, the Conjecture is wrong (it should have $1$ instead of $(-1)^{k-1}$ in the numerator within the sum...)


Swift programming style

Question: I saw some source code in github, like this:
functional-swift
We can see there's definition of a struct called Ship, and there're some variable in it. From the following code we can see that there're also some function in it. It is written in the following style:
struct xxx {
}

extension xxx {
    func yyy() {}
}

I can also definite the struct in the following style:
struct xxx {
    func yyy() {}
}

So what the different of the two style? Is there a swift programming style guide?
Comment: It helps to organize your code into groups of related methods, in particular when adopting protocols (as explained in the referenced Q&A). Recommended here: https://github.com/raywenderlich/swift-style-guide#protocol-conformance.
Comment: Please check this [question](http://stackoverflow.com/questions/28367950/swift-and-using-class-extension) out.  I think it covers your question.
Comment: How exactly you group the methods into extensions is a matter of personal taste. I would not define an extension for *each* method, as in the example code that you linked to.
Comment: I'm not sure this is a duplicate of that question, because that question is talking about extensions with protocols, which have obvious benefits, whereas this isn't.
Comment: @GoatInTheMachine: As I understand it, both questions are about when use extensions (and not define all methods directly in the struct/class definition).The other *question* does not mention protocols, so it seems like the same question to me. – It's the *answers* to the other question which tell that protocol conformance is the a major use-case, but also code organization: *"For me it seems completely reasonable since you can use extensions to expose different parts of logic to different extensions."*
Answer: from your example, the first one is a basic struct with an extension
struct xxx {
}

extension xxx {
function yyy() {}
}

the other is a struct with a function built in.
struct xxx {
function yyy() {}
}

imagine you cannot modify the original struct for some reason but you still want to be able to perform function yyy() -> you can extend the class to call the function yyy() without modifying the class itself (or changing the way it behaves elsewhere in your program)
"Extensions can add new functionality to a type, but they cannot override existing functionality." (src: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html)
-> Extensions are useful when you don't have access to a class but you want to add some functionalities. Using extensions, you can compartmentalize your classes and customize what a class can do as needed.
Answer: From the Swift docs:

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).

So the usefulness of it is when you want to extend an already existing implementation. Apple has great documentation, and I highly recommend you read the above link.
Comment: The question here is about defining your own type, not about extending an existing type for which you don't have the source code.

Swift programming style


flexslider is failing on version recognition and perms

Question: Updated via drush, flexslider module v.7.x-2.0-alpha3 is installed.
Installed latest version of library 2.3.0, released 17 days ago as of the time of this writing.
Getting drupal pesky error about version not recognized, so decided to downgrade library to 2.2.2, same error.
Moreover I am getting following errors in status report:
<code>Warning: fopen(sites/all/libraries/flexslider/jquery.flexslider-min.js): failed to open stream: Permission denied in _flexslider_requirements_library_installed() (line 212 of /var/www/asflorida.com/sites/all/modules/flexslider/flexslider.install).
Warning: fread() expects parameter 1 to be resource, boolean given in _flexslider_requirements_library_installed() (line 213 of /var/www/asflorida.com/sites/all/modules/flexslider/flexslider.install).
</code>
Before somebody tells me that this is a perm issue: I checked thoroughly and perms are 775 throughout and ownership is correct.
Either alpha 3 is not working with older library or viceversa.
Thanks in advance.
Comment: Just want to mention that I use alpha3 with 2.2.2 with no issues.  Drupal status page should show "Version 2.2 installed".  Flush your caches - manually check README.mdown in the library folder for version 2.2.2
Comment: well, that was my answer, the problem is that alpha3 will not recognize 2.3.0.
Answer: Basically this is a duplicate issue, workaround (cannot be called solution) is to downgrade from v.2.3.0 to 2.2.2.
I already posted in the module's issue queue.
The other issues were caused by ownership and perms issues, while I was testing both library versions, disregard that part.


How to insert data in symfony table?

Question: I have made a symfony form and I used:
<code>$conn->insert('Invoiceshasitems', array('Invoiceitemsid' => '$items'));
</code>
for data insertion but it not works ho i do insert data from symfony controller.
here is my code:
<code>$itemscounter = $request->request->get('itemscounter');
if(isset($_SESSION['invoiceid'])) {
    $invoiceid=$_SESSION['invoiceid'];
    //echo $invoiceid;
    //exit;
}
//$entity= new Invoiceshasitems();
if($request->isXmlHttpRequest()) {

    if($itemscounter > 1){

        for($i=1; $i<=$itemscounter; $i++){

            if($i==1){
                $items = $_POST['items'];
            }else {
                $items.$i = $_POST['items'.$i];
            }
        }
    }else{

        $items = $_POST['items'];
        $conn->insert('Invoiceshasitems', array('Invoiceitemsid' => '$items'));
    }
}
</code>
Comment: use doctrine: http://symfony.com/it/doc/current/book/doctrine.html
Comment: can i used $query = $em->createQuery("insert into Invoiceshasitems('invoiceid','invoiceitemid')values('".$invoiceid."','".$items."')");
      $ids = $query->getResult(); ?
Comment: i used above command but dql only for select,delete,update etc
Comment: another method to insert values other than dql?
Answer: You can use native query in Doctrine, there is some docs here: http://docs.doctrine-project.org/en/latest/reference/native-sql.html
For your example the code is something like that:
<code>$rsm = new ResultSetMapping();
$query = $this->_em->createNativeQuery('INSERT INTO Invoiceshasitems SET Invoiceitemsid = ?', $rsm);
$query->setParameter(1, $items);

$result = $query->getResult();
</code>
Comment: Link is broken: [http://docs.doctrine-project.org/en/latest/reference/native-sql.html](http://docs.doctrine-project.org/en/latest/reference/native-sql.html)

How to insert data in symfony table?


Url to a google maps page to show a pin given a latitude / longitude?

Question: Is there some url I can construct with a latitude,longitude pair that will lead me directly to a google maps page to visualize that location?
For example, the following pseudocode:
var lat = 43.23;
var lng = 114.08;

var url = 'http://google.com/maps/bylatlng?lat=' + lat + '&lng=' + lng';

print 'click here to see this location in google maps!: go';

Something like that?
Thanks
Comment: Now here's *my* question:  is there a way to display multiple teardrops, or even a track with just a url?
Answer: You should be able to do something like this:
http://maps.google.com/maps?q=24.197611,120.780512
Some more info on the query parameters available at this location
Here's another link to an SO thread
Comment: You can control the zoom by adding &z= to the end of that url (e.g. http://maps.google.com/maps?q=24.197611,120.780512&z=18).
Comment: @JonathanMcIntire the ability to set the zoom level like that doesn't seem to work any more; for your link it always seems to default it to zoom level 17 now.  Any ideas on how to control this?
Comment: Try this: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
Answer: From my notes:
http://maps.google.com/maps?q=37.4185N+122.08774W+(label)&ll=37.419731,-122.088715&spn=0.004250,0.011579&t=h&iwloc=A&hl=en
Which parses like this:
    q=latN+lonW+(label)     location of teardrop

    t=k             keyhole (satelite map)
    t=h             hybrid

    ll=lat,-lon     center of map
    spn=w.w,h.h     span of map, degrees

iwloc has something to do with the info window.  hl is obviously language.
See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
Comment: A bit off-topic but maybe still helpful for those who would like to specify a label/title/name for the marker on the Google Maps iOS app: while `q=lat,long+(My%20custom%20location%20name)` does no longer seem to work for the Google Maps web site, it does currently (still) work on their iOS app.
Comment: Thank you. Its works! Alson I add &z=10 for zooming in your example
http://maps.google.com/maps?q=37.4185N+122.08774W+(label)≪=37.419731,-122.088715&spn=0.004250,0.011579&t=h&iwloc=A&hl=en&z=12


What is the objective function to optimize in glm with gaussian and poisson family?

Question: I am reading this post and still confused about the different ways of fitting exponential data. Specifically, why I am getting different results with following code? Could anyone help me to write down the objective functions for different model ?
For lm, it is $||X\beta-\log(y)||_2^2$, but what about glm cases?
The reason I ask for objective function is that many literatures are focusing on algorithm details of "re-weighted least square", but lack the emphasis on high level objective.
last_14 = data.frame(rbind(
c(3460,  14,    0),
c(3558,  17,    1),
c(3802,  21,    2),
c(3988,  22,    3),
c(4262,  28,    4),
c(4615,  36,    5),
c(4720,  40,    6),
c(5404,  47,    7),
c(5819,  54,    8),
c(6440,  63,    9),
c(7126,  85,   10),
c(7905, 108,   11),
c(8733, 118,   12),
c(9867, 200,   13)))
names(last_14) = c('World', 'US', 'days')

fit_lm = lm(log(World) ~ days, last_14)
fit_glm = glm(formula = World ~ days,  data=last_14, family=gaussian(link='log'))
fit_glm2 = glm(formula = World ~ days,  data=last_14, family=poisson())

Answer: summary
Linear model with least squares (Gaussian distributed observations)
fit_lm = lm(log(World) ~ days, last_14)

$$\sum_{\forall i} (\log(y_i) - X_i \beta)^2$$
Non-linear model with least squares (Gaussian distributed observations)
using GLM model (with Gaussian distribution family)
fit_glm = glm(formula = World ~ days,  data=last_14,
family=gaussian(link='log'))

or using non linear least squars (NLS)
fit_nls = nls(World ~ exp(a+b*days), start = list(a = 8, b = 0.1), data=last_14)

$$\sum_{\forall i} (y_i - e^{X_i \beta})^2$$
Poisson regression (Poisson distributed observations)
using GLM model (with Poisson distribution family)
fit_glm2 = glm(formula = World ~ days,  data=last_14, family=poisson())

$$\sum_{\forall i} (e^{X_i \beta} -(X_i \beta)y_i)$$
GLM
The relationship for GLM can be written down as
$$Y_i = f( X_i \beta) + \epsilon_i$$
Sometimes people are instead using the link function $f^{-1}$ to linearize the equation
$$\begin{array}{}
f^{-1}(Y_i) = f^{-1}\left( f(X_i \beta) + \epsilon_i \right) \neq X_i \beta + \epsilon\end{array}$$
But that it is not the same. See the last inequality and how  $\epsilon$ is placed differently (an example with $f(x)=\exp(x)$ is $\log(\exp(1)+1) \neq 1+1$).

The difference between glm with link function and linearized least squares
The difference is that the error terms are incorporated differently. We can write it down more explicitly for a logarithm/exponential function.
Let the linearized relationship lm(log(World) ~ days) be
$$\log(y_i) = a + b x_i + \epsilon_i$$
Then the non-linearized relationship is:
$$y_i = e^{a + b x_i + \epsilon_i}$$
and this is not like the glm(World ~ days, family=gaussian(link='log'))
$$y_i = e^{a + b x_i} + \epsilon_i$$
The error term $\epsilon_i$ occurs differently in the formula.

The difference with between different families
In the case of the Gaussian/Normal family the following two are the same:
$$Y\vert X \sim \mathcal{N}(\mu = h(X), \sigma^2 )$$
or
$$Y = h(X) + \epsilon \quad \text{where} \quad \epsilon \sim N(0,\sigma^2)$$
this separation into a linear sum of a deterministic component $h(X)$ plus some error/noise term $\epsilon$, will not work the same for other families. For instance for the Poisson distribution you will get that the noise term is larger for a large mean.

Poisson distribution with log link
The log likelihood for a single observation $z$ is
$$L = z X\beta - e^{X\beta}$$
and
$$\frac{\partial L}{\partial \beta_i} = \left( z  - e^{X\beta} \right)  x_i$$
In the framework of GLM the optimum for this likelihood function is found by iterated least squares solving this likelihood
$$L_{itteration} = 0.5 w(Y^\prime - X\beta)^2$$
with derivative
$$\frac{ \partial L_{itteration}}{\partial \beta_i} = w (Y^\prime - X\beta) x_i$$
and the transformation between the two would be (check https://www.jstor.org/stable/2344614 for the details):
$$Y^\prime = X\beta + \frac{z - e^{X\beta}}{e^{X\beta}}$$
and
$$w = e^{X\beta}$$
where we do not know $e^{X\beta}$ but the current estimate $e^{X\hat\beta}$ can be used and then iteratively improve the result.
Intuitively
You could see GLM as loosely approximating the more general exponential family as Gaussian noise, for $\theta = X\beta$
$$Y \approx f(\theta) + \epsilon \quad \text{where} \quad \epsilon \sim N(0,w\sigma^2) $$
where

the weight $w$ relates to the non-homogeneity of the distribution function (e.g. in the case of Poisson distribution then $\sigma^2 = \mu$)

and in linearized form
$$f^{-1}(Y) \approx \theta + \epsilon + \frac{Y-f(\theta + \epsilon)}{\partial f(\theta) / \partial \theta }   \quad \text{where} \quad \epsilon \sim N(0,w\sigma^2) $$
where

the term $\frac{Y-f(\theta + \epsilon)}{\partial f(\theta) / \partial \theta }$ relates to the non-linearity in the effect of errors on the response when a link function is applied to the response. (ie. the model of the error distribution is for $Y$ and not for $f^{-1}(Y)$ and that needs to be corrected. So that is an additional correction, aside from the weights which only correct for the non-homogeneity in the variance of $Y\vert X$ and not $f^{-1}(Y) \vert X$)

Computational demonstration
days <- last_14$days
US <- last_14$US

### iterrating
Y <- last_14$US
X <- cbind(rep(1,14),last_14$days)
coef <- c(2,0.3)                 # begin solution
yp <- exp(X %*% coef)
for (i in 1:100) {
  w <- as.numeric(yp)            # weights
  Yprime <- log(yp) + (Y-yp)/yp  # y-values
  coef <- solve(crossprod(X,w*X), crossprod(X,w*Yprime))
  yp <- exp(X %*% coef)          # new solution
}

### glm function
modglm <- glm(US ~ days,
              family = poisson(link = "log"),
              control = list(epsilon = 10^-20, maxit = 100))

### direct optimization of likelihood
Loption = "Poisson"
L <- function(x) {
  a <- x[1]
  b <- x[2]
  Xb <- a+b*days
  if (Loption == "Poisson") {
    return(-sum(Y*Xb-exp(Xb)))
  }
  if (Loption == "Gaussian loglink") {
    return(sum((Y-exp(Xb))^2))
  }
  if (Loption == "linearized model") {
    return(sum((log(Y)-Xb)^2))
  }
}

start <- c(a=2,b=0.3)
modoptim <- optim(par = start,fn = L)

Which give the same results
> # glm model
> modglm$coefficients
(Intercept)        days
  2.4750654   0.2030466

> # optimizing likelihood function
> modoptim$par
        a         b
2.4745912 0.2031048

> # manual computation
> coef
         [,1]
[1,] 2.4750654
[2,] 0.2030466
>

Computations for other cases
Below are the other cases. Note that the GLM function with Gaussian family can also be alternatively done with nls.
> ###for the other cases
>
> Loption = "Gaussian loglink"
> optim(par = start,fn = L)$par
        a         b
2.1735638 0.2315177
> glm(formula = US ~ days,  data=last_14, family=gaussian(link='log'))

Call:  glm(formula = US ~ days, family = gaussian(link = "log"), data = last_14)

Coefficients:
(Intercept)         days
     2.1736       0.2315

Degrees of Freedom: 13 Total (i.e. Null);  12 Residual
Null Deviance:      35020
Residual Deviance: 1375     AIC: 110
> nls(US ~ exp(a+b*days), start = list(a=2,b=0.2))
Nonlinear regression model
  model: US ~ exp(a + b * days)
   data: parent.frame()
     a      b
2.1736 0.2315
 residual sum-of-squares: 1375

Number of iterations to convergence: 7
Achieved convergence tolerance: 3.19e-06
>
>
> Loption = "linearized model"
> optim(par = start,fn = L)$par
        a         b
2.5917459 0.1879523
> lm(log(US) ~ days)

Call:
lm(formula = log(US) ~ days)

Coefficients:
(Intercept)         days
     2.5918       0.1879

Comment: More precise would be to write that $Y\vert X \sim D(\mu = f(X\beta))$  and Y can be seen as following a distribution $D$ for which the mean parameter $E(Y\vert X)$ is equal to $f(X\beta)$. The description of a linear sum of a deterministic part and a random part makes indeed more sense for least squares (normal distribution).
Comment: optimizing likelihood function on POISSON one  `modoptim$par` is not exactly equal to manual calculation or glm results. Could help me to understand why?
Comment: @HaitaoDu I am not sure but I guess that the (small) discrepancy is because the algorithm used in `optim` stops already early before reaching the exact solution (optim is using a gradient method to itteratively improve the estimate, obtaining an estimate with a higher likelihood each step and getting closer to the exact solution each step, and stops when the steps of the improvements are smaller than a certain factor times the machine precision). You can change the parameters to make optim return a more accurate result.
Comment: Thanks for your comments i think `control = list(reltol=1e-30)` fixed it.
Comment: Example: for Nelder-Mead you can change the `reltol` parameter like this: `modoptim <- optim(par = start, fn = L, method = 'Nelder-Mead', control = list(reltol=10^-12))`. That reltol parameter defines when the algorithm stops (that is when the algorithm decides that it has converged close enough to the solution). For different methods there are different parameters and there will be different ways to get more precise results (e.g. for the gradient based methods it might be usefull to change the scale or ndeps parameters which have an effect on the precision of the computation of the gradient).
Comment: $Y_i = f( X_i \beta) + \epsilon_i$ confuses me. What would $\epsilon_i$ be for a logistic regression?
Comment: We often take $\epsilon \sim N(0,\sigma^2)$ but you could use any other distribution (in the case of GLM it is limited to a distribution from a particular exponential family). Also the function $f$ can be anything. For logistic regression $f$ is the exponential function.
Comment: This is by far the clearest explanation of the GLM which I have ever read.


When can a real analytic function change to have a non-zero imaginary part?

Question: For $f(z)$ which is an analytic function of the complex variable $z$, ($z=x+iy$):
$$f(z(x,y)) = u(x,y)+iv(x,y)$$
that satisfies:
$$v(x,0)=0$$
for $x$ in some finite range:
$$a<x<b$$
Consider a point $x=c$ for $c<a$ where:
$$v(c,0)\ne 0$$
does this necessarily imply that there exists at least one point of non-analyticity of $f(z)$ on the real line in the interval $(c,a)$?
i.e. $f(z)=\ln(z)$ is purely real for $z=x$,  $x>0$ and has a point of non-analyticity at $x=0$ and has non-zero imaginary part for $z=x$,  $x<0$. (As does $f(z)=z^{1/2}$, I want to know if this will always be the case.)
Answer: In that situation - assuming the condition is not vacuous, i.e. assuming $a < b$ - there always must be a singular point of $f$ in the interval $(c,a]$. (We cannot assert a singular point in the open interval $(c,a)$ since $a$ may be the only singular point on the real axis.)
Say that $f$ is defined and holomorphic on the open set $U \subset \mathbb{C}$. Let $V = \{ \overline{z} : z \in U\}$ and define
$$g(z) = \overline{f(\overline{z})}$$
for $z \in V$. Then $g$ is holomorphic on $V$, and by assumption we have $g(z) = f(z)$ for all $z \in (a,b)$. Therefore $g(z) = f(z)$ for all $z$ belonging to the connected component $W$ of $U\cap V$ that contains $(a,b)$ by the identity theorem. But also by assumption we have $g(c) = \overline{f(c)} \neq f(c)$, hence $c \notin W$. Thus it is impossible that $[c,a] \subset U$; for if it were, then $[c,b) \subset U \cap V$ and hence $[c,b) \subset W$.


Erro classse R, Android Studio

Question: Após criar um projeto no Android Studio,  aparece o seguinte erro no console:
/home/nayron/AndroidStudioProjects/MyApplication2 /app/build       /intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/values-v23/values-v23.xml
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
Error:(2) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.
Error:Execution failed for task ':app:processDebugResources'.> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/home/nayron/android-sdks/build-tools/23.0.1/aapt'' finished with non-zero exit value 1
Information:BUILD FAILED

Poderiam me explicar os possíveis motivos desse erro e como soluciona-lo, por favor?
Comment: Nayron, poderia incluir o seu `build.gradle`?
Answer: Este erro, em se tratandop de Android Studio, pode ter muitas causas.
Dando uma rapida pesquisada na internet percebe-se inúmeras pssoas com o mesmo erro e causas e soluções diferentes.
Uma delas é fazer o Downgrade do Gradle para a versão  com.android.tools.build:gradle:1.1.3 ou o Upgrade para versão mais recente.
Comment: Eu acho que o erro é porque ele está usando a versão 23 do `apocopam` mas não está usando o `compileSdkVersion` na versão 23.
Comment: Tentei fazer o que me recomendou, mas não obtive sucesso. O erro persiste.
Comment: Mas de qualquer forma, obrigado pela atenção.
Comment: @NayronMorais você esta usando o 'Gradle'?
Comment: Sou leigo nesta área, não sei se estou usando-o.

Erro classse R, Android Studio


Find $\phi_2$ given $d, \phi_1$ and $\lambda_1 = \lambda_2$

Question: Suppose that you have have two points $x = (\phi_1, \lambda_1)$ and $y = (\phi_2, \lambda_2)$, where $\phi$ and $\lambda$ represent latitude and longitude. Let $\Delta\phi = \phi_2 - \phi_1$ and $\Delta\lambda = \lambda_2 - \lambda_1$, then the distance between the two points in meters, $d$, is given by the following system
\begin{align}
&a = \sin²(\Deltaφ/2) + \cos φ_1 ⋅ \cos φ_2 ⋅ \sin²(\Delta\lambda/2)\\
&c = 2 ⋅ atan2( \sqrt{a}, \sqrt{(1−a)} )\\
&d = R ⋅ c
\end{align}
or alternatively by
$$
d = cos^{-1}( \sin \phi_1 ⋅ \sin \phi_2 + \cos \phi_1 ⋅ \cos \phi_2 ⋅ \cos \Delta\lambda ) ⋅ R\tag{1}$$
(Source for these equations can be found here)
Question: Suppose that $\lambda_1 = \lambda_2$, and suppose that I know $\phi_1$. How do I determine $\phi_2$ such that the distance between $(\phi_1, \lambda_1)$ and $(\phi_2, \lambda_2)$ is $d$?
What I've tried: If $\lambda_1 = \lambda_2$ then equation $(1)$ above can be reduced to
$$
\cos\big(
\frac{d}{R}\big) = \sin\phi_1\sin\phi_2\\
\Leftrightarrow \phi_2 = sin^{-1}\bigg(\dfrac{\cos(d/R)}{\sin(\phi_1)}\bigg)
$$
This doesn't work and I would like to know why!
Answer: I believe you have mistakenly reduced the expression $\cos{\phi_1}\cos{\phi_2}\cos{\Delta \lambda}$ to $0$ instead of $1$, as $\cos{0}=1$. Then we have
$$\cos{\frac{d}{R}} = \cos{(\phi_2-\phi_1)}$$
$$\phi_2 = \frac{d}{R}+\phi_1+2k\pi, k \in \mathbb{Z}$$


Finding maximum likelihood estimates of parameters of multiple normal populations

Question: I've just started studying maximum likelihood and likelihood ratio tests. I've calculated the maximum likelihood of a normal population with unknown mean and variance. However, I've been given this problem:

Independent random samples of size $n_1, n_2, ... ,n_k$ from $k$ normal populations with unknown means and
  equal but unknown variances are to be used to test the null hypothesis $H_0: \mu_1=\mu_2=...=\mu_k$ versus the
  alternative that these means are not all equal.
Find the restricted and unrestricted MLEs of $\mu_1...\mu_k$ and $\sigma$ and find the likelihood ratio statistic.

The multiple $\mu$s are really throwing me for a loop. So far I think I have the likelihood function correct: $$\prod\limits_{i=1}^k \frac{1}{\sqrt{2\pi}\sigma}\exp\left\{-\frac{1}{2\sigma^2}\sum_{j=1}^{n_i} (x_{ij}-\mu)^2\right\}$$
However, I'm a little concerned as to how I approach this from here. I understand I'm supposed to take the log of the function then take the partial derivatives of $\mu$ and $\sigma$, however the products and sums are throwing me off a bit. Is there a different approach to solving this problem or am I just over thinking it? Did I even set it up correctly? Any help would be greatly appreciated. Thanks!
Comment: If this is a homework question, please add a self-study tag.
Comment: Your likelihood is the one under $H_0$, so there is a single $\mu$ and this is a standard Normal model, except that you miss a $(\sqrt{2\pi}\sigma)^{n_i}$ in the denominator. Under $H_a$, you will have $\mu_i$'s in your exponential terms.
Comment: Later is better than never.
For a different answer to this k-sample test for comparison, see this post [Bayes-Poincaré's solution to k-sample tests for comparison and the Behrens-Fisher problem?](https://stats.stackexchange.com/questions/419690/bayes-poincar%c3%a9-s-solution-to-k-sample-tests-for-comparison-and-the-behrens-fishe)
Answer: As hinted in a comment, you have to set up an hypothesis test. Your hypothesis $H_0$ is that the mean is the same. In that case, the likelihood will be
$$
\mathcal{L} = \prod_{i=1}^n\frac1{\sqrt{2\pi}\sigma} \exp\left(-\frac{(x_i-\mu)^2}{2\sigma^2}\right)
$$
where the product is in all the data points together ($n=\sum_k n_k$). We know that the optimal estimator is
$$
\hat{\mu}=\frac1{n}\sum_{i=1}^nx_i
$$
and
$$
\hat{\sigma}^2=\frac1{n}\sum_{i=1}^nx_i^2-\left(\frac1{n}\sum_{i=1}^nx_i\right)^2
$$
The value of the log-likelihood you get it from replacing in the previous formula is
$$
\log\mathcal{L}_0=-n(\log(\hat{\sigma}\sqrt{2\pi})+1/2)
$$
Your hypothesis $H_1$ is that the mean is different from each sample. Since the samples are indipendent, the likelihood of that is simply the product of the likelihoods of each sample:
$$
\mathcal{L} = \prod_{j=1}^k \prod_{i=1}^{n_j}\frac1{\sqrt{2\pi}\sigma} \exp\left(-\frac{(x_i-\mu_j)^2}{2\sigma^2}\right)
$$
The solution for the $\mu_j$ is analogous:
$$
\hat{\mu}_j=\frac1{n_j}\sum_{i=1}^{n_j}x_i
$$
before replacing it in the likelihood formula, let's do some 'massage'
$$
\mathcal{L} = \frac1{(\sqrt{2\pi}\sigma)^n} \prod_{j=1}^k \prod_{i=1}^{n_j} \exp\left(-\frac{(x_i-\hat{\mu}_j)^2}{2\sigma^2}\right)
$$
then the product becomes
$$
\prod_{j=1}^k \prod_{i=1}^{n_j} \exp\left(-\frac{(x_i-\mu_j)^2}{2\sigma^2}\right) = \exp\left( \sum_{j=1}^k \sum_{i=1}^{n_j} -\frac{(x_i-\hat{\mu}_j)^2}{2\sigma^2} \right)
$$
apply logarithm
$$
\log\mathcal{L}_1=-n\log(\hat{\sigma}\sqrt{2\pi})-\left( \sum_{j=1}^k \sum_{i=1}^{n_j} \frac{(x_i-\hat{\mu}_j)^2}{2\hat{\sigma}^2} \right)
$$
Let's call $\hat{\sigma}^2_j$ the variance of the sample $j$; we have that
$$
\log\mathcal{L}_1=-n\log(\hat{\sigma}\sqrt{2\pi})-\left( \sum_{j=1}^k \frac{n_j \hat{\sigma}_j^2}{2\hat{\sigma}^2} \right)
$$
by derivating and equating to $0$ you get that
$$
\hat{\sigma}^2=\sum_{j=1}^k\frac{n_j}{n}\hat{\sigma}_j^2
$$
and we get
$$
\log\mathcal{L}_1=-n(\log(\sum_j n_j/n \hat{\sigma}^2_j \sqrt{2\pi})+1/2)
$$
The likelihood ratio, can be computed as the substraction of the two log-likelihoods:
$$
\log(\mathcal{L}_1/\mathcal{L}_0)=-n\log\left( \frac{ \frac1n \sum_{i=1}^n (x_i-\mu)^2 }{ \frac1n \sum_{j=1}^k \sum_{i=1}^{n_j}(x_i-\mu_j)^2}\right)
$$
You can replace the values of $\mu$, you get eventually to
$$
\Lambda = e^n\exp\left(1-\frac{\frac1{n^2}\sum_{j=1}^k\frac{n}{n_j}\left(\sum_{i=1}^{n_j}x_i\right)^2-\frac1{n^2}\left(\sum_{i=1}^nx_i^2\right)}{\frac1n\sum_{i=1}^nx_i^2-\frac1{n^2}\left(\sum_{i=1}^nx_i\right)^2}\right)
$$


$(\forall n \in \mathbb{Z}):n^{3} \equiv n$ (mod $6$)

Question: [This is not a duplicate, since I am seeking for an alternative proof for this problem]
This is a problem from Proofs and Fundamentals, by Ethan D. Bloch.

Show that, for all $n \in \mathbb{Z}$, $n^{3} \equiv n$ (mod $6$).

I wrote my proof as follows and I would really appreciate if you could check it:

Proof: Let $n \in \mathbb{Z}$. Note that $n^{3} - n = (n-1) \cdot n \cdot (n+1)$, so the former is the product of three consecutive integers. By the Division Algorithm, we know that $n = 3q + r$, with $q,r \in \mathbb{Z}$ and $r \in \{0,1,2\}$. Since we have three consecutive integers, we know that each is either equal to $3k$, or $3k + 1$, or $3k + 2$ for some $k \in \mathbb{Z}$.
Let's suppose that $n = 3k$ for some $k \in \mathbb{Z}$ (the argument is similar for the rest two cases, so for the sake of briefness I will omit here). It follows that $n-1 = 3k - 1 = 3k - 3 + 2 = 3(k-1) +2$ and $n+1 = 3k +1$. We have to possibilites on the parity of $k$.
If $k$ is even, then $k=2j$ for some $j \in \mathbb{Z}$. Hence $n = 3 \cdot 2 \cdot j = 6k$. Hence $n^{3}-n=6k(n-1)(n+1)$ and $k(n-1)(n+1) \in \mathbb{Z}$. Therefore $n^{3}-n \equiv 0$ (mod $6$) and then $n^{3} \equiv n$ (mod $6$).
If $k$ is odd, then $k = 2i + 1$ for some $i \in \mathbb{Z}$. Hence $n + 1 = 3(2i+1) +1 = 6i + 4 = 2(3i+2)$. It follows that $n^{3} - n = (n-1) (3k) (2(3i +2)) = 6k(n-1)(3i+2)$ and $k(n-1)(3i+2) \in \mathbb{Z}$. Thus $n^{3}-n \equiv 0$ (mod $6$). Therefore $n^{3} \equiv n$ (mod $6$). This completes our proof. $\square$

I would also like to know that if there is other way to prove this result? (In the book, Bloch gives a hint that says to note that $n \equiv 0$ (mod $6$), or ..., or $n \equiv 5$ (mod $6$) and then in each case to compute $n^3$ (mod $6$), but I don't know how this will work as a proof... any idea?).
Thank you for your attention!
Comment: @RobertShore Getting this closed will take time. And whenever you look for *alternative proofs*, it makes sense to collect the alternatives to the same place. I posted that link partly to make it easier for any wanna-be-answerer to check that they are actually offering an alternative approach. A common problem with *solution-verification* questions is that many answerers just want to post a reincarnation. That discussion should take place in meta, though.
Comment: Basically, the answerers should check at least [this](https://approach0.xyz/search/?q=%24n%5E3%5Cequiv%20n%5Cpmod6%24&p=1) as well as [this](https://approach0.xyz/search/?q=%24n%5E3-n%24%2C%206&p=1) Approach0 search results before posting anything. The latter has [this](https://math.stackexchange.com/q/1657878/11619) as its #1 hit.
Comment: I disagree with the close vote.  He wants his proof verified.  The other questions don't use this precise proof.
Comment: Are you supposed to know the *Chinese remainder theorem*?
Comment: @Bernard I don't that theorem yet...
Comment: Also [here](https://math.stackexchange.com/q/1280400/11619) and probably elsewhere also. This is pretty much a FAQ.
Comment: @JyrkiLahtonen it partially answers. I'm looking for an alternative proof.
Answer: Your proof is correct but you can simplify it.  Once you correctly note that $n^3-n$ is always the product of three consecutive integers, just observe that any three consecutive integers must include a multiple of $3$ and a multiple of $2$, so their product must be a multiple of $6$.
Comment: Any $n$ consecutive integers must include a multiple of $n$.  That seems obvious but if you need a proof, just note that they must walk through all possible remainders after dividing by $n$, including $0$.
Comment: First of all, thank you for the feedback, I really appreciate it! Second, I though of that, but it this was the only way that came to me to show that we will always have a multiple of $3$ and a multiple of $2$ is those 3 consecutive integers. Is there any more concise way to show that?
Comment: Got it! It is indeed pretty obvious, but now I'm really sure of the validity of the argument! Thank you!
Answer: There are only 6 different (non-equivalent) numbers modulo 6 namely 0,1,2,3,4,5. Now for every one of them compute $n^3 \pmod 6$ and check that it is equivalent to $n$.
The cases 0 and 1 are trivial.
Whilst for example
$$2^3=8\equiv 2\pmod 6$$
and also
$$3^3=27\equiv 3\pmod 6.$$
Now you need only to check 4 and 5 and you are done.
Comment: Yes, it is correct, but an argumentation like the one of @Robert Shore that any three consecutive numbers one is divisibile by $3$ to me would be sufficient.
Comment: I see! That's actually a more concise and clever way to prove this result! But is my proof acceptable? Thank you for the answer!
Answer: You can shorten a bit the verification writing the elements of $\mathbf Z/6\mathbf Z$ as $\:\{0,\pm 1,\pm 2,3\}$.
Of course, we only have to examine the cases $\;0,1,2,3$, of which the first two are obvious, so there remains to examine

$n\equiv 2$: $\:2^3=8\equiv 2\mod 6$,
$n\equiv 3$: as $3^2=9\equiv 3$, $\:3^3=3^2\cdot 3\equiv 3^2\equiv 3\mod 6$.


Does a chef node need a public IP?

Question: I'm looking at Chef as a possible solution for a project, and I'm still unfamiliar with its architecture. The first question that comes to my mind is this: do every node need a public IP?
I want to be able to manage a big number of nodes, each in different networks to which I won't have access. I'll bootstrap them in my local network, of course, but after that I'll install them in different physical locations/networks.
Will the Chef server still be able to converge them after they're plugged to a new network with a private address?
Answer: As long as the Chef nodes can contact the Chef server, everything will be fine.  Make sure your <code>/etc/chef/client.rb</code> and DNS is configured to work in the final environment.

Does a chef node need a public IP?


How can I show an "Add file" button?

Question: I'm making a form that can update a node values.
I managed to generate a file upload field which shows the already uploaded images, but there's no visible Add file button. When I add a new file, the other files disappear.
What should I change in the following code to show an Add file button?
<code>$files = $event->field_bijlages;
$fileIds = [];

foreach($files as $file) {
  $fileIds[] = $file->entity->fid->value;
}

/* Files uploading */
$form['files'] = array(
  '#type' => 'managed_file',
  '#upload_location' => 'public://',
  '#default_value' => $fileIds,
);
</code>
Normally, a managed_file type field shows the uploaded with a checkbox list which allows you to add/delete uploaded files. That's what I'm missing here.
Answer: I added this <code>#multiple => true</code> to parameters, since the original field is also a multiple files field. And that made it work!

How can I show an "Add file" button?


Como remover R$ do NumberFormatter?

Question: Galera estou com o seguinte problema.
Segue meu código:
$valores = '530222077.99';
$moeda = new NumberFormatter('pt_BR', NumberFormatter::CURRENCY);
$valores = $moeda->formatCurrency($valores, 'BRL');
echo $valores;

O seguinte código me retorna: R$530.222.077,99. Porem, eu preciso que me retorne 530.222.077,99, ou seja sem o R$.
Answer: Quando você usa NumberFormatter::CURRENCY, está pedindo o "pacote completo", que inclui a moeda e os separadores de milhar e decimal.
Uma opção para a parte numérica é usar NumberFormatter::DECIMAL
$valores = '530222077.99';
$moeda = new NumberFormatter('pt_BR', NumberFormatter::DECIMAL);
$valores = $moeda->formatCurrency($valores, 'BRL');
echo $valores;

Mais detalhes podem ser vistos na documentação da classe, em especial a parte das "constantes pré-definidas".
Note que você pode criar seus próprios formatos e máscaras se quiser, com o método NumberFormatter::create.
Comment: Teste `$moeda->setAttribute( NumberFormatter::MIN_FRACTION_DIGITS, 2 );`
Comment: perfeito funcionou 100%
Comment: estou tendo outro problema. se eu colocar um valor 2500 ele me retorna 2.500 ao indez de 2.500,00. Sabe como resolver isso?
Comment: poderia me dar mais uma ajuda? estou usando a forma CURRENCY para exibir totais em relatório, pois ela ja vem com o R$. O problema e que quando formata um numero negativo ele fica assim: (R$4.444,44) Sendo que preciso que ele fique assim: R$-4.444,44 Você sabe como resolver isso?
Comment: R$ -4.444,44 não existe :) O que você pode fazer, é usar um IF e colocar, por exemplo, parênteses em volta (ou um sinal de menos antes do R$). Conforme eu comentei em outra ocasião, se quiser realmente customizar muito a saída, é melhor uma função própria de formatação.
Comment: No caso como eu faço para ficar assim -R$4.444,44? Pois tem que ter uma forma de eu representar valor negativo correto?
Answer: Bom seguindo o manual do php:
http://php.net/manual/pt_BR/numberformatter.formatcurrency.php
Cheguei a solução. Que na minha opinião e muito melhor usar o NumberFormatter pois e uma biblioteca nativa do php.
Segue a solução para conversão.
$valores = '-99999999.99';

$moeda2 = new NumberFormatter('pt_BR', NumberFormatter::CURRENCY);
$moeda2->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "-R$");
$moeda2->setTextAttribute(NumberFormatter::NEGATIVE_SUFFIX, "");

$valores = $moeda2->formatCurrency($valores, 'BRL');

Retorna  -R$99.999.999,99
Solução para  reversão
$moeda2 = new NumberFormatter('pt_BR', NumberFormatter::CURRENCY);
$valor_puro = $moeda1->parseCurrency($valores, $moeda_bd);

Retorna 99999999.99

Como remover R$ do NumberFormatter?


hook_menu shows in menu but not show page

Question: I made module, and want to add settings page.
Menu Item appear in settings dashboard, but when try access page it display dashboard with menu items again, thought URL is correct.
return array(
    'admin/store/settings/vsl_spl'=> array(
        'title' => 'SPL Settings',
        'description' => 'SPL Settings Page',
        'page_callback' => 'vsl_spl_page_test',
        'type' => MENU_NORMAL_ITEM,
        "access arguments" => array('access administration pages'),
        'position' => 'left',
        'weight' => 10,
    ),
)

and callback function is just for test yet
function vsl_spl_page_test(){
    return '
Test
';
}

Page opens with status 200 but content is wrong.
Answer: It's just a typo. Remove the underscore from page_callback.
Comment: I'm so sorry. It is just so unusual to use spaces. Thanks a lot.
Comment: No problem! Welcome to Drupal Answers!


Excel | Limitar calculo dentro da célula com valor máximo e valor mínimo

Question: Estou a contruir um excel onde necessito que uma determinada celula faça um calculo onde o valor só pode ser entre 0 (zero) e 50.
Para o valor máximo já consegui colocar a funcionar com a seguinte formula :
<code>=MÍNIMO(50;(SOMA(E15-H15)))
</code>
Vou é precisar também que o valor nunca seja negativo.
Existe alguma formula mais fácil ou que recomendem para esta situação?
Comment: Use [`IF`/`SE`](https://support.microsoft.com/pt-br/office/se-fun%C3%A7%C3%A3o-se-69aed7c9-4e8a-4755-a9bc-aa8bbff73be2), lembrando que para mais de uma condição na IF/SE você pode usar as funções de operadores lógico: https://support.microsoft.com/en-us/office/using-if-with-and-or-and-not-functions-d895f58c-b36c-419e-b1f2-5c193a236d97
Answer:
: Use esse caso queira calcular o valor restante da célula H15 - Essa é a que mais se adequa a formula que você forneceu.
<code>=MÁXIMO(0;(SOMA(MÍNIMO(50;(SOMA(E15-H15))))))
</code>

: Use esse caso queira somar as duas células E15 e H15
<code>=SE(E15+H15<=0;0;SE(E15+H15>=50;50;E15+H15))
</code>

: Use esse caso queira somar o intervalo de E15 até H15
<code>=SE(SOMA(E15:H15)<=0;0;SE(SOMA(E15:H15)>=50;50;SOMA(E15:H15)))
</code>
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


How to upload custom file (.txt, .rar, .xml, .zip) in php (wordpress)?

Question: I want to enable uploading files directly to the root. Supported file extensions should be: .txt, .rar, .xml, .zip. I'm trying to do this with the code from w3schools, as I'm beginner in php and wordpress plugin development. Plugin works, there is a menu icon on the left admin bar, there is an upload option on the admin page, but when I "upload" the file, there is no file in uploads folder (I'm first trying to do just like the code is on w3schools. The code is:
HTML

Test file upload page

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

and the PHP file (upload.php)
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
    echo "File is an image - " . $check["mime"] . ".";
    $uploadOk = 1;
} else {
    echo "File is not an image.";
    $uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=
"jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been
uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
}
?>

I know that this is not a good approach, and that there are Wordpress functions to to what I'm trying to do, but I just wanted to try this that way... If you know any better way, I would appreciate if you open my eyes. Also, I have another question: Can file upload work on local? I mean, I'm doing everything on localhost with MAMP, and this is for practice purposes.
I haven't edited any of the code to support file extensions I nedded, because I first wanted to test if it works with image files, but it isn't.
EDIT 1:
I also saw that in php.ini file file_uploads directive should be set to On:
file_uploads = On

But, there is no php.ini file in wordpress directory. Is there a way to edit php.ini file with wordpress plugin? Maybe that is the problem. Just guessing.
Answer: You have the following issues with your code:

The upload.php file is not needed, everything should go in a single file, your main plugin file in this case.
As there's no upload.php file, the form action should be empty.
Everything in your PHP code should be inside if(isset($_POST["submit"])) { }, because if nothing was submitted you don't need to execute anything from the upload script.
Your $target_dir should be an absolute path, something like:

/home/user/public_html/wp-content/
/Users/username/Sites/wp/wp-admin

Here's a small working example based on the code you posted, I'm using wp_upload_dir to set the destination directory. In my test, images were uploaded to http://localhost/wp-content/2018/10/image.png.
<?php
/**
 * Plugin Name: (SO) Testing upload
 */
add_action('admin_menu', function () {
    add_menu_page(
        'Upload',
        'Upload',
        'read',
        'so_upload',
        'so_upload_callback',
        null,
        6 // position, just after Posts
    );
});

function so_upload_callback()
{
    ?>

Test file upload page

    <form action="" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
    </form>

    <?php
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $target_dir = wp_upload_dir();
        $target_file = $target_dir['path'] . '/' . basename($_FILES["fileToUpload"]["name"]);
        $uploadOk = 1;
        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
        // Check if file already exists
        if (file_exists($target_file)) {
            echo "Sorry, file already exists.";
            $uploadOk = 0;
        }
        // Check file size
        if ($_FILES["fileToUpload"]["size"] > 500000) {
            echo "Sorry, your file is too large.";
            $uploadOk = 0;
        }
        // Allow certain file formats
        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType !=
            "jpeg"
        && $imageFileType != "gif" ) {
            echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            $uploadOk = 0;
        }
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            echo "Sorry, your file was not uploaded.";
            // if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
                echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been
                    uploaded.";
            } else {
                echo "Sorry, there was an error uploading your file.";
            }
        }

    }
}

Note that files uploaded this way don't show up on WP media library. Also, if the code is for real, the form needs a nonce field for security (wp_nonce_field).
Comment: Yes, check the link about "absolute path" that you'll find how to upload wherever you want. Sure, just use `add_submenu_page()` to create a page where you will list the contents of the target directory with images. On Google, use "what you want site:stackoverflow.com" and you'll find lots of code ready to use. Check the advanced search features here on [so] and at [wordpress.se] to find stuff too. Good luck!
Comment: If someone have similar problem, and want the upload destination to the root, you can use: `get_home_path()` instead of `wp_upload_dir()`, and then change change this line `$target_file = $target_dir['path'] . '/' . basename($_FILES["fileToUpload"]["name"]);` to `$target_file = get_home_path() . '/' . basename($_FILES["fileToUpload"]["name"]);`
Comment: Wow. Thank you. Can it be done in a way so files uploaded would be on the root of the website (along with wp-content, wp-admin, etc...). Also, can I add another menu page that will be shown as, for example (Uploaded files) and then that page is shown only if there are files that are uploaded, so from there I can delete files? I'm not aksing you to do that for me, but to give me some advices and where should I look. Thanks again for answering my question in such a great and useful way.


Proving points lie on a straight line (geometric proof)

Question: I am struggling to understand what criteria to look for when trying to prove that $A$, $B$ and $N$ are on a straight line in the question below:

I can work out the interior angle at $ B$ as $150$ and the exterior angle as $30$. The angle $BCN$ is $120$, but I cannot see why this is sufficient to draw the conclusion that $N$ will be on the projection of $AB$?
Comment: Looks like you are done.  $\Delta BCN$ is isosceles so $\angle CBN=\angle CNB=30$.
Comment: @Lulu How do I know that $CBN = 30$? I know the exterior angle is $30$, but my brain is struggling to be convinced that this $CBN$ is the exterior angle?
Comment: @Lulu I was being silly, thank you - it's the isosceles triangle part!
Comment: No worries.  Like I said, you were nearly done.
Answer: You would like to prove that $A\hat{B}N = 180^\circ$ and since $A\hat{B}C = 150^\circ$, it suffices to show that $N\hat{B}C = 30^\circ$.
Note that triangle $BCN$ is an isosceles triangle. Can you take it from here?