Colorbox not working for anonymous users, but works fine for logged in

Question: I am having an issue getting my colorboxed images to load while viewing the page as an anonymous user. As an anonymous user, there is no reference to anything related to colorbox at all. However, when logged in as admin, everything works fine.
This feels like a permissions issue, but I don't see any settings in permissions. also, the configuration in the 'manage display' settings leave a bit to the imagination.
What am I doing wrong? Is this indeed a permissions issue? 7.x 1.3 and drupal 7.14
Comment: Can you post a link?
Comment: http://tourismbuilder1.hokkaido-select.com/content/dart-bar-que-sera-sera voila! Each of those three should be a link that, when clicked, open in a Colorbox. Again, works fine when logged in. Thanks!
Comment: http://tourismbuilder1.hokkaido-select.com/content/traditional-mochi-making here it seems to work .. just do the same ;)
Answer: I had a javascript conflict in my theme. Works great now that that has been cleared up. Thanks!


which condition from question to select for which hypothesis test?

Question: I'm learning statistics and having hard times understanding hypothesis.
Suppose we are testing the hypothesis that sugar is linked to obesity. Which will be for what type of hypothesis.
for example-
H0: Yes, sugar is linked to obesity and
H1: No, sugar is not linked to obesity  or
H0: No, sugar is not linked to obesity and
H1: Yes, sugar is linked to obesity.
Another example(from an exam):
"Select the hypothesis formulation and the corresponding best values for α, in a Judiciary Scenario so as to avoid punishing an innocent in lieu of which it's okay to pronounce a real case of guilty as not guilty:"
answer is: H0 : Defendant is Innocent, H1 : Defendant is not Innocent, α = 1%
I'm confused between which condition to select for what hypothesis and also how to select confidence intervals.
Comment: A couple of comments. Identifying the null and alternate hypotheses have nothing to do with what you *expect* to happen or what you *want* to happen or what would be *interesting*. So the null hypothesis is that the incomes of men and women are equal. We may not expect the null hypothesis to be true. And maybe we want the null hypothesis to be true. But these considerations don't help you identify the null hypothesis. For probably every test you'll be studying, the null is always that there is no association, no correlation, no difference between groups, and so on.
Answer: In statistics Null Hypothesis i.e. H0 usually states that two variables ( in your case sugar and obesity ) are not related or there is no association between them. So for this case, the correct hypothesis should be -
H0: No, sugar is not linked to obesity
H1: Yes, sugar is linked to obesity.
Since now it's easy for you to state the Null hypothesis, all other statements about variables association become part of H1, H2, .... Hn hypothesis.
Now talking about confidence intervals -
This concept emerges from the case where you compare a set of hypothesis to figure out which one is correct. The way you do it is using data given to you in various forms. You draw conclusions by doing various hypothesis-testing/statistical measures. These conclusions involve calculating certain variables/numbers based on various formulae ( just for example sake: t-test etc ).
Now, these calculated numbers help in rejecting or accepting a certain hypothesis. But since we make certain assumptions about the inference that we are trying to do ( assumptions can be w.r.t the data, model etc) we can never be 100% accurate. Hence we try to find out how sure we are about these calculations ( aka a notion of being confident i.e confidence interval ). So it will totally depend on cases like in medical diagnosis even being 99% sure is not enough hence you need to be REALLY CONFIDENT in this domain. But certain other domains might not be so rigorous and you could maybe go with 95,90 or even 85% confidence intervals.

Note: This is my first answer and I do hope I did a good job!
Comment: That was a nice explanation. You said "In statistics Null Hypothesis i.e. H0 usually states that two variables are not related or there is no association between them". So, how does that relate to my second example:

"Select the hypothesis formulation and the corresponding best values for α, in a Judiciary Scenario so as to avoid punishing an innocent in lieu of which it's okay to pronounce a real case of guilty as not guilty:"
answer is: H0 : Defendant is Innocent, H1 : Defendant is not Innocent, α = 1%.

How do i select which belongs to what in this case. I'm confused because.
Comment: In statistics, H0 is usually assumed to be true and then tests are performed to either reject or accept the H0. Since it's mentioned that by default we assume the person is innocent hence not guilty, this means that the Null Hypothesis H0: Defendant is Innocent ( No relation between Defendant and Guilty ).
Also you mentioned alpha = 1% , the formula relating alpha and confidence interval is : alpha + confidence  = 1. Hence you will need to find out the 99% confidence interval in your case.
Answer: In inferential statistics, the null hypothesis is a general statement or default position that there is no relationship between two measured phenomena, or no association among groups. (e.g. sugar is not linked to obesity)
Testing (rejecting or disproving) the null hypothesis and thus concluding that there are grounds for believing that there is a relationship between two phenomena (e.g. sugar is linked to obesity) is the criteria for rejecting a null hypothesis.
The null hypothesis is generally assumed to be true until evidence indicates otherwise.
In you case it would be
Ho : Sugar is not linked to Obesity
Hi : Sugar is linked to Obesity
When your Probability value(p value) <= level of significance (alpa, usually 0.05),
We reject the null hypothesis, concluding sugar is linked to Obesity
Else we fails to reject the null hypothesis, concluding sugar is not linked to obesity
Comment: that was a nice explanation. you said "the null hypothesis is a general statement or default position that there is no relationship between two measured phenomena". So, in my second example, it should be "H0: Defendant is not Innocent". But, it's the other way. Why and How?
Comment: @NaveenKumar The underlying meaning is defendant is not related to crime. So, Ho: Defendant is innocent


Dropdown em menu vertical com bootstrap 4

Question: Preciso fazer um menu vertical seguindo esse layout porem estou com dificuldades de fazer o menu abrir um dropdown estou usando bootstrap 4 segue meu código + a imagem do layout de como deve ficar.

HTML:

          keyboard
          teste

asdfasdfad

          keyboard
          teste

            keyboard
            teste

          keyboard
          teste

SCSS:
.left {
    position: fixed;
    top: 50%;
    left: 15px;
    background: #337ab7;
    display: inline-block;
    white-space: nowrap;
    width: 50px;
    transition: width .5s;
}

.item:hover {
    background-color: #222;
    width: 250px;
}

.left .fas {
    margin: 15px;
    width: 20px;
    color: #fff;
}

i.fas {
    font-size: 17px;
    vertical-align: middle !important;
}

.item {
    height: 50px;
    overflow: hidden;
    a{
        color: #fff;
    }

    .drop{
        li{
            a{
                display: none;
            }
        }
    }
}

.item{
    a{
        &:hover{
            .drop{
                li{
                    a{
                        display: block;
                    }
                }
            }
        }
    }
}

Answer: Para fazer o drop vc pode usar position:absolute, assim vc tira esse submenu do flow e ele não interfere nos outros elementos ao redor.

Segue o código da imagem acima:

.left {
    position: fixed;
    top: 50%;
    left: 15px;
    background: #337ab7;
    display: inline-block;
    white-space: nowrap;
    width: 50px;
    transition: width 0.5s;
}

.item:hover {
    background-color: #222;
    width: 250px;
}

.left .fas {
    margin: 15px;
    width: 20px;
    color: #fff;
}

i.fas {
    font-size: 17px;
    vertical-align: middle !important;
}

.item {
    height: 50px;
    /* overflow: hidden; */
}

.item a {
    color: #fff;
}

.item .drop li a {
    /* display: none; */
}

.item a:hover .drop li a {
    display: block;
}

.item a:hover .drop li a {
    display: block;
}

.item {
    position: relative;
}

.item > a {
    display: none;
}

.item:hover > a {
    display: initial;
}

.drop {
    margin-left: 50px;
    position: absolute;
    background: black;
    display: none;
    z-index: 2;
}

.item:hover .drop {
    display: block;
    width: calc(100% - 50px);
    padding-inline-start: 0;
    list-style: none;
}

        keyboard
        teste

asdfasdfad

asdfasdfad

asdfasdfad

asdfasdfad

        keyboard
        teste

        keyboard
        teste

        keyboard
        teste

asdfasdfad

asdfasdfad

asdfasdfad

asdfasdfad


Como subir um projeto Spring Boot em um servidor Glassfish ou Tomcat

Question: Consigo executar a aplicação normalmente pela classe principal com o  'tomcat embedded' como dependência.
    Porém ao tentar executar a aplicação em algum servidor a própria IDE Eclipse informa que a aplicação não pode ser executada em um servidor.
    Reconheço a facilidade de usar o Spring Boot para desenvolvimento e testes, porém gostaria de subir a aplicação em um servidor já existente junto á outras aplicações que já estariam rodando neste servidor, sem a necessidade de outra máquina.
    Considerando este cenário,
    Quais dependências devo adicionar ou remover no maven?
    Devo remover a classe principal da aplicação( a que possui o método 'main' e 'SpringApplication.run') ?
    Quais configurações (em Java) devem ser acrescentadas, apenas as que forem essenciais para o projeto web.
Answer: No seu pom.xml troque o empacotamento de jar para war.
<code>    <groupId>br.com.teste</groupId>
    <artifactId>testex</artifactId>
    <version>0.1-SNAPSHOT</version>
    <packaging>war</packaging>
</code>
Coloque a dependência do tomcat como provided.
<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
</code>
Feito isso gere o .war

mvn clean package

Vai ser gerado um arquivo .war dentro da pasta target pronto para ser deployado no tomcat.


Comparing values in previous 2 columns and fill a cell with the lower value

Question: I have a dataframe looks like this:
import pandas as pd
    df = pd.DataFrame({'AA': [1, 1, 2, 2], 'BB': [3, 0, -1, 3.4]})

Now, I need to compare the values in 'AA' and 'BB' then create and fill 'CC' column with the lower values.
I tried many ways, but without defining another function, I think there should be an effective way. What can I try next?
Answer: Then using min with axis
df.min(1)
Out[263]:
0    1.0
1    0.0
2   -1.0
3    2.0
dtype: float64

Answer: Use min and axis, selecting only the series you need:
df['CC'] = df[['AA', 'BB']].min(axis=1)
df
   AA   BB   CC
0   1  3.0  1.0
1   1  0.0  0.0
2   2 -1.0 -1.0
3   2  3.4  2.0


Função recursiva retornando undefined no Javascript com Node

Question: A função recursiva abaixo para de executar quando chega no "if (sorted) " e a condição é verdadeira, como deveria fazer. Só que não importa o que eu coloco para retornar, ela não retorna.
Se eu boto return 1, ela retorna undefined por exemplo.
Não tem lógica isso
OBS: já dei console.log na variável "sorted", ela contém o booleano true.
Sou obrigado a ter um return num else também? Mas dá não funciona nada, porque o sorted na primeira chamada da função, é false, aí ja entra no else e para tudo.
O código está sendo escrito na plataforma Hackerhank. A Main e entradas e saídas já vem configurados.
function minimumSwaps(arr, cont) {
    let sorted = arr.every(isAlreadySorted)
    if (sorted) return 1
......
.....
..
}

E lá na função Main:
function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const n = parseInt(readLine(), 10);

    const arr = readLine().split(' ').map(arrTemp => parseInt(arrTemp, 10));

    var cont = 0
    const res = minimumSwaps(arr, cont);

    ws.write(res + '\n');

    ws.end();
}

minimumSwaps retorna undefined. E logo, o res printado na tela é undefined
Comment: Oi Lucas, podes criar um exemplo com o problema que dê para correr aqui? assim como está falta código para identificarmos o problema...
Answer: A questão é que aparentemente o Javascript no Node não deixa uma função ter return apenas no if e não no else.
A função funcionou corretamente quando eu coloquei a chama recursiva como return do else do if de retorno:
function minimumSwaps(arr, cont) {
....
....
...

    let sorted = arr.every(isAlreadySorted)
    if (sorted) return 1
    else return minimumSwaps(arr, cont)


Tempo de execução em desafio de olimpíada de programação

Question: Olá, preciso fazer a seguinte questão: https://olimpiada.ic.unicamp.br/pratique/p2/2017/f3/arranhaceu/
Eis o enunciado:

Um arranha-céu residencial possui N andares, numerados de 1 a N. O síndico do arranha-céu está tendo muito trabalho com uma nova regra do corpo de bombeiros. Ele não sabe o porquê, mas os bombeiros apontam um andar k e exigem que o síndico informe o total de pessoas que moram no arranha-céu do andar 1 até o andar k, inclusive. Talvez seja alguma medida de segurança dos bombeiros! O problema é que o prédio tem muitos andares e toda hora tem gente se mudando, passando a morar no arranha-céu, ou indo embora. O síndico precisa cuidar de dois eventos:

Mudança: alterar o número de pessoas que moram num determinado andar;
Bombeiro: informar o total de pessoas que moram do andar 1 até um determinado andar, inclusive.

Dados o número de pessoas que moram em cada andar do arranha-céu inicialmente, e uma sequência de eventos (do tipo Mudança ou Bombeiro), seu programa deve imprimir, para cada evento do tipo Bombeiro, o total de pessoas exigido, no momento do evento!
Entrada
  A primeira linha da entrada contém dois inteiros N e Q, representando, respectivamente, o número de andares e o número de eventos. A segunda linha contém N inteiros Ai, 1 ≤ i ≤ N, indicando o número de pessoas que moram no i-ésimo andar inicialmente. Cada uma das Q linhas seguintes representa um evento e tem uma de duas formas:

"0 K P", Mudança, alterar o número de pessoas que moram no K-ésimo andar para P pessoas;
"1 K", Bombeiro, informar o total de pessoas que moram do andar 1 até o andar K, inclusive.

Saída
  Para cada evento do tipo Bombeiro, seu programa deve imprimir uma linha contendo um inteiro representando o total de pessoas correspondente aquele evento.
Restrições
  1 ≤ N ≤ 105 e 1 ≤ Q ≤ N
  Há pelo menos um evento do tipo Bombeiro.
  1 ≤ K ≤ N
  0 ≤ Ai ≤ 1000 e 0 ≤ P ≤ 1000
Informações sobre a pontuação

Em um conjunto de casos de teste somando 20 pontos, N ≤ 20000

Exemplos
Entrada:
8 4
30 2 0 42 10 11 11 9
1 5
0 4 12
1 5
1 1

Saída:
84
54
30

Entrada:
1 1
0
1 1

Saída:
0

O código que fiz é esse:
#include <stdio.h>

int main(){

    int n, q, k, p, contEventos, evento, totalPessoas, i, pessoas[100000];

    scanf("%d %d", &n, &q);

    for(i = 0; i < n; i++){
        scanf("%d", &pessoas[i]);
    }

    for(contEventos = 0; contEventos < q; contEventos++){

        scanf("%d", &evento);
        scanf("%d", &k);

        if(evento == 0){

            scanf("%d", &p);
            pessoas[k - 1] = p;

        }else if(evento == 1){

            totalPessoas = 0;

            for(i = 0; i < k; i++){
                totalPessoas += pessoas[i];
            }

            printf("%d\n", totalPessoas);

        }
    }

    return 0;
}

Pelos casos de teste que eles disponibilizam funciona bem. Porém na hora de submeter a solução, nos outros testes meu código excede o tempo máximo de execução de 1000ms. O que posso fazer pra diminuir este tempo de execução?
Correção do meu código:

Compilação correta
Fase de testes -- Tempo Limite para cada execução: 1000 ms
  Teste  1: ........     (20 pontos)
  Teste  2: TTTT     (0 pontos)
  Teste  3: TT     (0 pontos)
  Teste  4: TT     (0 pontos)
  Teste  5: TTTT     (0 pontos)
Total: 20 pontos (de 100 possíveis)
Legenda:
.: resultado correto
X: resultado incorreto
E: erro em tempo de execução
M: Referência a memória inválida
S: programa não gerou saída
T: tempo limite excedido
V: violação de recursos
Answer: O seu problema
O problema é o seguinte: Imagine um prédio com 100.000 andares e que os bombeiros pedem insistentemente milhares de vezes para saber quantas pessoas têm até o último andar. Isso vai fazer o seu programa consumir um tempão calculando e recalculando o totalPessoas. Cada consulta percorreria n andares e são q consultas no total, logo o tempo nesse caso vai ser proporcional a O(nq).
Outras soluções que não funcionam
Você poderia pensar em uma abordagem de recalcular tudo só quando alguém se mudar e guardar o resultado numa variável. Mas daí, deve haver algum teste onde ocorrem milhares de mudanças e o seu programa vai de novo estourar o tempo com O(nq).
Você pode pensar em fazer um array auxiliar que mostre o acumulado de pessoas até cada um dos andares, para consultá-lo quando os bombeiros chegarem. Mas nesse caso, você teria que reconstruir a tabela quando houverem mudanças a partir do andar onde ocorreu a mudança, e deve haver algum teste onde ocorrem milhares de mudanças no primeiro andar, e o resultado é novamente O(nq).
Divisão e conquista
Talvez uma abordagem de dividir e conquistar seja a solução. Se você manter uma contagem do número de pessoas na metade inferior do prédio em uma variável (vamos chamar de x), a consulta dos bombeiros na metade superior ficará bem mais rápida, pois você não precisará recontar a metade inferior, basta usar o valor x). Da mesma forma, se houver alguma mudança na metade inferior do prédio, você só precisará recalcular o valor x da metade inferior do prédio, sem se preocupar com os valores da metade superior.
Usando-se essa ideia recursivamente, subdivide-se cada bloco de andares pela metade até chegar a um ponto onde se tem um bloco de apenas um andar. Então junta-se os blocos de 2-em-2 somando-se o número de pessoas em cada andar. Depois, junta-se esses blocos maiores de 2-em-2 também formando blocos ainda maiores até você ter um bloco que representa o prédio inteiro.
Para um prédio de 12 andares, o resultado é o que está abaixo:

Andares que não existem por estarem depois do último são considerados como zeros. Por exemplo, o 193 da quarta coluna deveria agrupar 8 andares ao invés de 4, mas o prédio acaba antes disso e portanto o que tem depois são apenas zeros.
Como descobrir quantas pessoas têm até algum andar?
Ok, mas como podemos saber quantas pessoas têm nos 9 primeiros andares, por exemplo?
A resposta é que os 8 primeiros andares têm 134 pessoas e o 9º tem 77. Logo a resposta é 134 + 77 = 211 pessoas.
E se quisermos os 7 primeiros andares?
A resposta é que os 4 primeiros tem 88, o 5º e o 6º juntos têm 9 e o 7º tem 24. Logo a resposta é 88 + 9 + 24 = 121 pessoas.
E se em um prédio maior que esse, quisermos até o 42º andar?
Nesse caso pega-se o número de pessoas dos 32 primeiros andares, mais o número de pessoas dos 8 andares do 31º ao 40º e então o número de pessoas do 41º junto com o 42º.
Mas como saber quais desses blocos de tamanhos diferentes escolher?
É só olhar para o número escrito em binário. Por exemplo:

9 é 1001, ou seja, 8 + 1. Então pega-se um bloco correspondente a 8 andares seguido de um bloco de 1 andar.
7 é 111, ou seja, 4 + 2 + 1. Então pega-se um bloco correspondente a 4 andares seguido de mais um de 2 andares e então um de 1 andar.
42 é 101010, ou seja, 32 + 8 + 2. Então pega-se um bloco de 32 andares, um de 8 e um de 2.

Na imagem do prédio, o próprio prédio azul corresponde aos blocos de tamanho 1, a fila amarela à sua direita os de tamanho 2, depois os de tamanho 4, 8, 16 e assim por diante. Dessa forma, é possível saber de quais colunas os blocos devem ser escolhidos.
Note que nunca dois blocos da mesma coluna são acessados nesta operação.
Como mudar a quantidade de moradores de um andar?
Essa é fácil, altera-se o bloco correspondente ao andar e todos os blocos à direita dele. Os demais blocos não precisam ser recalculados.
Complexidade da solução.
Quantas blocos (cada um numa coluna diferente) cada operação de mudança ou de contagem pelos bombeiros é acessado?

Num prédio de 1 andar, 1 bloco.
Num prédio de 2 andares, 2 blocos.
Num prédio de 3 a 4 andares, 3 blocos.
Num prédio de 5 a 8 andares, 4 blocos.
Num prédio de 9 a 16 andares, 5 blocos.
Num prédio de 17 a 32 andares, 6 blocos.
...
Num prédio de 32.769 a 65.536 andares, 17 blocos.
Num prédio de 65.537 a 131.072 andares, 18 blocos.

Isso começou a ficar legal. Nesse caso, qualquer operação que exija a recontagem das pessoas (seja a mudança ou seja os bombeiros) vai acabar consumindo tempo proporcional a 1 + log2 n. Portanto a complexidade total é O(q log2 n). Considerando que n é 100.000, e que 1 + log2 n é próximo a 18, isso claramente é bem melhor que qualquer solução O(nq).
Organizando a solução
Agora precisamos ver como organizamos isso na memória. Podemos usar uma matriz com 18 x 100.000, afinal de contas, 18 é o máximo de colunas de blocos que temos e 100.000 é o máximo de andares. Declaramos então pessoas[CAMADAS][MAX_N], onde CAMADAS é 18 e MAX_N é 100.000.
Os blocos são organizados sequencialmente em cada fileira da matriz assim:

Com essa lógica, o bloco i da coluna t é pai dos blocos 2 * i e 2 * i + 1 da coluna t - 1. Isso é importante para construir esses blocos depois que o prédio for montado:
pessoas[t][i] = pessoas[t - 1][2 * i] + pessoas[t - 1][2 * i + 1];

Pelo lado contrário, o bloco k da coluna t é filho do bloco k / 2 da coluna t + 1 (e portanto k / 2 é pai de k). Note que essa divisão é inteira.
Assim sendo, o irmão do bloco i em uma coluna t qualquer é o bloco i ^ 1 nessa mesma coluna. Esse ^ 1 serve para inverter o último bit de um número, transformando um número par num ímpar e um ímpar num par.
Ao atualizar o valor do andar k (na verdade k - 1, pois como você já percebeu, esse - 1 serve para começar a contar do 0), o bloco pai vai receber a soma dos valores dos filhos. Logo, a expressão para atualizar um bloco pai na coluna t a partir do valor alterado no filho k é:
pessoas[t][k / 2] = pessoas[t - 1][k] + pessoas[t - 1][k ^ 1];

Para os bombeiros verificarem o número de pessoas até determinado andar k, para cada camada t, olha-se os blocos k dessa camada. Para atualizar o k na hora de pular da camada t para a camada t + 1, basta fazer k /= 2;. No entanto, só são considerados os blocos que correspondem aos bits 1 tal como já explanado, o que pode ser verificado com k & 1, considerando-se que o k está mudando nessa iteração. Ou seja:
for (t = 0; t < CAMADAS && k > 0; t++) {
    if (k & 1) totalPessoas += pessoas[t][k - 1];
    k /= 2;
}

Código resultante
No final, o resultado é isso:
#include <stdio.h>

#define MAX_N 100000
#define CAMADAS 18

int main() {

    int n, q, k, p, t, contEventos, evento, totalPessoas, i, pessoas[CAMADAS][MAX_N];

    scanf("%d %d", &n, &q);

    for (i = 0; i < n; i++) {
        scanf("%d", &pessoas[0][i]);
    }
    for (; i < MAX_N; i++) {
        pessoas[0][i] = 0;
    }
    for (t = 1; t < CAMADAS; t++) {
        for (i = 0; i < MAX_N / 2; i++) {
            pessoas[t][i] = pessoas[t - 1][2 * i] + pessoas[t - 1][2 * i + 1];
        }
        for (; i < MAX_N; i++) {
            pessoas[t][i] = 0;
        }
    }

    for (contEventos = 0; contEventos < q; contEventos++) {
        scanf("%d", &evento);
        scanf("%d", &k);

        if (evento == 0) {
            scanf("%d", &p);
            k--;
            pessoas[0][k] = p;
            for (t = 1; t < CAMADAS; t++) {
                pessoas[t][k / 2] = pessoas[t - 1][k] + pessoas[t - 1][k ^ 1];
                k /= 2;
            }
        } else if (evento == 1) {
            totalPessoas = 0;

            for (t = 0; t < CAMADAS && k > 0; t++) {
                if (k & 1) totalPessoas += pessoas[t][k - 1];
                k /= 2;
            }

            printf("%d\n", totalPessoas);
        }

        // Para mostrar a tabela.
        /*for (int y = 0; y < CAMADAS; y++) {
            printf("\n|");
            for (int z = 0; z < n; z++) {
                printf("%d ", pessoas[y][z]);
            }
            printf("|\n");
        }*/
    }

    return 0;
}

Os laços que têm pessoas[0][i] = 0; e pessoas[t][i] = 0; servem para limpar as posições não utilizadas da tabela para evitar que sujeira/lixo pré-existente na memória atrapalhem o cálculo.
Note que a tabela desperdiça uma boa quantidade de memória, pois grande parte das posições dela ficam sempre vazias mesmo para um prédio de 100.000 andares cheio de gente em todos os andares. A tabela tem 1.800.000 posições, e até é possível reduzir-se o tamanho dela com algumas operações matemáticas para 199.985 posições, que é o tamanho mínimo dela. No entanto o código para fazer isso ficaria bem mais complexo e mais difícil de entender e o ganho de desempenho seria desprezível.
Veja aqui funcionando no ideone.
Comment: @VictorStafusa, problemas da OBI tem complexidade o suficiente para serem intercambiados facilmente com os da maratona ACM-ICPC. Então, sim, quem faz essas questões de OBI está pensando em gente que tenha pelo menos uns 4 anos de programação e treino para programação competitiva. Ou seja: pessoas que treinam desde o 6 ano do ensino fundamental
Comment: Achei excelente essa sua abordagem ao problema, que ainda não me tinha ocorrido. E suspeito que era a solução que o autor do problema esperava.
Comment: Sua resposta foi muito melhor do que eu esperava, parabéns. Porém eu achei um tanto confusa a resolução. Vc usou operadores de bit que eu nem sabia sobre. Analisando com um pouco mais de tempo tenho certeza que vou conseguir entender, mas o ponto é, visto que essa questão foi dada pra alunos do ensino médio, será que não tem uma solução "menos" complexa?
Comment: @AntonyLeme Para alunos do ensino médio é de se esperar soluções mais simplistas como a que você tinha, sem ter limitação de tempo. Agora, exigir o comportamento ótimo disso a partir de alunos do ensino médio é loucura, insanidade, maluquice, crueldade. Há coisas aqui que dependem de conhecimento que só é adquirido lá pelo 5º ou 6º semestre de um curso superior de ciência da computação, e que boa parte dos alunos estuda só pra passar na prova e depois esquece.
Comment: @VictorStafusa entendi. Como se trata de uma olimpíada, imagino que seja da intenção deles cobrar essas coisas a mais. Sua resolução me atentou pra algumas coisas que vou tentar entender melhor, pra talvez ganhar uns pontos a mais em alguma questão. Talvez não seja tão preocupante, já que teoricamente meus concorrentes têm o mesmo nível de conhecimento que eu. De qualquer forma, obrigado.


Records are not coming in textfile from mysql

Question: Here, I want to fetch record from mysql to textfile that I am writing into textfile.
But textfile is creating as blank.
Where is the problem?
My code:
$myFile = 'abctest.txt';
//echo $myFile;exit;
$fo = fopen('com_order/order_textfile/'.$myFile, 'w+') or die("can't open file");

$data_query=mysql_query("SELECT order_id from tbl_order") or die(mysql_error());

while($data=mysql_fetch_array($data_query))
{
    $stringData = fwrite($fo, "Order: ".$data['order_id']."\n");
}
fwrite($fo, $stringData);
fclose($fo);

header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$myFile);

Comment: What is the output from `mysql_error()` if any?
Comment: No @TimBiegeleisen: Its shows nothing.
Answer: readfile() call is missing:
readfile($myFile);

So it should look like this:
header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$myFile);
readfile($myFile);

Here readfile() is the function which actually performs all the hard work (reads the file, writes to output).
More on the topic:
readfile()
Force download
UPDATE
Also you have a file path problem
Note that you create file in com_order/order_textfile/'.$myFile but then use $myFile without the path. When referencing file you should use path instead:
$myFile = 'abctest.txt';
$filePath = 'com_order/order_textfile/'.$myFile;
$fo = fopen($filePath, 'w+') or die("can't open file");

$data_query=mysql_query("SELECT order_id from tbl_order") or die(mysql_error());

while($data=mysql_fetch_array($data_query))
{
    $stringData = fwrite($fo, "Order: ".$data['order_id']."\n");
}
fwrite($fo, $stringData);
fclose($fo);

header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$filePath);
readfile($filePath);

Comment: Thanks, but No records are coming in textfile.. !!
Comment: Yeah...Now I get what I want...!! Thanks palovich.
Answer: It seems like there is a problem with the way you execute your query but try the code below it's working.
$link = mysqli_connect("localhost", "username", "password", "database name") or die("error unable to connect to database". mysqli_error($link));

$myFile = 'abctest.txt';
//echo $myFile;exit;
$fo = fopen('com_order/order_textfile/'.$myFile, 'w+') or die("can't open file");

$data_query=$link->query("SELECT order_id from tbl_order") or die(mysql_error());

while($data=mysqli_fetch_array($data_query))
{
    $stringData = fwrite($fo, "Order: ".$data['order_id']."\n");
    //echo("$stringData");
}
fwrite($fo, $stringData);
fclose($fo);

header('Content-type: text/plain');
header('Content-disposition: attachment; filename='.$myFile);

Comment: Thanks, but No records are coming in textfile.. !!
Comment: Make sure the following is correct 1) directory to your text file 2) query.


For every integer $n$, the quantity $n^2 + 2n \equiv 0\pmod 4$ or $n^2 + 2n \equiv 3\pmod 4$

Question: I'm trying to prove this question using induction
So far I have
Base Case
Let $n = 1$, $(1^2 + 2)\equiv 3 \pmod 4 $
Claim holds for base case
Induction
Assume $n = k$ holds, that is $k^2 + 2k \equiv 0\pmod 4$ or  $k^2 + 2k \equiv 3\pmod 4$
Let $n = k+1$ such that
$${(k+1)^2 + 2(k+1)}\equiv {k^2 + 2k + 1 + 2k + 2}\pmod 4$$
Then I substitute $k^2 + 2k$ with both $0$ or $3$ from the earlier assumption.
So we have
$$(0 + 2k + 3) \equiv (2k + 3) \pmod 4$$
Or,
$$(3 + 2k + 3) \equiv (2k + 6) \pmod 4$$
Where do I go from here?
Comment: Are you sure you want to use induction in particular? It seems to be easier in this case to write $n^2+2n=(n+2)n$, and then we see immediately that the two factors are either (in some order) $0$ and $2$ modulo $4$, or $1$ and $3$ modulo $4$ ...
Comment: The base case should be four base cases, say 1,2,3,4. Then given truth for $k,$ prove the thing is also true for $k+4.$
Comment: **Hint** adding $1$ shows it's equivalent to: $\,\rm \underbrace{squares}_{\ \large (n+1)^{\Large 2}}$ are $\equiv 1\,$ or $\,0\pmod{\!4};\,$ indeed $\rm\, {odd}^{\large 2}\equiv 1,\ {even}^{\large 2}\equiv 0\ \ \ $
Answer: Separate cases for $n$ even and $n$ odd.
If $n$ is even, than it is $n=2m$.
We get: $(2m)^2+2(2m)=4m^2+4m=4(m^2+m)\equiv 0\mod 4$
If $n$ is odd, then it is $n=2m+1$.
We get: $(2m+1)^2+2(2m+1)=4m^2+4m+1+4m+2=4(m^2+2m)+3\equiv 3\mod 4$
Answer: $$n^2+2n=(n+1)^2-1$$
Now $n+1\equiv0,\pm1,2\pmod4$
$\implies(n+1)^2\equiv0,1\pmod4$
$(n+1)^2-1\equiv?,?$
Answer: From where you are stuck, we can do the following case distinction:
Case 1: $k^2+2k \equiv 0 \mod 4$. Notice that in this case $k$ cannot be an odd number. And any even $k$ satisfies this (can be proven by induction). Therefore $k = 2m$ for some integer $m$. Then,
$$2k+3 = 4m+3 \equiv3 \mod 4$$
Case 2: $k^2+2k \equiv 3 \mod 4$. Notice that in this case $k$ cannot be an even number. And any odd $k$ satisfies this (can be proven by induction). Therefore $k = 2m+1$ for some integer $m$. Then,
$$2k+6 = 4m+9 \equiv1 \mod 4$$
But instead of doing this, Cornman's answer is shorter and better since we are doing the case distinction anyway so why would we have to do an additional induction when a case distinction itself can be done for proving? I'm posting this just to complete your solution. So I refer to Cornman's answer.
Answer: You only need one equation.
$\begin{array}\\
(n+2)^2+2(n+2)
-(n^2+2n)
&=n^2+4n+4+2n+4
-(n^2+2n)\\
&=4n+8\\
\end{array}
$
which is divisible by $4$,
so whatever remainder $n$ has
mod 4, $n+2$ also has.
Since $n=0 \implies n^2+2n = 0$,
all even numbers have a
remainder of 0 mod 4.
Since $n=1 \implies n^2+2n = 3$,
all odd numbers have a
remainder of 3 mod 4.
Comment: Simpler: $\large \bmod \color{#c00}4\!:\,\ \overbrace{\color{#c00}n(n\!+\!2)}^{\Large f(n)} \equiv \overbrace{(n\!+\!2)(\color{#c00}{n\!+\!4})}^{\Large f(n+2)}\ \ $
Comment: Cute. Would be a good answer.


Modal with content depending on opening hours

Question: I need the user to enter opening hours for their helpline in the CMS along with two sets of text, one that will be displayed if the user views it during their opening hours & another which is displayed outside of their opening hours.
This content needs to be displayed in a modal on specified pages when a link is clicked (a 'modal box' is like a JavaScript overlay on the page).
The way I have been trying to approach the problem (taken from a suggestion else where on Stack Exchange) was to use the Office Hours & Colorbox Node modules together. Unfortunately unless I've misunderstood what Colorbox Node does or how it works I cannot get it to open a modal at all, I can't actually get it to do anything.
Below are the steps I've taken to install the Office Hours & the Colorbox Node modules so hopefully someone can spot what I've done wrong. I am more than open to other suggestions to solve this problem though.
Using the two modules mentioned my plan was to create a custom template which would read the current date & time, compare it to what has been entered into the Office Hours module then display the appropriate text from one of two text area fields in the CMS.

Created fresh Drupal 7 install
Installed Office Hours 7.x-1.4 module (https://www.drupal.org/project/office_hours)
2a. Installed required module Date api 7.x-2.9 (https://www.drupal.org/project/date)
Installed Colorbox node 7.x-3.5 module (https://www.drupal.org/project/colorbox_node)
3a. Installed required module colorbox 7.x-2.10 (https://www.drupal.org/project/colorbox)
3b. Installed required module Libaries 7.x-2.2 (https://www.drupal.org/project/libraries)
Created new content type with the Office Hours field
Created new node setting the new office hours
Created test page with link to office hours page, link has class of "colorbox-node" which should show a modal?

This is what the link tag currently looks like:
Test link

Comment: is there a javascript error ? how does your colorbox-node link look like, does it have width and height specified ?
Comment: @rémy I've tried the link both with & without the width & height specified without any success. The link now looks like Test link. I'll update the question to include it in a moment too.
Comment: Try looking in the browser dev tool's console to see if there is a JS error when you click the link, and post what you find if something is there.
Comment: @AlexFinnarn I've checked that but noting appears in the console.
Comment: can you provide a link to the page ?
Comment: @rémy here's a like to the page which should open a modal.
http://drupal-test.neilnand.co.uk/node/2
Answer: if you run your site under an url like example.com/dat/fresh/site/, remove the first slash in the href, like:
Test link

or change to full path, like:
Test link

Comment: Answers that are only "guesses" are assumed to be posted as comments. Therefor I recommend to EDIT your answer to remove the guessing part of it. Just a suggestion (to avoid it gets converted to a comment by moderators ....)
Comment: Thanks for the answer but the site is hosted on a sub-domain, the page that has the link that should open a modal is http://drupal-test.neilnand.co.uk/node/2
Answer: I've managed to work it out, was a very simple problem.
When I installed the colorbox module (not colorbox node) I just installed the module but I need to copy the colorbox plugin into the Drupal libraries directory as well. Soon as I knew found this out and did it, it has started working.


What is the purpose of having multiple neurons in each layer?

Question: I started a deep learning course (introductory one). But I have two years experience working with ML projects on my own time. This course is just for me to understand deep learning at a more fundamental level.
Starting with a single layer perceptron, it makes sense. We have a linear function to act as a hypothesis. Then that output is fed to an activation function that adds non-linearity and normalises outputs.
That totally makes sense to me. Now my understanding so far:

When we have multiple neurons in a layer, the connections to the neuron represents some weight. The neuron itself is just an activation function. (That is just notation though) and each neuron has its own set of weights to match the number of features.

Having read this question and its answers, I understand that stacking layers just adds more non-linearity. While stacking a linear function on a linear function, our function is still linear. But there is a limit to how much we can learn at any order, and adding layers just means we can have a more complex decision boundary. That said, a model too deep can be prone to overfitting.

Batch Normalisation then aims to normalise inputs to make distributions simpler for each layer while also making backpropagation faster.
Dropout looks to prevent overfitting through randomly dropping neurons to see if we can learn without that specific layer.
But why would there be multiple neurons per layer? Is it just like poling/averaging where you have more candidates to chose from to ensure confidence and correctness? Or is each neuron learning something else entirely?
Answer:
Or is each neuron learning something else entirely?

This is the purpose, although I wouldn't say they learn entirely different things since they might have some correlation. Each neuron will have its own view of the data and produces outputs according to it. It's like multiple people from different perspectives looking at the same thing, sharing their opinions, and these opinions are aggregated over and over again in the subsequent layers.
Comment: Thank you for this. It makes sense now. They are all making different inferences based on different knowledge (weights).
Comment: And since each neuron gives a single valued output, when cascading, I think the output for each neuron can be seen as a single feature to the next layer.

So if my first layer has few neurons, the next layers have very few layers. And I doubt the second layer having only one feature can be enough.
Comment: Correct, sometimes hidden layer outputs are used as features for other ML algorithms as well. You can manage with one neuron in the second hidden layer (according to universal approximation theorem), but then your first layer may have exponentially larger number of neurons.
Answer: Neural network is basically a tensor function (tensors = scalars, vectors, matrices etc.). It takes stuff in (e.g. vector of some features), compoundly apply some operations like matrix multipication or activation functions, and produces stuff out (e.g. vector of probability distribution over some classes).
The term neuron basically refers to a particular element of a tensor. Having 1 neuron in a layer = the layer would consist of a scalar value (or equivalently vector of size 1, matrix of size 1x1 etc.). Usually, it's good idea to have more dimensional tensors in a network.
Example: You have network that takes an input of 10-dimensional vector, apply matrix multiplication (the matrix is a learnable parameter) to get a vector of 64-dimension, then apply elementwise activation function (e.g. RELU), then apply e.g. softmax classification to get probability distribution over 7 classes.
The hidden layer have 64 neurons, which means that the vector have a dimensionality of 64. If it would have only a dimensionality of 1, the capacity (complexity) of the network would be much lower.
Comment: Thank you for your answer Jakub, I was typing my answer to my own question and then I just saw your answer. It makes a lot more sense now.

A layer's output represents the number of input values the next layer gets. So giving it a single neuron just means there is only one feature to learn from.
Answer: I think I have the answer having taken some time out.
When we run a neuron, it is a glorified $z=W.T*x +b$ followed by $sigmoid(z)$
As a result, the output is just a single value in a certain range. If a layer has 100 neurons, it has 100 such features.
When we cascade and add multiple layers, the output of $L1$ is the input to $L2$. As a result, if $L1$ has only a single neuron, the next layer has only one feature to learn from. So adding more layers just allows us to get more features and better represent our data.
Answer: Expanding upon what @gunes said, if you take a shallow network and explicitly trace out what the network's forward pass is. You can see the adding of additional nodes (within a layer) allows the network to minimise its prediction error.
Let's assume we have some Feed-Forward Neural Network (FFNN) that takes in a single input and a single output and has a single hidden layer of N hidden nodes, and a non-linear activation function denoted, $\sigma$, and the entire forward pass of the network can be described as $\hat{y} = f(x)$, where $\hat{y}$ is the prediction of the true output $y$.
For N = 1, the network can be written as,
$$ \hat{y} = w^{(2)}\sigma(w^{(1)}x_j + b^{(1)})$$
for a given number of hidden nodes, N, it's written as a sum of single neurons, i.e.,
$$ \hat{y} = \sum_i w^{(2)}_{i}\sigma(w^{(1)}_ix_j + b^{(1)}_i) $$
If we look at this from a linear regression standpoint we would minimise a loss function, for example the Mean Absolute Error (MAE), in order to tune the weights and biases such that our network accurately predicts our training data.
Let's apply the Universal Approximation Theorem to see what adding more neurons does. Let's say we have a single hidden node in our network and we give our network a single example pair $(x_j, y_j)$, this would give a prediction $\hat{y_j}$ which would have an error of $\vert y_j - \hat{y}_j \vert$. We would then use some optimization algorithm (SGD, RMSprop, Adam etc...) to minimise this error. However, a single hidden node can only 'learn' so much and will eventually hit a local minimum where it'll learn no more.
This would be written out like,
$$\hat{y}_j = w^{(2)}_1\sigma(w^{(1)}_1 x_j + b^{(1)}_1)$$
and let's say (for the sake of argument) the lowest error we can get is 10. This error of 10 can be minimising by adding a new neuron. Let's say the target $y_j$ is 20 and our model predicts $\hat{y}_j$ = 10 (giving the error of 10 from above). We can add a new neuron to try and reduce this error by getting the new neuron to output a contribution to the total sum which minimising our error. And, let's say the best the 2nd neuron can do is an output of 5 - which would bring out total MAE to 5.
$$\hat{y}_j = \underbrace{w^{(2)}_1\sigma(w^{(1)}_1 x_j + b^{(1)}_1)}_{\text{first neuron outputs 10}} + \underbrace{w^{(2)}_2\sigma(w^{(1)}_2 x_j + b^{(1)}_2)}_{\text{second neuron outputs 5}} $$
In this two neuron case, the best the model can do is 15 and in principle, we can keep adding neurons to the layer to reduce this error. Leading to the Univeral Approximation Theorem stating that a neural network can approximate any continuous function if given enough nodes to do so.
In short, the neurons for a given layer allow the network to transform the input in a certain manner and having fewer neurons restricts the ability of the layer to transform the data in the 'correct' way. Which in the case of deeper networks this restricts the ability of higher layers in transforming the data because the initial transformation they get are 'further' away (in terms of a loss metric) from the exact transformation!


Using sticky-enabled Table Headers causes IE10 to crash on printing

Question: A customer complained that printing a Views page on my Drupal 7.23 (Marinelli 7.x-3.0-beta11) Site causes IE10 to error ("Internet Explorer has stopped working").  And he's right.  Works fine on Firefox, Chrome, Opera, even IE9 (but not IE 10 Browser Mode IE9).  It does work in IE10 in Document Mode 'quirks'.
On investigation it boils down to using sticky table headers - use them fail, turn them off fine!  I found that code in misc/tableheader.js lines 12-14 (below) 'helps' IE10 create the problem.
So, I have a crude workaround, but would prefer to do something more elegant. Anyone encountered this problem and have a workaround (short of not using IE10?).
$('table.sticky-enabled', context).once('tableheader', function () {
  $(this).data("drupal-tableheader", new Drupal.tableHeader(this));
});

Update - I guess it is naïve of me to expect someone to identify the error either in Drupal core, the theme, Views or my code which causes this problem. Certainly not without providing more information.  I was hoping it might 'ring a bell' and thus satisfy my curiosity.
Can I ask for more specific advice?  I found elsewhere the code below to include in template.php as a more elegant way of disabling sticky headers than no-oping the function in drupal tableheaders.js.  Can anyone please suggest how I can restrict this to print requests only? Thanks Ron
function marinelli_js_alter(&$js) {
  unset($js['misc/tableheader.js']);
}

Comment: thx kiamlaluno, neat!  You'd never guess I'm a newbie to posting on stackexchange also to Drupal - most of my sites are either wordpress or native html/php.
Comment: Hello and welcome. It seems it's either bug in Drupal core or more plausibly in IE, and it's generally not allowed to post bugreports here. If you know (or will know) the way to work around and need help with implementing it, it will be valid question all right.
Answer: In the last paragraph you talk about hook_js_alter.
Basically the first part should be a name of your template or custom module, so if your module will be named ie_workaround.module function should look like this:
function ie_workaround_js_alter(&$js) {
  unset($js['misc/tableheader.js']);
}

It's important to do your best to have this hook executed when this element is already set by the module or theme that sets it. You can do this using hook_module_implements_alter and placing your hook at the end of hooks array.
Comment: thx Molot.  It works :).  How  do I restrict it to print (am OK with php but new to delving into drupal)?
Comment: @Ron problem is that [script tag](http://www.w3schools.com/tags/tag_script.asp) does not support [media attribute](http://www.w3schools.com/tags/att_link_media.asp) like [link tag](http://www.w3schools.com/tags/tag_link.asp). It means you can restrict CSS to certain media, like screen or print, but you cannot do this for javascript. No version of HTML allows it. And PHP (so, Drupal) does not know why browser requested a page and cannot predict what is it going to do with returned HTML.


content was blocked because it was not signed by a valid security certificate error when using browserstack

Question: Using browserstack to test my app in different browsers and getting the following error: content was blocked because it was not signed by a valid security certificate
Is there any way to bypass that?
Answer: If you are using a self-signed certificate you have to set acceptSslCerts parameter to True in your configuration.
Comment: where to set this parameter? i didn't find acceptSslCerts in my configuration.


Fastest way to look up value in previous period?

Question: I have a dataset of household retail purchases of products. For each household trip, I would like to look up whether any brands purchased during that trip by that household were purchased in the previous period - if so, loyal=1 else loyal=0. I have a large dataset with billions of observations, so the more efficient the better. :)
library(data.table)
household <-  as.integer(c(1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3))
trip      <- as.integer(c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9))
brand     <- as.integer(c(1,2,3,4,5,6,7,5,1,6,8,9,9,2,8,1,3,4,5,6,7,8,9,1,1,2,3,4,1,5,6,7,1,8,9,2))
DT <- data.table(household,trip,brand)

Desired output:
> DT
             household trip loyal
[1,]         1        1    NA
[2,]         1        2     0
[3,]         1        3     1
[4,]         2        4    NA
[5,]         2        5     0
[6,]         2        6     0
[7,]         3        7    NA
[8,]         3        8     1
[9,]         3        9     1

I tried something like this but it's obviously not producing the desired output.
DT$loyal <- 0
for (h in unique(DT$household)){
  for (t in unique(DT$trip)){
    DT[brand %in% (DT[trip=t-1]$brand)]$loyal <- 1
  }}

Comment: thanks, I've corrected it :)
Comment: Minor point: don't use `cbind` on columns to build a table, just do `data.table(household, trip, loyal)`. Also, using integers for integer-like numbers will usually speed stuff up.
Answer: You can self join in order to get an index and then join again to a unique combination of household and trip. This comes to mind
# Create a column of the previous trip
DT[, prev_trip := trip - 1L]

# Self join
indx <-
  DT[DT
   ,.(household, trip)
   ,on = .(household, prev_trip = trip, brand)
   ,nomatch = 0L]

# A unique combination `household` and `trip` joined with the index
res <- unique(DT[, .(household, trip)])[indx, on = .(household, trip), loyal := 1L]
res
#    household trip loyal
# 1:         1    1    NA
# 2:         1    2    NA
# 3:         1    3     1
# 4:         2    4    NA
# 5:         2    5    NA
# 6:         2    6    NA
# 7:         3    7    NA
# 8:         3    8     1
# 9:         3    9     1

Not sure if the 0 are critical there as they don't look very informative to me but it is easy to add them later if needed
Comment: Alternate self-join: `DT[, loyal_brand := .SD[.(household = household, trip = trip - 1L, brand = brand), on=.(household, trip, brand), .N, by=.EACHI]$N > 0L]; DT[, loyal := any(loyal_brand), by=.(household, trip)]`
Comment: Thanks!  This is exactly what I needed.


Sum of Normally Distributed Random Variables

Question: I am aware that the sum of two (or more) normally distributed Random Variables is not necessarily also normal.
I do have questions regarding the special case where I have the following addition:
For c $\in \mathbb R$, is c + N(0,a), where I add a normal Random Variable with mean zero and variance a to c, is then the sum normally distributed? Also, does this addition correspond to drawing a random variable X too from a Normal distribution with mean and then add it to N(0,a)?
Hope the question is clear, thanks
Answer:
I am aware that the sum of two (or more) normally distributed Random Variables is not necessarily also normal.

Yes, it's usually only the case if they're jointly normal (multivariate normal)

For c ∈R, is c + N(0,a), where I add a normal Random Variable with mean zero and variance a to c, is then the sum normally distributed?

Yes.

Also, does this addition correspond to drawing a random variable X too from a Normal distribution with mean and then add it to N(0,a)?

You mean, if $Y\sim N(0,a)$ and $X\sim N(\mu_X,\sigma^2_x)$? The previous result means that $X+Y|X=c$ is normal. That's useless when you don't condition on the value of $X$, though, and then the form of the dependence between $X$ and $Y$ that you started with again comes in.
Comment: Your conclusion that 'sums of random variables can be understood as conditioned probabilities' is ... pretty much a misunderstanding of what was going on. A conclusion based on adding a constant to a random variable carries over to adding two random variables *if one of them is held constant*. That 'holding one constant' is what introduces conditional distributions. If you *don't* hold it constant, the conclusion based on adding a constant *simply doesn't apply*. It's not complicated or mysterious - it's a result of adding constants and attempting to generalize to adding random variables.
Comment: I see. So then c + N(0,a) is normally distributed with N(c,a) - is this correct? What is the conditioning you mention in this case? Not sure I understand that part
Comment: "*So then c + N(0,a) is normally distributed with N(c,a)*"  Yes. The conditioning is conditioning on $X$ taking the value $c$. http://en.wikipedia.org/wiki/Conditional_probability_distribution; these kinds of ideas are covered in pretty much any basic college level mathematical statistics/probability text.
Comment: I know about conditioned probabilities, but I had never read that sums of random variables can be understood as conditioned probabilities too...did not think that was covered in any basic text.


Remove certain string from word Excel VBA

Question: So I have a certain word within a word in a cell in excel that I'm trying to remove. For instance in one of the cells I have P/N279-82345 and I'm trying to get rid of the P/N in the front but keep the rest. I know there is the like function but is there a way to use the like function to remove just the P/N?
Thank You
Answer is
x = Replace(ws2.Cells(i, 1), "P/N", "")

Comment: `Replace` is what you need
Answer: Use the replace function.
Syntax can be found here: https://support.office.com/en-us/article/REPLACE-REPLACEB-functions-8d799074-2425-4a8a-84bc-82472868878a
Answer: if you are looking for a VBA macro function you can use something like:
Cells(1, 1).Value = Replace(Cells(1, 1).Value, "P/N", "")
where the Cells value is the range you want to search.
If you are looking for an excel worksheet function, you can use substitute:
=substitute(A1,"P/N","")
where A1 is the cell that contains the value you want to substitute.


Getting null in mapping column in Hibernate bidirectional ManytoOne , OnetoMany

Question: I am trying to create bidirectional OnetoMany, ManytoOne mapping. Below are the entity classes StudentAddress and Student3 class:
Student3 entity class:
@Entity
@Table(name="Student3", schema="cf_2583f365_c3c6_499a_a60d_138e7e7023eb")
public class Student3 {
@Id
@Column(name = "STUDENT_ID")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int student_id;

@Column(name = "STUDENT_NAME")
private String student_name;

@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="student_address_id",referencedColumnName="address_id")
/*@JoinColumn(name = "student_address_id")*/
private StudentAddress studentAddress;

@Override
public String toString() {
    return "Student3 [student_id=" + student_id + ", STUDENT_NAME=" + student_name + "]";
}

public int getStudent_id() {
    return student_id;
}

public void setStudent_id(int student_id) {
    this.student_id = student_id;
}

public String getStudent_name() {
    return student_name;
}

public void setStudent_name(String student_name) {
    this.student_name = student_name;
}

public StudentAddress getStudentAddress() {
    return studentAddress;
}

public void setStudentAddress(StudentAddress studentAddress) {
    this.studentAddress = studentAddress;
}

public Student3() {

}

}

Student address entity class:
@Entity
@Table(name="StudentAddress", schema="cf_2583f365_c3c6_499a_a60d_138e7e7023eb")
public class StudentAddress {

@Id
@Column(name = "address_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int address_id;

@Column(name = "address_detail")
private String address_detail;

@OneToMany(cascade=CascadeType.ALL,mappedBy = "studentAddress")
private List<Student3> students;

@Override
public String toString() {
    return "StudentAddress [address_id=" + address_id + ", address_detail=" + address_detail + ", students="
            + students + "]";
}

public int getAddress_id() {
    return address_id;
}

public void setAddress_id(int address_id) {
    this.address_id = address_id;
}

public String getAddress_detail() {
    return address_detail;
}

public void setAddress_detail(String address_detail) {
    this.address_detail = address_detail;
}

public List<Student3> getStudents() {
    return students;
}

public void setStudents(List<Student3> students) {
    this.students = students;
}

public StudentAddress() {

}

}

On saving the data from Student3 object , I am able to save data like this:

But when I save data from StudentAddress side, I get a null in the student_address_id column:

Code to save data from Student3, studentAddress side:
/**************SAVE STUDENT Address Controller*************************/
@RequestMapping(value="/saveStudentAddress", method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public String savestudentaddress (@RequestBody StudentAddress s1) {

    System.out.println(s1);
    studentaddressRepository.save(s1);
    return "success";
}

/**************SAVE STUDENT3 Controller*************************/
@RequestMapping(value="/saveStudent3", method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public String savestudent (@RequestBody Student3 s1) {

    System.out.println(s1);
    student3Repository.save(s1);
    return "success";
}

Json to save data from Student3 side:
{
    "student_id" :123,
    "student_name": "avijit kumar Mamod",

    "studentAddress":{
                    "address_id" : 123,
                    "address_detail" : "209 - Berlington Street"
                    }
}

Json to save data from StudentAddress side:
{
"address_id" : 123,
"address_detail" : "209 - Berlington Street",
"students": [{
            "student_id" :123,
            "student_name": "avijit kumar Mamod"
           }]
}

Comment: Could you show the code how you are saving data from StudentAddress side?
Comment: @Abhi I have updated my qn , added codes for the same.
Answer: Modify your saveStudentAddress code like below and try
@RequestMapping(value="/saveStudentAddress", method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public String savestudentaddress (@RequestBody StudentAddress s1) {
    System.out.println(s1);

    for(Student s: s1.getStudents()){
      s.setAddress(s1);
    }

    studentaddressRepository.save(s1);
    return "success";
}

Comment: Its working !! But I dont understand , we are not even saving 's', we are still saving 's1'. Why setting up s, wud make such a difference ??
Comment: That is how Hibernate docs, in this case, suggest saving an object. Hope it helped.
Comment: please see my answer below, this is even more bizzare
Answer: Now today, on removing mappedBy from StudentAddress side & putting @JoinColumn(name="student_address_id"), when I tried to save from studentAddress side, it did added value in DB student_address_id.
studentAddress looks like this now:
@OneToMany(cascade=CascadeType.ALL/*,mappedBy = "studentAddress"*/)
@JoinColumn(name="student_address_id")
private List<Student3> students;

I am not sure why this happened. I dont have extra code as suggested by abhi in above answer. Controller is very simple now:
@RequestMapping(value="/saveStudentAddress", method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public String savestudentaddress (@RequestBody StudentAddress s1) {
    System.out.println(s1);
   studentaddressRepository.save(s1);
    return "success";
}

Answer: Not Write OneToMany in both the classes.
Comment: I have edited my question, by mistake I have added StudentAddress Class two times. Now Student3 class is available.


confidence interval of the difference of two statistics

Question: I have the returns of two groups of stock over 135 months and I am trying to find the confidence interval for the difference of two Sharpe ratios (that I will call $X$ and $Y$). To do so, I want to apply the formula:
$$(X-Y) \pm 1.96 \cdot \sigma(X-Y)$$
Thus, I first calculate the standard error of $X$ and $Y$ as the standard deviation of the bootstrapped Sharpe ratios. Now I want to calculate the standard deviation of the difference between the statistics. I found that I can apply the formula:
$$\newcommand{\length}{{\rm length}}\sigma(X-Y) = \sqrt{\frac{\sigma_X^2}{\length_X} + \frac{\sigma_Y^2}{\length_Y}}$$
My problem is in understanding which value I should use for the length(x) and length(y): should I use the length of my original statistic (1), of my original sample (135) or of the bootstrapped statistic (10000)?
Answer: If you're bootstrapping, you should just bootstrap the confidence interval and not rely on a normal approximation. In each bootstrapped sample, compute $X-Y$. The empirical 2.5 and 97.5 percentiles of the bootstrapped distribution are the bounds of a 95% confidence interval.
There are other ways of computing a bootstrapped confidence interval, but this is one (the percentile bootstrap).
Comment: Just to be sure that I understood correctly, you suggest to first bootstrap the statistic for each sample (so to have two vectors each of them with 10000 values of the Sharpe ratio), then to subtract one vector to the other and finally to take the empirical 2.5 and 97.5 percentiles of this resulting vector?
(thanks for the answer)
Comment: Do I have to sort the two vectors before subtracting one from the other? So that the "highest" Sharpe ratios of one group are subtracted to the "highest" Sharpe ratios of the other group?
Comment: I don't know anything about Sharpe ratios, so I don't know if they need to be treated differently to other statistics, but in a bootstrap you draw a random sample with replacement from your collected data, compute the statistic of interest (which in your case is the difference between the Sharpe ratios), and repeat, leaving you with a *single* vector of the statistic of interest. It's this single vector from which you compute the 2.5 and 97.5 percentiles.
Answer: As an alternative to bootstrapping, you can use a HAC estimator for covariance and the delta method. See section 4.2 of Short Sharpe Course. Some example code using the SharpeR package with the HAC estimator from sandwich package in R:
set.seed(1234)
x <- rnorm(135)
y <- rnorm(length(x))
xy <- cbind(x,y)
sg <- SharpeR::sr_vcov(xy,vcov.func=sandwich::vcovHAC,ope=12) # 12 for monthly data
difd  <- matrix(c(1,-1),nrow=1)
srdif <- difd %*% sg$SR
difvar <- difd %*% sg$Ohat %*% t(difd)
alpha <- 0.05
cis <- srdif + sqrt(difvar) * qnorm(c(alpha,2-alpha)/2)
cis
[1] -1.86814  0.08004


What is Multiple dispatch and how does one use it in Julia?

Question: I have seen and heard many times that Julia allows "multiple dispatch", but I am not really sure what that means or looks like. Can anyone provide me an example of what it looks like programmatically and what it enables?
Answer: From the Julia docs

The choice of which method to execute when a function is applied is called dispatch. Julia allows the dispatch process to choose which of a function's methods to call based on the number of arguments given, and on the types of all of the function's arguments. This is different than traditional object-oriented languages, where dispatch occurs based only on the first argument, which often has a special argument syntax, and is sometimes implied rather than explicitly written as an argument. 1 Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch. Multiple dispatch is particularly useful for mathematical code, where it makes little sense to artificially deem the operations to "belong" to one argument more than any of the others: does the addition operation in x + y belong to x any more than it does to y? The implementation of a mathematical operator generally depends on the types of all of its arguments. Even beyond mathematical operations, however, multiple dispatch ends up being a powerful and convenient paradigm for structuring and organizing programs.

So in short: other languages rely on the first parameter of a method in order to determine which method should be called whereas in Julia, multiple parameters are taken into account. This enables multiple definitions of similar functions that have the same initial parameter.
A simple example of multiple dispatch in Julia can be found here.
Comment: I'd also recommend watching this video https://www.youtube.com/watch?v=kc9HwsxE1OY talk starts at 2.25


Mathematics in Deep Learning Theory

Question: What areas of pure mathematics may give fruitful perspectives with which to develop more theory in the field of deep learning?
(I'm asking about topics at the level of advanced undergraduate and introductory graduate courses.)
Comment: http://mathoverflow.net/questions/202442/deep-learning-deep-neural-nets-for-mathematician
Comment: Joan Bruna, [Mathematics of Deep Learning](http://cims.nyu.edu/%7Ebruna/Media/cims_oct19.pdf), Courant Institute, NYU.
Comment: you have to explain your overall goal (are you a math undergraduate looking to do a masters etc). there are many that would argue that deep learning is a purely 'practical' success with little theoretical machine learning let alone mathematical innovation.
Comment: I am a theoretically-inclined undergraduate intending to do a PhD.  I am beginning to see a little bit more theory (coming from many different perspectives) trying to explain the "practical" success of deep learning, so I wanted to know what advanced courses may give further interesting frameworks to think within as a future researcher.  (Even if the link is more speculative, I'm curious to know.)
Comment: undergraduate in what ? computer science/maths/statistics ???
Comment: Tomaso Poggio's course (Last 2 classes) seems interesting http://www.mit.edu/~9.520/fall14/ (from kjetil's link)
Answer: You may be interested in the following papers : Computing with infinite networks, by Christopher K. I. Williams and Bayesian learning for neural networks by Radford M. Neal presenting an interesting relationships between neural networks and gaussian processes.
It is not related to "deep learning" (understood as neural network with multiple layers) but it has a strong mathematical content, related to single layer neural networks with an infinite number of weights.

Mathematics in Deep Learning Theory


Média da nota dos alunos e a soma das médias

Question: Galera, como sou novo em JS, queria uma ajudinha de vocês.
Bom, vamos a alguns passos:

Tenho essa constante que irá retornar um array de objetos

<code>    const alunos = [
      {
        nome: 'aluno1',
        notas: [9, 8.5, 10]
      },
      {
        nome: 'aluno2',
        notas: [6.5, 7.5, 6]
      },
      {
        nome: 'aluno3',
        notas: [3, 2, 4.5]
      }
    ];
</code>

Quero calcular a média das notas, mostradas na variável do objeto "notas".
E, por fim, somar as médias dos alunos.

Como posso fazer essa instrução?
Answer: Olá  masterofdefeats seja bem vindo ao STO em PT, bom, você poderia tentar algo do tipo:
<code>    alunos.map(aluno => {
      aluno.media = aluno.notas.reduce((t, n) => t + n, 0)/aluno.notas.length
      return aluno
    })
</code>
Por fim, para somar as médias dos alunos, pode usar algo como:
<code>let somaMedia = alunos.map(e => e.media).reduce((t, n) => t + n, 0)
</code>


How to get the conditional probabilities from joint probability table?

Question: I have a table of 3 binary variables whose joint probability is given.

a
b
c
p(a,b,c)

0
0
0
0.192

0
0
1
0.144

0
1
0
0.048

0
1
1
0.216

1
0
0
0.192

1
0
1
0.064

1
1
0
0.048

1
1
1
0.096

I see that there is a joint probabilities formula for 3 variable
$P(a,b,c) = P(c|a,b)P(a,b) = P(c|a,b)P(b|a)P(a)$
But when I cross-validate it with the table value and the formula it's not exact. What's happening here I am not getting it. It's not the same formula I assume. But how do I get the conditional probabilities from this table? If I can get the form, I can build the DAG.
I can see some patterns like 0.192 and 0.048 is twice even though $a$ is changed. Then I thought maybe $a$ is independent of $b$ and $c$?
I also find this formula $p(θ|X,α)=\frac{p(X|θ)p(θ|α)}{p(X|α)}$
So, I tried with a=1, b=1, c=1,
$
P(c|a, b) * P(b|a) * P(a)
= P(c|a, b) * \frac{P(b \cap a)}{P(a)} * P(a)
= \frac{P(c\cap a \cap b)}{P(a\cap b)} * \frac{P(b \cap a)}{P(a)} * P(a)
= \frac{1}{8}
$
Comment: None of $a,b,c$ are independent of the others.  Can you show use what you got when you tried $P(a,b,c) = P(c\mid a,b)P(a,b) = P(c\mid a,b)P(b\mid a)P(a)$ for some particular value of $a,b,c$?
Comment: The answer to the title question is "apply a definition of conditional probability." For instance, you can compute $P(b\mid a)=P(a\text{ and } b)/P(a)$ and read off the probabilities for any possible values of $(a,b)$ directly from the table.
Comment: @Henry I have added my approach. maybe it's the wrong approach. But the thing I am trying to do is to build that DAG from the formula or vice versa. I am trying to find out how that p(a, b, c) is generated. And also how did you find out none of a, b, or c is independent of each other? I also got the same observation. Just curious about your approach.
Comment: That does not show me your calculations. I would say $\frac23 \times \frac9{25}\times \frac25 = \frac{12}{125}$ not $\frac18$
Comment: @Henry How did you get these values?
Comment: @PritamSinha You first
Comment: @Henry $P(a=1\cap b=1\cap c=1) = \frac{1}{8}$. All other term cancels out. I am getting different answers every time with different approaches.
Comment: The last line of your table says $P(a=1\cap b=1\cap c=1) = 0.096$.  You still have not said how you got  $\frac18$
Comment: @Henry there is 1 occurrence of 111 out of 8 combinations. That's how. How 0.096 is coming that's the thing I want to know
Comment: The $8$ possible combinations are not equally likely: the table shows the joint distribution and so the probability of each
Answer: First, It appears that you are mixing up the definition of conditional probability for events and for random variables.
The definition $P(a,b,c)=P(c|a,b)P(a,b)=P(c|a,b)P(b|a)P(a)$ is for events.
For random variables, the definition is :
$$P(A = a,B = b,C =c)=P(C = c|A = a,B = b)P(B = b,A = a)$$
where $a,b,c$ is the values that the random variables $A$, $B$, $C$ can assume (in this case, $0$ or $1$).
Now, if you want  the conditional probability of $C$, given $A$ and $B$, you must obtain the probability $P(B = b,A = a)$.
Here is what you should do:
First, obtain $P(B = b, A = a)$ for all possible values of $a$ and $b$.
For example, to obtain $P(B = 0, A = 1)$, just sum all probabilities where $B = 0$ and $A = 1$. Do the same for the other possible values of $A$ and $B$.

Now, you can calculate $P(C = c|A = a,B = b) = \frac{P(A = a,B = b,C =c)}{P(B = b,A = a)}$

you can follow the same reasoning for the other conditional probabilities.
A good exercise for learning is to obtain all possible combinations of conditional and unconditional probabilities for all variables.
Comment: The definitions for random variables and events are the same, it's just a matter of notation. People sometimes do use notation shortcuts like using $P(a)$ meaning $P(A=a)$.
Comment: @Tim. Yes, I understand and agree. Maybe you could help me to rewrite the first sentences in a more precise way, I would appreciate it. A side note:  In my understanding, the OP was confusing about the events definition, for this reason I introduced the random variables. Another possible approach it would be use the notation $a_0$ and $a_1$ to represent, respectively,  the events $\{w \in \Omega: a=0\}$ and $\{w \in \Omega: a=1\}$. But I think this could lead to more confusion.


Left inverse of a function

Question: Let $f$ be the function  $f\colon \mathbb{N}\rightarrow\mathbb{N}$, defined by rule $f(n)=n^2$.
Needed to find two left inverse functions for $f$. I know only one: it's $g(n)=\sqrt{n}$. Does anyone can help me to find second left inverse function?
Comment: What exactly do you mean by $2$ left inverse functions? I see only one inverse function here.
Comment: @Inceptio: I suppose this is why the exercise is somewhat tricky. One is obvious, but as my answer points out -- that obvious inverse is not well-defined.
Comment: @Ilya : What's a left inverse function?  A function $g$ with $g \circ f = $ identity?
Comment: see definition here http://en.wikipedia.org/wiki/Inverse_function#Left_and_right_inverses
Answer: Note that $\sqrt n$ is not always an integer, so this is not the correct function, because its range is not the natural numbers.
Hint: You can round a non-integer up and down.
Answer: For each $n\in \mathbb{N}$, define $f_{n}: \mathbb{N} \rightarrow \mathbb{N}$ as
\begin{eqnarray}
f_{n}(x)=\left \{
\begin{array}{cc}
\sqrt{x} & \text{ when }x\text{ is a perfect square }\\
x+n &otherwise
\end{array}\right.
\end{eqnarray}
 Then $f_{n}~ o ~f (x)=f_{n}(x^2)=x$.
Each $f_{n}$ is a left inverse of $f$.

Left inverse of a function


How many languages does .Net support?

Question: How many languages does the latest versions of Visual Studio (2012 and 2010) support?
Also, is it possible to create a new language in .Net?
Comment: http://en.wikipedia.org/wiki/List_of_CLI_languages
Comment: http://www.dotnetpowered.com/languages.aspx
Answer: Visual Studio 2010 and 2012 directly support C#, VB.Net, C++/CLI, and F# for .NET development.  There are many other languages with various levels of "support" as well, including IronRuby and IronPython, Boo, etc.
Anybody is free to make their own language on top of the CLI, and many have done so.  Wikipedia has a fairly long list of .NET languages.
Answer: At least C#, F#, IronPython, Visual Basic.NET, C++ (and also a "hidden" C compiler I believe as well), at the minimum.
In addition, support for HTML5, Javascript, CSS3, etc.

How many languages does .Net support?


Why Should One Use Backtracking Line Search Method to Implement an Algorithm

Question: I am new to MATLAB and I am asked to implement on matlab the following algorithm:
Steepest descent
Newtont
Quasi-Newton (bfgs)
Gauss-Newton
using a line search method and the justify my decision.
I am using the backtracking line search cause I know that to use that I just need to saisfy one of the Wolfe conditions and to be honest also because it's the only method we studied so far, so I don't know how to justify properly my choice.
Could you please give me some more explenations?
What could I say more?
Comment: Your question is unclear.  It appears you've named three algorithms, not one, and you seem most concerned about justifying a choice of line-search method.  Have you read [Backtracking line search](https://en.wikipedia.org/wiki/Backtracking_line_search) and are you comfortable with the motivation provided there?
Answer: Using backtracking, assuming the direction selected is a descent direction, guarantees improvement in the minimization in each iteration.
In many cases it is sufficient, given enough steps, to get to local stationary point.
When not using Backtracking but, for example constant step size, one might diverge. Namely the step size should be set according to the surface being minimized and backtracking is one of the simplest way to do so.


breaking down ouput per timestamp by group on mysql

Question: New to mysql,
Under one table(table called tableX), let's say structure is like below
server       date           numberofUser
 server1   timestamp        3
 server2   timestamp        2
 server3   timestamp        7
 server1   timestamp        2
 server2   timestamp        8
 server3   timestamp        4

I want to collect for last 100 occurrence(so by the timestamp) but for each timestamp(which means for timestampX(which all server1,2,3 are measured), I want to total numberofUser for server1 and server 2.
So desire output is
timestamp1     5     (which comes from server1(2)  and server2(3) added
timestamp2     24    (which comes from server1(12) and server2(12) added
timestamp3     7     (which comes from server1(3) and server2(4) added

Can someone please point me to right direction? thank you
I already got total for last x occurrence of all servers(server 1 and 2) as below which works fine but now I need to break down by each timestamp
select sum(numberofUser) from (
    (select  server,   date, numberofUser from tableX
    where server = 'server1'
    order by date limit 10)
    union
   ( select  server,   date, numberofUser from tableX
    where server = 'server2'
    order by date limit 10 )) as t

::::::::::::::::::::::::::::::UPDATE::::::::::::::::::
http://sqlfiddle.com/#!9/7bc7f/1
I have my scheme above
output I want to see is below for given scheme
date1                   total
1970-01-01 00:00:03       85
1970-01-01 00:00:04       125

Comment: also, can someone recommend me a book or tutorial for topic like this?
Comment: I could help with this, so could anyone, if you created a sqlfiddle, loaded it with real data, and showed a columnar table with formatting showing expected results. As is, this is pretty bad.
Comment: I guess my example is pretty bad? Sorry, but I really don't understand simple problem like this is so difficult to figure out for newbie and was hoping to get some material to comb through. I am looking at some books now and struggle a bit on my own to see if I can figure it out. thank you guys!
Comment: well load up a fiddle at least and we can help, like this guy did in his [question](http://stackoverflow.com/q/37713790) .... and show what with that fiddle (you only do the left side) what you want your output to look like
Comment: Ok, I updated the original at the bottom w/ fiddle and desired outcome
Comment: Perfect, thx. I am sure someone can help. If not, I will.
Comment: Great! also, if you can recommend any resource, I would love to study further upon on this subject. thank you
Answer: Well to hit your desired output you would have to do limit 2 not the 100 you mention in your question. The second query uses a derived table on the inside that enforces the last ones first (the limit 2), with the outer query flipping the results to ordered as you showed.
select date1,sum(numOfUsers) as total
from test1
where server in ('server1','server2')
group by date1
order by date1 desc
limit 2;
+---------------------+-------+
| date1               | total |
+---------------------+-------+
| 1970-01-01 00:00:04 |   125 |
| 1970-01-01 00:00:03 |    85 |
+---------------------+-------+

Your final query is
select date1,total
from
(   select date1,sum(numOfUsers) as total
    from test1
    where server in ('server1','server2')
    group by date1
    order by date1 desc
    limit 2
) xDerived
order by date1;
+---------------------+-------+
| date1               | total |
+---------------------+-------+
| 1970-01-01 00:00:03 |    85 |
| 1970-01-01 00:00:04 |   125 |
+---------------------+-------+

xDerived is merely an alias name. Every derived table requires an alias name even if not used explicitly thereafter. Regardless of how silly it looks.
Comment: I am so sorry, where is xDerived coming from? When I google, I get nothing.
Comment: I accepted the answer but I don't understand the xDerived
Comment: I tweaked it slightly. Similar to the derived tables `xParams1` and `xParams2` in the final chunk answer [here](http://stackoverflow.com/a/37791885). Those were two little mini tables used to pump prime some variables used.


join two csv file using column reference

Question: I have two csv files
file 1 :
firstName    lastName     internalId      email         phoneNumber
XX           YY           123             firstname.lastname@example.com    003312345600
ZZ           QQ           147             email@example.com    003371236500
KK           JJ           159             email@example.com    003369865300

file 2 :
internalId    email        phoneNumber
159           email@example.com   003379632500
147           firstname.lastname@example.com   003396325200

i like to join file 1 and file 2 to have this result
firstName    lastName     internalId      email         phoneNumber
XX           YY           123             email@example.com    003312345600
ZZ           QQ           147             email@example.com    003396325200
KK           JJ           159             firstname.lastname@example.com    003369865300

modify email and phoneNumber if it finds the same internalId if not I keep the same values
Answer: awk solution:
awk 'NR==FNR{ a[$1]=$2 FS $3; next }
     FNR>1 && ($3 in a){ split(a[$3], b); $4=b[1]; $5=b[2] }1' file2 file1 | column -t

NR==FNR - processing the 1st input file i.e. file2
a[$1]=$2 FS $3 - fill the array a with concatenated values of the 2nd $2 and 3rd field $3 of file file2(i.e. email and phoneNumber) indexing it with the 1st field value $1, i.e. internalId
FNR>1 && ($3 in a) - processing the 2nd input file file1, making substitutions on matched internalIds

The output:
firstName  lastName  internalId  email       phoneNumber
XX         YY        123         email@example.com  003312345600
ZZ         QQ        147         firstname.lastname@example.com  003396325200
KK         JJ        159         firstname.lastname@example.com  003379632500

Comment: with shell  please
Comment: @Golden, don't tell that your system doesn't have `awk` installed
Comment: @Romain, Yes i have
Comment: @Romain, but I do not master awk well
can you explain to me the first line please
Answer: I'm assuming you need to do this in shell from your tags
Looks like a duplicate of this. Join command is your friend here


Match regex in any order in Golang

Question: I have something like this:
option name [p1|p2|p3] | [p4]

where option and name are mandatory. option must be exactly matched, while name is valid any ASCII character combination. Any string after these two is optional if match and it can appear in any order. So, it should match:
option name1 p1
option name1 p1 p4
option name1 p4 p1

My regex attempt:
^(option)\s+(([a-zA-Z0-9]+))\s?(((p1|p2|p3)?)\s?((p4))?)\s?$

This works if optional strings are provided in particular order e.g:
option name1 p1 p4
option name1
option name1 p1
option name1 p4

but this one doesn't work:
option name1 p4 p1

Is there a way to write regex to support any order of these optional strings?
Edit:
p1,p2,p3,p4 are just for example. It could be any of exact strings provided e.g. foo, bar, baz.
More clarification:
name could be any string. In perfect scenario it should be different then foo, bar, baz and other options.
Comment: So what differentiates `name1` from `p1`? Do you have a whitelist? What should happen with `option p1`?
Comment: is `option jhfgudfbs4 ^%#*$)` valid?
Comment: It should fail. option and name are mandatory. Other options afterward should be exact matched as I wrote in question. I will update my question, so it is clear.
Comment: It is still not clear whatsoever. You state that "while **name** is valid any ASCII char combination". Well `p1` is an ASCII char combination.
Comment: Did you mean to specify that `name` must be followed by a digit?
Comment: I mean you can chose any letter and digits as combination for name. I updated my question.
Comment: Your question makes even less sense now. If name can be any string then why is `foo` not allowed? `foo` **is** "any string". If you have a whitelist of names and valid string after name then share it because your requirements are impossible to achieve per your question and clarifications.
Comment: @MonkeyZeus It might look worst question to you, but I tried to demystify anything that might confuse you. I am not good in regex. That is the reason I asked question. If you read carefully, you could understand as I stated with " Any string after these two is optional if match". So it should match.
Answer: If you want to match both variants, you could use an or | to list each of the 2 variants.
To make the second part optional you could use an optional non capturing group (?:...)?
An example without all the capturing groups:
^option\s+[a-zA-Z0-9]+(?:\s?(?:(?:foo|bar|baz)(?:\s?test)?|test(?:\s?(?:foo|bar|baz))?))?$

In parts it will look like

^ Start of string
option\s+[a-zA-Z0-9]+ Match option, 1+ whitespace chars and a+ chars a-zA-Z or digits 0-9
(?: Non capturing group

\s? Match optional whitespace char
(?: Non capturing group

(?:foo|bar|baz)(?:\s?test)? Match for example for, bar etc and optional test
| Or
test(?:\s?(?:foo|bar|baz))? Match test and optionally foo, bar etc

) Close non capturing group

)? Close non capturing group and make the whole part optional
$ End of string

Regex demo
Comment: Thank you very much for explanation too :) Couldn't upvote twice :)
Comment: Thanks for answer. Sorry for misleading question :( p1,p2,p3 are just examples. In my scenario it should match different strings e.g foo baz bar.
Comment: Why do you use the `p` in the question and in the your regex? In that case you have to list all the options instead of a character class but still use the alternation part to match either one of the left side and one of the right side, or vice versa.
Comment: I tried to simplify it. Since I am not expert in regex, I overlooked this possibility. I will update my question.
Comment: @coder Do you mean like this? https://regex101.com/r/NBgyZe/1
Comment: @coder Then you can make the whole part after it optional https://regex101.com/r/rlKk0m/1
Comment: Yep. That is correct :) Thanks. Accepted & upvoted.

Match regex in any order in Golang


How to change background of barchart?

Question: I have created a BarChart using jqplot.BarRenderer. The background of the barchart created is white. I want to change the white background to some other color. I am using this sample from jqplot site.
Comment: Based on [this](http://www.jqplot.com/docs/files/jqPlotOptions-txt.html) (outdated, actually) document, you can provide custom color to `options.grid.background = "#666"`; Not sure if it still works. Lack of documentation was surprise for me.
Answer: Add option for $.jqplot like this.
grid: {
    background: '#223344'
}

Here is an example. http://jsbin.com/uQupaxi/1/edit?html,output

How to change background of barchart?


Organizing the list with a pivot

Question: I need to organize a list. The item in the zero index will be the pivot, so that every item in the list smaller will be put left to it in the list, and everything greater will be put right to it in the list.
Now I can't use "sort" or any built-in function in Python. Anyone could give me a clue?
Comment: Sounds like you're trying to do some sort of quicksort. Is that right? If so, could you include your progress so far if you have any, or what you don't understand?
Comment: Well, actually there's no real progress because I don't know where to begin. I have no experience with Python.
Comment: create two empty list, all elements less than pivot put in list 1 and all elements greater than pivot put them in list 2, than merge list and select pivot as second index in merged list, repeat the steps
Comment: Can't you even use the built-in `len()` function? Or is the list's length given to you separately? There are very many web sites that explain how to do quicksort, which includes your desired partition routine. What research have you done?
Comment: So, start with even the most basic things. Do you know how to create a list in Python? If not, search it and start with that. After that, find out how to index lists, and you'll then be able to get the pivot. If there's any step in particular that's confusing, just share that @Shalom.I
Comment: I believe I can use the len() function, just not aynthing built-in to sort it the way required.

@Aurora0001: I know how to create a list. What do you by "index" lists? As for the pivot, it's needed to be the first item in the list.
Comment: @Shalom.I by indexing a list, I mean given `x = [1, 2, 3]`: `x[0] == 1` and `x[1] == 2` etc.
Comment: Yep, that, too, I know. But still, even though I have an understanding what's needed to be done, I don't know where to begin the translation to "python"... you know...
Answer: Since you give no attempted code, I'll just give you an idea of the algorithm.
Go through the list, skipping index 0 where the pivot value is and starting at index 1, and examine the list entries. If the entry is less than or equal to the pivot value, "swap list entries to move that value to the lower end of the table." If you do the coding right, this will not be needed and you can just leave the value in place. If the value is greater than the pivot value, swap list entries to move the examined value to the upper end of the table. You stop when you have examined all the list entries. If you really need the pivot value between the two sublists, make one last swap to put the pivot value in its proper place.
You need two variables to keep track of the limits of the examined lower part of the list and the examined upper part of the list. The unexamined values will be between these two sublists. These variables are indices into the list--much of your code will deal with using and updating these indices as you progress through the table's values.
Now think about the exact definition of those two key index variables, their initial values, how they change for each examined value, and just when you will stop the loop that examines the list's values.
Note that the algorithm I suggest is not the best way to do the partition. There is another, more complex algorithm that reduces the number of swaps. But you should learn to crawl before you walk, and my suggestion does get the job done with the same order of execution time.
Comment: Well, I thought about it, my problem as stated in my last comment up there to Aurora0001, is that I don't know how to start typing the code, even though I have that understanding as you mentioned. Thanks.
Comment: @Shalom.I: If you understand what I wrote, then briefly give your definitions and names of the two key index variables, their initial values, and the condition that shows the partition is done. You need to show some work of your own: I won't do your homework for you. If you show real effort then I can lead you a little further. What I ask for here does not require Python code, just showing real understanding that you will later use for actual code.

Organizing the list with a pivot


Block Active Directory Group

Question: I have a touch-screen machine available to the public running under a domain account. This domain account is a member of an AD group for which I have denied all access at the folder level for our other internal sites and this is working just fine. Unfortunately, this machine can still access our SharePoint (MOSS 2007) Intranet even though I have denied permission in the WSS folders on the WFE server.
How do I deny access to Group X? Anonymous Access is turned off.
Comment: Why does the machine need to be running under a domain account?
Comment: Because one of the applications is hosted on an internal web site which we have tightened down.
Comment: What else can it access that you haven't thought of yet? Printers? File shares? Open databases? Management interfaces for servers and clients?
Comment: @Oskar, Group Policy was applied to answer this.
Answer: If the MOSS site has the Public group enabled, the user will be able to get in without authenticating, and there's no way to block that (because the site wouldn't know who's connecting in the first place without authentication).
If the MOSS site does not have Public enabled, something's messed up in the security settings (like everyone being a part of the site admin group).
Comment: Chris, what exactly do you mean by "public group enabled"?
Comment: Sorry, that should have been Public Role (or maybe it was Unauthenticated Users, but that doesn't sound right). My apologies, but I've been working with SP 2010 for months now and 2007 is becoming a distant memory.
Comment: It's set up as an Intranet Publishing site. I'm thinking of adding that group to a SharePoint Group and restricting the members with the Web App Policy in Central Admin. Does this make sense?
Comment: +1 for the advice on the site admin settings :-)
Answer: I solved this by simply adding the AD group as a user for the Web Application Policy using the steps outlined in keithbung's response here:
http://www.eggheadcafe.com/software/aspnet/30654160/limiting-access-to-sharepoint.aspx
Answer: Are you trying to protect your network by blacklisting this account/machine under every network resource? Everything about the way you're doing this is wrong.
You really need to look into implementing VLANs. The proper approach here isn't to worry about every application. Instead, you should segregate public machines from your private network by putting them in separate VLANs with an edge firewall between them.

Block Active Directory Group


What is the meaning of S.H. in a harp score?

Question: On this page of Marcel Tournier's Vers la source dans le bois, one sees S.H. in the 8th bar. What does this mean?
Answer: "S.H." stands for "sons harmoniques" (harmonic sounds). The circle above the note provides the same information.

The harmonic is a popular effect in harp music. Although the octave harmonic is the most common harmonic in the harp repertoire, fifth, double octave and third harmonics can also be produced. On some strings, even more harmonics can be produced. Harmonics can be used in combination with normal notes as well as with other harmonics. On the harp, as many as four harmonics can be produced simultaneously.
  Source: http://sites.siba.fi/web/harpnotation/manual/plucked-sounds/harmonics


Consequence of Cauchy integral formula?

Question: The below is a theorem from a book and the author says that it is a consequence of Cauchy integral formula, though I am unable to prove it. I took the rectangular contour whose vertices were $\gamma-i \beta, \alpha - i \beta, \alpha + i \beta $ and $\gamma + i \beta$ and used the Cauchy integral formula. Now I would like to let $\alpha \to \infty$ but I am unable to proceed after that. I would greatly appreciate help on this front.
Comment: This crazy integral should constitute a negatively oriented, closed path over the extended complex plane.  Thus it follows directly from Cauchy's Theorem.
Answer: This theorem is not true in general. First of all, the assumption that $\gamma \ne 0$ is weird, because you can always shift the function and consider the variable $w=z+t$ for some real $t$, which will replace $\gamma$ by $\gamma-t$. So if this would be true for some real $\gamma$, it is automatically true for all real $\gamma$. Now if you consider the function $f(z) = e^{-iz}$, $\gamma=0$, and $z_0=1$, then the integral in the formula is (with parametrization $z=it$, $dz=i \, dt$)
$$
\int_{-i\beta}^{i\beta} \frac{e^{-iz}}{z-1} \, dz = \int_{-\beta}^\beta \frac{e^t}{it-1} \, i \, dt = \int_{-\beta}^\beta \frac{e^t(t-i)}{1+t^2} \, dt,
$$
and it is pretty easy to see that both the real and imaginary part of this integral diverge as $\beta \to \infty$. (The exponential function grows too fast for positive $t$, and there is no cancellation because the real part is always positive, the imaginary part is negative for $t>0$.)
If you want an example with $\gamma \ne 0$, just pick $\gamma=2\pi$ and $z_0 = 2\pi+1$. By periodicity of the function, the integral you get is going to be exactly the same.
In order to make the statement true, you will need to assume something about the growth/decay of $f(z)$ as $z \to \infty$. Just curious, which book is this?

Consequence of Cauchy integral formula?


How do I recursively mirror a directory and its contents with puppet?

Question: Let's say I have a module with files/etc/foo/{conf0, conf1, conf2, conf3, etc}. It's simple enough to place each of these files when the number of them is small:
file { 'conf0':
    path => '/etc/foo/conf0',
    ensure => true,
    source => 'puppet:///.../etc/foo/conf0',
}

and repeat. But there's a fair bit of duplication involved, and it's tedious to maintain if there are several configuration files. I would like to ensure that files/etc/foo/ is mirrored onto a given path. That is to say,
file { 'etc foo confs':
   path => '/etc/foo',
   ensure => recursive,
   source => 'puppet:///.../etc/foo',
}

would create /etc/foo/conf0, /etc/foo/conf1 and so on. Is this possible?
Answer: Sure - the files type has a recurse option (and recurselimit if you want to limit how deep into the directory it goes).
file { 'etc foo confs':
   path => '/etc/foo',
   source => 'puppet:///.../etc/foo',
   recurse => true,
}

Comment: The other thing to keep in mind if doing this is the number of files that Puppet is going to have to maintain connections for. It would not take long to run out of file descriptors and puppet start running into trouble. I've ran into this problem before trying to do this very task.
Comment: @JeremyBouse Thank you; that's very useful information.