Qual o modo mais performático de converter int[] para int?

Question: Qual o modo mais performático de converter as posições invertidas de um array para int? Por exemplo, o seguinte array deve resultar no inteiro 153 para efeitos de cálculo futuro:
int[] a = new int[] {3, 5, 1};

Pensei em duas formas, porém não consegui identificar um bom modo de testar qual tem um desempenho melhor e também não sei se alguma delas é realmente a melhor forma. Vou listá-las abaixo.

Forma 1:
private int arrayToInt(int[] numeros) {
  int resultado = 0;
  int multiplicador = 1;

  for (int numero : numeros) {
    resultado = resultado + (numero * multiplicador);
    multiplicador = multiplicador * 10;
  }

  return resultado;
}

Forma 2:
private int arrayToInt(int[] numeros) {
  StringBuilder construtor = new StringBuilder();

  for (int numero : numeros) {
    construtor.append(numero);
  }

  return Integer.parseInt(construtor.reverse().toString());
}

Comment: Na ordem inversa mesmo? Primeiro unidades e depois dezenas?
Comment: @JeffersonQuesado isso mesmo!
Comment: Devido ao `int` ter no máximo 9 dígitos, posso assumir que o tamanho máximo do `array` é 9?
Comment: Eu creio que medir o melhor seja saber exatamente quantas chamadas de quais bytecodes serão feitas, assim como também alguns detalhes de localidade e o peso de chamada por bytecode. Estou bolando aqui um jeito, feio (com direito a `switch`) porém creio que seja o mais rápido.
Comment: @JeffersonQuesado tem dois modos que eu pensei aqui também, vou editar a pergunta e colocar os dois ali, só que ainda fica a dúvida de qual é o melhor justamente porque não consegui bolar uma forma de testar
Comment: Trabalhar com strings será mais lento que o primeiro jeito, não tenha dúvida... Criação de `a.length` objetos distintos será mais caro do que qualquer multiplicação que você faça. Estou incluindo na minha resposta também um jeito de comparação de performance baseado [neste aqui](https://pt.stackoverflow.com/a/235636/64969)
Comment: Vou terminar a resposta outro dia, ela ainda não está pronta para ser postada e já está mais tarde do que eu havia dado conta
Comment: @JeffersonQuesado sim, não precisa cobrir todos os casos. Na realidade o que importa mesmo é o desempenho. Eu consegui pensar em algumas formas mas não pensei muito bem em como testar, por isso resolvi perguntar, no caso de alguém saber qual o melhor e saber explicar o porquê
Answer: Conforme eu comentei, creio que, para se ter uma noção geral de como a sua soma vai ser performática ou não, você precisaria analisar os bytecodes que serão chamados e o peso geral que eles tem relativos um ao outro. Também seria adequado fazer o melhor uso possível da localidade das variáveis, otimizando o uso do cache do processador.
Vou dividir essa resposta em duas seções (além desta introdutória):

uma função otimizada (veja próximo parágrafo sobre o que está sendo levado em consideração)
como testar e por em contra-ponto diversas soluções

Vou considerar aqui que chamadas JNI estão fora de cogitação. Também não vou considerar o efeito que o jitter possa vir a ter. Apenas uma análise teórica. Também vou pular otimizações do próprio compilador.
Função de soma otimizada
O resultado obtido é um int, então sabemos que no máximo o número valerá 2^31 - 1, o que dá 10 casas decimais. Portanto, o vetor terá no máximo tamanho 10.
Como o tamanho do vetor é limitado (variando de 1 a 10; não considerando o caso trivial de tamanho 0), podemos tentar resolver de duas maneiras:

método iterativo (em que vou percorrendo cada elemento do vetor individialmente)
somatório para cada tamanho

A vantagem do método iterativo é que se escreve menos código. Imagino escrever o método iterativo de duas maneiras diferentes: ascendente e descendente. Vamos dar uma olhada nelas?
int soma_asc(int []a) {
  int base = 1;
  int acc = 0;

  for (int i = 0; i < a.length; i++) {
    acc += a[i] * base;
    base *= 10;
  }

  return acc;
}

Vou ficar devendo os bytecodes propriamente ditos, mas por cima o laço ficaria:

iniciar as variáveis acc, base e i com suas constantes
iconst_0, istore_2, iconst_1, istore_1, iconst_0, istore_3
carregar a variável i na pilha
iload_3
resgate do tamanho do vetor, deixando-o na pilha
aload_0, arraylength
compara esses valores, caindo fora caso dê falsa a comparação
if_icmpge:13
acessar o valor do vetor na posição i
aload_0, iload_3, iaload
carregar base na pilha e multiplicar pelo valor anteriormente obtido
iload_1, imul
carregar o antigo valor acc, somar com o valor anteriormente obtido, armazenar de volta em acc
iload_2, iadd, istore_2
carregar base, carregar a constante 10, multiplicar e armazenar de volta em base
iload_1, ldc:#10, imult, istore_1
incrementar i
iinc:3:1
carregar a variável i na pilha
iload_3
resgate do tamanho do vetor, deixando-o na pilha
aload_0, arraylength
compara esses valores, voltando ao passo 4 caso dê verdadeira a comparação
if_icmplt:5
carrega o valor de acc para ser retornado, retornando logo em seguida
iload_2, ireturn

Tomemos como exemplo um vetor de tamanho 3. Serão executados os reguintes bytecodes (linhas começadas por ; são comentários):
iconst_0, istore_2, iconst_1, istore_1, iconst_0, istore_3
iload_3
aload_0, arraylength
if_icmpge:13
aload_0, iload_3, iaload
iload_1, imul
iload_2, iadd, istore_2
iload_1, ldc:#10, imult, istore_1
iinc:3:1
iload_3
aload_0, arraylength
if_icmplt:5
; terminou de executar a tarefa referente ao primeiro dígito

aload_0, iload_3, iaload
iload_1, imul
iload_2, iadd, istore_2
iload_1, ldc:#10, imult, istore_1
iinc:3:1
iload_3
aload_0, arraylength
if_icmplt:5
; terminou de executar a tarefa referente ao segundo dígito

aload_0, iload_3, iaload
iload_1, imul
iload_2, iadd, istore_2
iload_1, ldc:#10, imult, istore_1
iinc:3:1
iload_3
aload_0, arraylength
if_icmplt:5
; terminou de executar a tarefa referente ao terceiro e último dígito

iload_2, ireturn

Um total de 57 bytecodes foram executados aqui, com dois desvios de fluxo. Foram feitos 37 acessos de leitura de informações da memória (3 acessos à heap), 9 acessos de escrita.
Se fossem 4 dígitos, teríamos +17 execuções de bytecodes, +1 desvio de fluxo, +11 acessos de leitura à memória (+1 acesso à heap), +2 acessos de escrita.
Note que essa função soma_asc pode ser reescrita com o açúcar-sintático da notação foreach, com a diferença de que a[i] ficaria armazenado em uma variável v:
int soma_foreach(int []a) {
  int base = 1;
  int acc = 0;

  for (int v: a) {
    acc += v * base;
    base *= 10;
  }

  return acc;
}

Isso implicaria no uso de alguns bytecodes de modo distinto, se não me engano afetando apenas o passo 4:

carregar o valor de a[i] na variável v, e então carregar o valor de v na pilha
aload_0, iload_3, iaload, istore#4, iload#4

Isso implica em, para cada conjunto de instruções, mais um acesso de escrita e outro de leitura. Portanto, sem considerar possíveis otimizações do compilador, seria dois bytecodes pior por cada número no vetor de entrada.
A função soma_desc tem outra abordagem, indo da ponta final até o índice alcançar zero:
int soma_desc(int []a) {
  int acc = 0;

  for (int i = a.length - 1; i >= 0; i--) {
    acc = acc*10 + a[i];
  }

  return acc;
}

Por cima, em uma análise semelhante ao que foi feito na função anterior:

incializar acc com a constante 0
iconst_0, istore_1
carregar o tamanho de a, subtrair 1 e armazenar em i
aload_0, arraylength, iconst_1, isub, istore_2
verificar se deve fazer o salto
iload_2, iconst_0, if_icmplt:6
resgatar acc, multiplicar por 10, somar com a[i], guardar em acc
iload_1, ldc:#10, imult, aload_0, iload_2, aiload, iadd, istore_1
incrementar i e verificar se continua no laço
iinc:1:-1, iconst_0, if_icmpge:4
carregar o valor de acc e retornar
iload_1, ireturn

Novamente, se for feito para o vetor com 3 elementos:
iconst_0, istore_1
aload_0, arraylength, iconst_1, isub, istore_2
iload_2, iconst_0, if_icmplt:6
iload_1, ldc:#10, imult, aload_0, iload_2, aiload, iadd, istore_1
iinc:1:-1, iconst_0, if_icmpge:4
; terminou o primeiro laço

iload_1, ldc:#10, imult, aload_0, iload_2, aiload, iadd, istore_1
iinc:1:-1, iconst_0, if_icmpge:4
; terminou o segundo laço

iload_1, ldc:#10, imult, aload_0, iload_2, aiload, iadd, istore_1
iinc:1:-1, iconst_0, if_icmpge:4
; terminou o terceiro e último laço
iload_1, ireturn

+11 bytecodes por laço, 2 bytecodes de terminação e 10 bytecodes de início, para um total de 45 bytecodes executados. 5 acessos de escrita ao todo (sendo 1 por laço), 4 acessos de leitura por laço (sendo 1 de leitura da heap) mais 1 leitura na terminação mais 1 acesso de leitura de heap e 1 acesso de leitura de variável no início, totalizando então 7 acessos de leitura (3 de heap). Também contou com 2 desvios de fluxo.
É, esse algoritmo aparantou ser mais rápido...
Agora, como eu sei o tamanho máximo do vetor usado, eu posso fazer a soma adequada para tamanho, sem envolver iteração alguma:
int soma_desenrolada_1(int []a) {
  switch (a.length) {
  case 0: return 0;
  case 1: return a[0];
  case 2: return a[0] + a[1]*10;
  case 3: return a[0] + a[1]*10 + a[2]*100;
  case 4: return a[0] + a[1]*10 + a[2]*100 + a[3]*1_000;
  case 5: return a[0] + a[1]*10 + a[2]*100 + a[3]*1_000 + a[4]*10_000;
  case 6: return a[0] + a[1]*10 + a[2]*100 + a[3]*1_000 + a[4]*10_000 + a[5]*100_000;
  case 7: return a[0] + a[1]*10 + a[2]*100 + a[3]*1_000 + a[4]*10_000 + a[5]*100_000 + a[6]*1_000_000;
  case 8: return a[0] + a[1]*10 + a[2]*100 + a[3]*1_000 + a[4]*10_000 + a[5]*100_000 + a[6]*1_000_000 + a[7]*10_000_000;
  case 9: return a[0] + a[1]*10 + a[2]*100 + a[3]*1_000 + a[4]*10_000 + a[5]*100_000 + a[6]*1_000_000 + a[8]*100_000_000;
  case 10: return a[0] + a[1]*10 + a[2]*100 + a[3]*1_000 + a[4]*10_000 + a[5]*100_000 + a[6]*1_000_000 + a[8]*100_000_000 + a[9]*1_000_000_000;
  }
  return -1;
}

Eu não sei como o Java vai compilar o switch para bytecodes, mas tem como prever o comportamento após isso. A soma que ele vai realizar. Peguemos para o caso com tamanho do vetor sendo 3 para comparar:
; coloca a[0] no topo
aload_0, iconst_0, aiload
; coloca a[1] no topo, multiplica por 10 e soma
aload_0, iconst_1, aiload, ldc#10, imul, iadd
; coloca a[2] no topo, multiplica por 100 e soma
aload_0, iconst_2, aiload, ldc#100, imul, iadd
; resposta obtida, só retornar
ireturn

Simples assim. Executando 16 bytecodes (compare com os outros que, para cada incremento no tamanho do vetor subia mais de 10 bytecodes), 3 acessos de leitura ao heap, nenhuma escrita de variável. Interessante, não é?
Podemos tentar diminuir a quantidade de constantes sendo multiplicada botanto o 10 em evidência. Assim, só haverá multiplicações por 10, por mais nenhum outro valor. Isso vai exigir colocar alguns parênteses a mais:
int soma_desenrolada_2(int []a) {
  switch (a.length) {
  case 0: return 0;
  case 1: return a[0];
  case 2: return a[0] + a[1]*10;
  case 3: return a[0] + 10*(a[1] + 10*(a[2]));
  case 4: return a[0] + 10*(a[1] + 10*(a[2] + 10*(a[3])));
  case 5: return a[0] + 10*(a[1] + 10*(a[2] + 10*(a[3] + 10*(a[4]))));
  case 6: return a[0] + 10*(a[1] + 10*(a[2] + 10*(a[3] + 10*(a[4] + 10*(a[5])))));
  case 7: return a[0] + 10*(a[1] + 10*(a[2] + 10*(a[3] + 10*(a[4] + 10*(a[5] + 10*(a[6]))))));
  case 8: return a[0] + 10*(a[1] + 10*(a[2] + 10*(a[3] + 10*(a[4] + 10*(a[5] + 10*(a[6] + 10*(a[7])))))));
  case 9: return a[0] + 10*(a[1] + 10*(a[2] + 10*(a[3] + 10*(a[4] + 10*(a[5] + 10*(a[6] + 10*(a[7] + 10*(a[8]))))))));
  case 10: return a[0] + 10*(a[1] + 10*(a[2] + 10*(a[3] + 10*(a[4] + 10*(a[5] + 10*(a[6] + 10*(a[7] + 10*(a[8] + 10*(a[9])))))))));
  }
  return -1;
}

Como seria para entrada com vetor de tamanho 3?
; vou tentar obedecer a ordem dos parênteses, portanto, a primeira coisa é carregar a[0] na pilha
aload_0, iconst_0, aiload
; estado atual da pilha: a[0]
; a separação dos elementos da pilha vai ser por #
; agora, põe dez para multiplicar pelo resultado da soma...
ldc#10
; estado atual da pilha: a[0] # 10
; coloca a[1] na pilha
aload_0, iconst_1, aiload
; estado atual da pilha: a[0] # 10 # a[1]
; agora, põe dez para multiplicar pelo resultado da soma...
ldc#10
; estado atual da pilha: a[0] # 10 # a[1] # 10
; põe a[2] na pilha. depois desse passo, basta por os operadores
aload_0, iconst_2, aiload
; estado atual da pilha: a[0] # 10 # a[1] # 10 # a[2]
; primeira operação: multiplicação
imul
; estado atual da pilha: a[0] # 10 # a[1] # 10*a[2]
; soma...
iadd
; estado atual da pilha: a[0] # 10 # a[1] + 10*a[2]
; multiplica...
imul
; estado atual da pilha: a[0] # 10*a[1] + 100*a[2]
; soma
iadd
; estado atual da pilha: a[0] + 10*a[1] + 100*a[2]
; pronto, só falta retornar
ireturn

Para um total de 16 bytecodes, que nem no exemplo anterior. A diferença aqui é que diminuímos a quantidade de constantes no código, portanto poderemos ter alguma vantagem da utilização da localidade temporal dos campos de memória.
Comparando performance do código
Alguns meses atrás respondi uma pergunta em Java sobre performance de métodos de ordenação. Para tal, elaborei todo um esquema de teste. Expliquei mais da metodologia lá. Após executar os testes, você obtém média e desvio padrão dos tempos de execução.
Basicamente o problema aqui é adaptar a função de geração de números aleatórios na função calculaTempo. Vou postar a original para referência, para então adaptarmos ao mundo de até 10 inteiros distintos, inteiros esses valendo de [0,10), fechado no começo e aberto no final:
public static LongSupplier calculaTempo(Consumer<Array> metodoOrdenacao) {
    return () -> {
        Array a = Array.getRandomArray(SIZE_ARRAY);

        long init = System.currentTimeMillis();
        metodoOrdenacao.accept(a);
        return System.currentTimeMillis() - init;
    };
}

Para mudar para calculaSoma, vou montar o vetor na mão eu mesmo. Para tal, vou usar de um gerador de números aleatórios r que vou prover junto com meus argumentos (sim, como IntSupplier). A função Random.nextInt(n) provê valores inteiros no intervalo [0, n). Se eu usar n=10, voi là, tenho o intervalo exatamente como havia sido especulado. Vou chamar essa variável de fornece_0_10 para indicar que é um IntSupplier que retornará resultados no intervalo fechado no começo e aberto no final [0,10). Como não interessa calcular a soma do vetor no caso trivial em que seu tamanho é 0, mas sim no tamanho variando de [1,11), o tamanho do vetor será 1 + fornece_0_10.getAsInt():
public static LongSupplier calculaTempo(IntSupplier fornece_0_10, Consumer<int[]> calculaSoma) {
    return () -> {
        int sizeOfA = 1 + fornece_0_10.getAsInt();
        int []a = new int[sizeOfA];

        for (int i = 0; i < sizeOfA; i++) {
            a[i] = fornece_0_10.getAsInt();
        }

        long init = System.currentTimeMillis();
        calculaSoma.accept(a);
        return System.currentTimeMillis() - init;
    };
}

Para chamar essa função, basta iniciar um gerador de números aleatórios r e assar a função lambda () -> r.nextInt(10) (considerando todas essas funções como estáticas da classe Soma):
Random r = new Random();
IntSupplier fornece_0_10 = () -> r.nextInt(10);

Estatisticas estatisticaSomaAsc = repeatGetEstatisticas(N_REPETITION, calculaTempo(fornece_0_10, Soma::soma_asc));
Estatisticas.printEstatisticas(estatisticaSomaAsc, "SOMA ASCENDENTE");

Estatisticas estatisticaSomaForeach = repeatGetEstatisticas(N_REPETITION, calculaTempo(fornece_0_10, Soma::soma_foreach));
Estatisticas.printEstatisticas(estatisticaSomaForeach , "SOMA FOREACH");

Estatisticas estatisticaSomaDesc = repeatGetEstatisticas(N_REPETITION, calculaTempo(fornece_0_10, Soma::soma_desc));
Estatisticas.printEstatisticas(estatisticaSomaDesc , "SOMA DESC");

Estatisticas estatisticaSomaDesenrolada1 = repeatGetEstatisticas(N_REPETITION, calculaTempo(fornece_0_10, Soma::soma_desenrolada_1));
Estatisticas.printEstatisticas(estatisticaSomaDesenrolada1 , "SOMA DESENROLADA V1");

Estatisticas estatisticaSomaDesenrolada2 = repeatGetEstatisticas(N_REPETITION, calculaTempo(fornece_0_10, Soma::soma_desenrolada_2));
Estatisticas.printEstatisticas(estatisticaSomaDesenrolada2 , "SOMA DESENROLADA V2");

Agora só falta coletar os resultados. Quando maior o número de repetições definido em N_REPETITION, mais confiável serão os resultados. Como Random fornece números aleatórios em distribuição uniforme, os valores obtidos se equilibram quando o número de repetições tende ao infinito.

Falta colocar o resultado dos testes para ver qual o mais eficiente


What methods can be used to solve $\int_{0}^{\infty}x^{-\ln x}dx=\sqrt{\pi\sqrt{e}}$?

Question: I am interested in alternative solutions to the following question:

Prove that $\int_{0}^{\infty}x^{-\ln x}dx=\sqrt{\pi\sqrt{e}}$

I first used $\int_{0}^{\infty}x^{-\ln x}dx=\int_{0}^{\infty}e^{-\ln^{2}x}dx$
Then I used a u-sub to get:
$$\frac{1}{2}\int_{0}^{1}\left(e^{\sqrt{-\ln u}}+e^{-\sqrt{-\ln u}}\right)\frac{ue^{\ln^{2}\left(e^{-\sqrt{-\ln u}}\right)}}{\sqrt{-\ln u}}du$$
I realized I could simplify it to $\frac{1}{2}\int_{0}^{1}\frac{e^{\sqrt{-\ln u}}+e^{-\sqrt{-\ln u}}}{\sqrt{-\ln u}}du$.
After another substitution, I got $\int_{0}^{\infty}\left(e^{v}+e^{-v}\right)\left(e^{-v^{2}}\right)dv$
I solved using $\text{erfc}(x)$:
$$\int_{0}^{\infty}\frac{e^{2v}+1}{e^{v+v^{2}}}dv=\int_{0}^{\infty}\left(e^{v-v^{2}}+e^{-v-v^{2}}\right)dv=\sqrt{\pi\sqrt{e}}$$

I feel like there should be a better way to do this.
What other methods can be used to solve this?
Comment: @DominikKutek I didn't notice, that's why I asked. Thanks
Answer: Well, substitute $\ln(x) = y$, then $\int_{0}^{\infty} x^{-\ln(x)} dx = \int_{-\infty}^{\infty} e^{y}e^{-y^2}dy = e^{1/4}\int_{-\infty}^{\infty} e^{-t^2} dt = e^{1/4}\sqrt{\pi}$.


How to split 2nd element in array in JavaScript?

Question: How to split 2nd value in array?
Input [["ABCD","123,456"],["EFGH","565,565,878"]]
Required Output [["ABCD","123","456"],["EFGH","565","565","878"]]
I tried array.map(x => x[1].split(',')) but I am getting output as [["123","456"]],["565","565","878"]] 1st value is getting omitted. How to include 1st value also?
If I use x.split(',') I am getting error

x.split is not a function
Comment: `input.map(array => array.map(str => str.split(",")).flat())`
Comment: @ChrisG ok I see solutions are better in comments :) someone else says don't answer in comments. very confusing environment. Final story I had to remove my answer.
Comment: @DiegoDeVita 99.9% of questions here are dupes, typos or rtfm. I only post an answer if a) due diligence b) actually not answered before. But again, this never happens. So I downvote/flag the question but still help the OP with a comment (since they don't know their question is bad because SO removed the rules from the question form)
Comment: @DiegoDeVita Add to this that lots of high rep users apparently have decided to just F it and post answers to obvious dupes. SO has been going down the drain for years, all we can do to keep a minimum of quality control is to keep downvoting and flagging.
Answer: Try this
input.map(([name, list])=>[name, ...list.split(',')])


Combine JAXWS and JAXB bindings

Question: I'm customizing JAXB beans generated by an WSDL file with jaxws-maven-plugin. To customize them I'm using a binding file.
Basically I want:

Prevent the generation of JAXBElement
Customize some element names

My bindings file is:
<jaxws:bindings version="2.1"
           xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
           xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
           xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
           xmlns:jaxws="http://java.sun.com/xml/ns/jaxws">

<jaxb:globalBindings generateElementProperty="false">
    <xjc:simple/>
</jaxb:globalBindings>

<jaxb:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema" node="//xs:complexType[@name='WorkDocuments']/xs:choice">
    <jaxb:property name="documents"/>
</jaxb:bindings>

The problem is that if I use jaxws:bindings as root element the Element 1 doesn't works and JAXBElement are generated
And if I use jaxb:bindings as root element then Element 1 works but Element 2 doesn't as the xpath expressions doesn't match any element.
How can I correct the binding file to get the two elements working at same time?
Answer: I found a solution that is use <jaxws:bindings> as root element and then put the globalBindings inside a jaxws:bindings:
That is:
<jaxws:bindings version="2.1"
            xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
            xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:jaxws="http://java.sun.com/xml/ns/jaxws">

<jaxws:bindings node="wsdl:definitions/wsdl:types/xs:schema[@targetNamespace='yourNamespace']">
    <jaxb:globalBindings generateElementProperty="false">
    </jaxb:globalBindings>
</jaxws:bindings>

Combine JAXWS and JAXB bindings


Why are existing entity reference fields not available to add to a media type?

Question: I have a number of existing entity reference fields in my site. The key one is a taxonomy reference field called field_search_terms. I would like to add this field to the Document media type. However when I go to manage fields for the media type my existing fields are not available.
It looks like I need to create a new field and any search that mixes content and media will need to have two filters.
Why is this limitation in place? Is there an issue I can follow to learn more?
Comment: Fields can only be re-used in the same entity type - maybe your existing `field_search_terms` is on a different entity type?
Answer: I found the resources I was looking for with help from a comment by Clive:
A field can only be used on the same entity type. There is an open issue for this in the queue. According to the issue and my recollection this is a change from Drupal 7. If so it feels like a major regression.
The documentation is also incorrect at the time of this writing.
Comment: It's no longer possible because in D7 a field got a generic table in the database and the entity type was a field within the database. Within D8 a field gets its own table in the database but the table name is prefixed with the entity type. There are probably lots of valid reasons for this such the config management system requiring it to be like this, with the trade-off of being unable to reuse a field across entity types and you now just have to remake the field for each entity type


Different p-values from weight and unweighted regressions?

Question: I'm trying to determine whether an unweighted or weighted regression would be more suitable for my data.
I have variables X and Y, both are measured variables but X has very small errors while Y has quite large errors. This is because Y is calculated from an average of 5 measurements - so the error bars are including repeatability of these values from our analytical instrument.
I initially thought weighted regression would work because it would treat data points with smaller errors as more important, giving more weight to Y values with smaller standard deviations (so that data points that were more reproducible by the instrument are more reliable).
However I've been warned against using weighted linear regressions because they are ideal for data that has large errors on both X and Y variables, is this statement true?
I'm also worried about choosing the regression method because I get very different p values from the two regressions. With the weighted regression my p value is <0.001, but with the unweighted regression my p value is ~0.5, which completely changes my interpretation. I'm trying to understand what's causing this much difference in p values with the different regression methods and what regression would be best for my data.
Any insight would be appreciated!
Comment: I would not consider your Y variable with larger error, *because* you repeated the measurement 5 times.
Comment: The weighted regression might perform 'better' (lower significance). However, I imagine that this fit is dominated by a few 'accurate' high weight points (in only a part of the entire domain of X). So the result should not be generalized over the entire domain of your measurement for X. This would be sort of extrapolation.
Comment: @MartijnWeterings  Initially the idea of repeating measurement was to test how reproducible my data was. That's why I'm wondering, if low standard deviations across 5 measurements of a same sample result in more 'accurate' data points, would it be acceptable to treat them with more 'weight'. What did you mean by "generalized over the entire domain"? Sorry, I'm not super familiar with regression methods.
Comment: 1) You could indeed use the repeated measurements to find out the measurement error in the Y variable and how it varies for different values of Y, but you compare it with X. You say *"...X has very small errors while Y has quite large errors. **This is because** Y is calculated from an average of 5 measurements ...."*
Comment: 2) In some cases you might consider the lower weight of points as 'ignoring the points' like when you remove outliers (but less severe). If the lower weight points are all at the same side,  mostly for very high or very low values, then you should regard your regression line as not being very representative for that region, even when you got some points measured there and included (they are however only low weight).
Answer: Given the large differences in error for the different points, the unweighted regression p-values are not reliable. Your weighted regression is probably more appropriate; I am not aware of the assumption that you describe and do not think that it is accurate. If anything, I would expect the opposite to be true (i.e. that X-error should be much lower than Y-lower, as in your data).
A few additional thoughts/ideas.
1) There's no need to average your 5 measurements, and therefore little need for weighting. You can include them all while accounting for their non-independence with a random intercept term in a linear mixed effects model.
2) It's true that having errors in both X & Y can get complicated. There are methods that have been developed for this (orthogonal regression), but they have their limitations as well. I discuss their pros and cons a bit in this answer. If your errors on the X-axis are small, it may be best to avoid this approach.
3) A completely different approach one can take when faced with errors in both X & Y is to bootstrap your regressions. Let's say you can estimate the mean and standard deviation of each point, both in X & Y dimensions. You can randomly draw a value from the normal distribution fitted to each point, in each dimension. Do this for every point and fit a linear model to this resampled dataset. Repeat this process a large number of times, fitting your model to each resampled dataset. By aggregating across all your fitted models, you can estimate the distribution of intercept and slope values. Since each point is drawn from its own distributions, this accounts for differences in the error of each point, in both dimensions.
Comment: Reading your comment 1) I tried using all my measurement values as Y (and just assigned a small constant (0.01) as errors to all values, assuming those are analytical errors from the instrument). Now that I assigned the same X and Y errors for all my data points I'm getting the same regression lines (slope/intercept/R2) for both my weighted and unweighted regressions but my p-values are still 3 orders of magnitude different from each other. So maybe there were other factors than the large error bars in Y that affects my p-values?
Comment: @Jen I don't quite follow, I'm afraid. My point #1 advocated using all your data points and not including weights (but a random intercept instead). So I don't see how the process you describe reflected this. However, if you weight all points identically, then your results (including p-values) should be identical to unweighted regression.
Comment: I figured it might be just because I was using an 'unusual' weighted regression (York method). When I used lm function with weights I did find that my weighted and unweighted points yield same results. I'll have to think more about which weighted regression algorithm I want to use, but thank you!


Finding injection from $[0,1]$ to $P(\mathbb{N})$

Question: I'm using Schröder-Bernstein to prove that $\mathbb{R}$ is equinumerous to $P(\mathbb{N})$, the power set of the naturals. Part of my proof requires that I find an injection from $[0,1]$ (which is equinumerous with $\mathbb{R}$) to $P(\mathbb{N})$. I already found the reverse injection by encoding membership of $n$ as the $n$th bit in a binary sequence following the decimal point.
Hints appreciated!
Edit: Thanks for all the suggestions. For those interested, I concluded that the following would be the most accessible and elegant way for me to prove $[0,1]$ is equinumerous with $P(\mathbb{N})$.
Let $f: [0,1] \rightarrow P(\mathbb{N})$ be defined as follows. Each $c \in [0,1]$ can be written in binary uniquely as $a_1.a_2a_3...$ by choosing the canonical representation of nonterminating $0$s rather than nonterminating $1$s when there is a choice. Then $f(c) = \{k: a_k = 1\}$ gives an injection.
Let $g  : P(\mathbb{N})\rightarrow [0,1]$ work as follows. For any $A \in P(\mathbb{N})$, $g(A)$ is the decimal, rather than binary, representation $0.a_1a_2\ldots$, where for each $k \in \mathbb{N}$, $a_k = 1$ if $k \in A$ and $0$ otherwise. Note that we ensure injectivity because, in decimal, a number of the form $0.a_1a_2\ldots$ will only have multiple representations if one of them has a nonterminating tail of $9s$.
By Schröder-Bernstein, we have $\mathbb{R}$ is equinumerous to $P(\mathbb{N})$.
Comment: prove that function you mentioned is surjection as well
Comment: http://mathoverflow.net/questions/56633/simple-bijection-between-reals-and-sets-of-natural-numbers
Comment: @user26977 I think that it is usually easier to utilize http://www.cut-the-knot.org/WhatIs/Infinity/Bernstein.shtml
Comment: Binary expansion is "almost bijective", the only problem is that there is some ambiguity about numbers which can be written as ending in infinitely many $1$s, since these can also be written as ending in infinitely many $0$s by performing an "infinite carry". "Correcting" that by choosing a "canonical" representation of these numbers (e.g. deciding that valid binary expansions never end in an infinite tail of $1$s) produces a bijection between a certain subset of $P(\mathbb{N})$ and $[0,1]$, which reduces the problem to showing that $P(\mathbb{N})$ and this subset have the same cardinality.
Comment: To prove *that*, the usual way I know to proceed is to argue that this subset of $P(\mathbb{N})$ has a countable complement, then you construct an injection from $P(\mathbb{N})$ to this subset using a Schroder-Bernstein-like argument. Then the other way has the inclusion map, so Schroder-Bernstein applies.
Answer: An idea is to consider numbers in $[0,1]$ expanded in their binary representation $a_0.a_1a_2\dots$, where $a_n\in\{0,1\}$ and, for any $n>0$, there exists $m>n$ with $a_m=0$ (which excludes representations that are "eventually $1$".
Each number in $[0,1]$ has exactly one representation of this type; for $x\in[0,1]$, call $x_n$ the $n$-th digit and define
$$
f(x)=\{n\in\mathbb{N}:x_n=1\}
$$
For instance $f(1)={0}$ and $f(0)=\emptyset$, whereas $f(1/2)=\{1\}$. If $x\ne y$, then $x_n\ne y_n$ for at least one $n$, so either $n\in f(x)$ and $n\notin f(y)$ or $n\notin f(x)$ and $n\in f(y)$. In particular, $f(x)\ne f(y)$.
For the converse injection, given $A\subseteq\mathbb{N}$, consider the binary alignment defined by
$$
0.a_10a_30a_50\dots
$$
where $a_{2n+1}=1$ if $n\in A$ and $a_{2n+1}=0$ if $n\notin A$.
Different sets define different numbers in $[0,1]$; the inserted zeros in even positions ensure that no alignment is "eventually $1$".
Comment: Thanks, you led me to my solution. Check out my edited question—I thought you might be interested in my alternative solution to the converse injection that avoids the inserted zeros.
Comment: @rorty Yes, the alternative approach is good: the problem is to avoid "eventually $b-1$" sequences, where $b$ is the radix.
Answer: For each real number, choose a decimal representation $a=0.a_1a_2\dots$ in binary, and define $f:\mathbb{R}\to P(\mathbb{N})$ by noting that since $\mathbb{N}$ is equinumerous to $\mathbb{N}\times \{0, 1\}$, we have a bijection, $h:P(\mathbb{N}\times\{0, 1\})\to P(\mathbb{N})$, so we may define $g(a)=\{(i, a_i)|i\in\mathbb{N}\}$, and letting $f=hg$ we obtain the desired injection.
Answer: Define $f: [0, 1] \to P(\mathbb{N})$ to be $f(x) = \{ 2^i 3^{a_i} | i = 1, 2, \ldots \}$ where $a_i$ are the decimal expansion of $x = \sum_{i = 1}^\infty \frac{a_i}{10^i}$, $a_i \in \{0, 1, \ldots, 9\}$. Show that this is injection.
Answer: You can define an injection $g:\mathbb R\to P(\mathbb Q)$ by setting $g(x)=\{q\in\mathbb Q:q\lt x\}$ (the lower Dedekind cut). Now restrict $g$ to $[0,1]$ and compose it with a bijection from $P(\mathbb Q)$ to $P(\mathbb N)$ to get your injection $f:[0,1]\to P(\mathbb N).$
For the other direction, you can get an injection $h:P(\mathbb N)\to\mathbb R$ by simply defining $$h(S)=\sum_{n\in S}10^{-n}.$$
Answer: Your function $P(\mathbb N)\to[0,1]$ is not an injection.  For example, $\{1\}$ and $\mathbb N\setminus \{1\}$ map to $0.1$ and $0.0111\dots$, which are the same number $1/2$.
In fact, if you use the same trick in the opposite direction then you do get an injection $[0,1]\to P(\mathbb N)$, encoding a real number as a set of natural numbers using some chosen 'canonical' binary expansion for each number.  For example, given the choice, you could always choose the non-terminating binary expansion.
Therefore, the question you should be asking is: 'How do I find an injection from $P(\mathbb N)$ to $[0,1]$?'  You will probably have to do this in a slightly clumsy way.
As an idea, let $P_{\inf}(\mathbb N)$ denote the set of infinite subsets of $\mathbb N$.  These subsets correspond to non-terminating binary expansions, and this gives us an injection $P_{\inf}(\mathbb N)\to[0,1]$.  Now there is an injection $[0,1]\to[0,1]$ sending $0.a_1a_2a_3\dots$ to $0.0a_10a_20a_3\dots$.  Composing this with our injection gives us an injection $P_{\inf}(\mathbb N)\to[0,1]$ that is very far from being surjective, and now there are plenty of spare elements of $[0,1]$ that we can map the finite subsets of $P(\mathbb N)$, giving us an injection $P(\mathbb N)\to[0,1]$.
Comment: My function is an injection if I still consider only 0s and 1s but in decimal rather than binary. E.g., 0.1 and 0.011111111... would be different numbers in decimal. But you and egreg led me to the injection I'm looking for (which is to use binary but only consider canonical representations).
Comment: Very good point, and well done.  Now I think of it, your solution using decimal is much more elegant than mine.


Does deserialized object preserve static values?

Question: Here's a very basic test program:
public class Body implements Serializable {
    static int bod = 5;
    int dis = -1;
    public void show(){
        System.out.println("Result: " + bod + " & "  + dis);
    }
}

public class Testing {
    public static void main(String[] args) {
        Body theBody = new Body();
        theBody.show();
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.dat"));
            out.writeObject(theBody);
            out.close();
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.dat"));
            Body bodyDouble = (Body)in.readObject();
            in.close();
            bodyDouble.show();
        } catch(IOException e) {
        } catch(ClassNotFoundException e) {
        }

    }
}

But I don't understand why its output is:
Result: 5 & -1
Result: 5 & -1

Since static members are not serialized and hence get default values I was expecting another output:
Result: 5 & -1
Result: 0 & -1

How did the deserialized object acquire the right static field value?
I've made this test application because I need to serialize a few objects with a number of static fields in order to make deep copies (and of course, I need to be sure that copies have the same static fields' values since they are used as array indices).
And now I'm absolutely confused about what happens after deserialization. On the one hand, static members don't get serialized but, on the other hand, as the example prooves, static members somehow preserve their values. I suspect that it has something to do with casting of readObject() to the Body object but I'm not sure.
Comment: http://stackoverflow.com/questions/1008023/how-to-serialize-static-data-members-of-a-java-class
Answer:
How did the deserialized object acquire the right static field value?

Because the static field values have not changed between serialization and deserialization:
You are running your test within the same application. Hence the static class members retain their value. The class iteself is not reloaded or re-initialized - it is still the same.
You should separate your test in two separate applications:

Let one application serialize the object
Let one application deserialize the object

Then run these two applications one after the other. You will then see that the static members are not restored in your second application.
Alternatively, in your code above, you could also set the static field to a different value right before deserialization - you will then see that the variable still has this value after deserialization.
On a side note, never do ... catch(IOException e) {} ... - at least, print the stack trace with e.printStackTrace().
Comment: Thank you. So do I get it right that since I need a temporary identical deep copy of an object at runtime (with no separate application involved) I don't need to worry about static fields - all deserialized copies will have them? I.e. losing static values is basically a problem of object exchanges between different applications?
Comment: Yes. Because serialization is about objects (class instances), not classes. This might be useful for your specific use case: http://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object-in-java


How to output the firebase snapshot in reverse order?

Question: I am trying to get the latest 3 data from the database and display them in reverse order in the HTML page.
Code:
var refForevent = database.ref('/events/post');

refForevent.orderByChild("intro").limitToLast(3).on('child_added', function(snapshot){

    var eventlist = []

    eventlist.push(snapshot)
    console.log(eventlist)

    eventlist.reverse()

    document.getElementById("event1date").innerHTML = moment(eventlist[0].intro).format("MMM Do YYYY");
    document.getElementById("event1title").innerHTML = eventlist[0].title;

    document.getElementById("event2date").innerHTML = moment(eventlist[1].intro).format("MMM Do YYYY");
    document.getElementById("event2title").innerHTML = eventlist[1].title;

    document.getElementById("event3date").innerHTML = moment(eventlist[1].intro).format("MMM Do YYYY");
    document.getElementById("event3title").innerHTML = eventlist[1].title;

})

Output: Output that I am getting
Database:
Comment: UPDATE: I'm sorry. It is orderByChild("intro"). I forgot to update it before posting it here. My bad.
Comment: There's an `edit` link right under your question so that you make edits like that to your question.
Answer: Since you're listening to the child_added event, your function gets called with each post node that matches the query in the order in which Firebase returns them. So your eventlist will only ever contain one node at a time.
To reverse the items, you can either get Firebase to return the values in reverse order, as Renaud suggest (I'll also link some answers below), or you can listen to all results in once go and then reversing client-side (as your code already seem to be trying). The latter would look something like:
var refForevent = database.ref('/events/post');

refForevent.orderByChild("date").limitToLast(3).on('value', function(results){

    var eventlist = []
    results.forEach(function(snapshot) {
        eventlist.push(snapshot.val())
    });

    eventlist.reverse()
    console.log(eventlist);

    ...
})

So this:

Listens to the value event, instead of child_added, so that it gets all matching child nodes in one go.
If then loops over the results, adding them to the array,
It calls .val() on each child snapshot, to get the value from it.

For more on descending sorting, also see:

Display posts in descending posted order (the oldest I could find describing the trick with negative values)
firebase -> date order reverse (with many more links from there)
Sorting in descending order in Firebase database
Comment: This worked for the first event and it was in the order I wanted it too. But I got an error "Cannot set innerHTML of null" for the rest.
Comment: That error seems unrelated to the Firebase interaction, which is what I helped with here. For the best help on Stack Overflow, isolate the problem as much as possible as shown in [how to create a minimal, complete, verifiable example](http://stackoverflow.com/help/mcve).
Comment: Okay. Thank you :)
Answer: I see that the field intro contains a date.
Here is one solution:

Take the value of this field
Remove the hyphen separators (e.g. from 2020-12-10 you get the number 20201210)
Multiply this number by -1
Store the resulting value in another field
Sort on this field

Alternatively (and more elegant...), use the date to create a Timestamp, multiply it by -1 and use it as explained above, i.e. store the resulting value in another field and sort on this field.


How to proceed with live, local website

Question: I've done plenty of web development at a pretty basic level, and usually just local pages to be called from shared network drives.
Here is where I'm stuck:
I am attempting to build a simple application for work where other leads and I can open a local html page from our shared drive, and add/remove employee names to different tasks, so we can keep tabs on who's doing what.
The tasks are the same every day, just hardcoded titles on sectioned out divs.
Problem is, I can't figure out how to make it to where changes I make will populate for other people with the window open (considering this is just a local page and not a live environment being hosted on anything).
For the general design, I've toyed with hard coding all the employee names under each task in hidden div tags, with a bit of jquery to make the div visible when that worker is assigned.
I have also toyed with appending data to the existing tags using <code>.innerHTML</code>.
Still have no idea how to make this live so we can see each others changes.
Can you point me in the right direction?
Comment: a wheel is being reinvented
Comment: You're not going to be able to do it without some sort of shared database. Why not make a Google Doc?
Answer: I've figured it out. It may be a bit on the lazy side, but i'm just setting the HTML page to auto refresh every 5s. The data displayed will pull from a notepad doc that leads will be able to update and save.
Answer: I am assuming that you just want your peers to be able to see the changes your making live? If so you need to use Ajax. You could set it to ping the server every so often to update on the fly. I'm still quite uncertain as to whether or not that was your question, but if not please elaborate or post your code so I can help further.

How to proceed with live, local website


How to authenticate a gcloud service account from within a docker container

Question: I'm trying to create a docker container that will execute a BigQuery query. I started with the Google provided image that had gcloud already and I add my bash script that has my query. I'm passing my service account key as an environment file.
Dockerfile
FROM gcr.io/google.com/cloudsdktool/cloud-sdk:latest
COPY main.sh main.sh

main.sh
gcloud auth activate-service-account email@example.com --key-file=/etc/secrets/service_account_key.json
bq query --use_legacy_sql=false

The gcloud command successfully authenticates but can't save to /.config/gcloud saying it is read-only. I've tried modifying that folders permissions during build and struggling to get it right.
Is this the right approach or is there a better way? If this is the right approach, how can I get ensure gcloud can write to the necessary folder?
Answer: See the example at the bottom of the Usage section.
You ought to be able to combine this into a single docker run command:
KEY="service_account_key.json"
echo "
[auth]
credential_file_override = /certs/${KEY}
" > ${PWD}/config

docker run \
--detach \
-env=CLOUDSDK_CONFIG=/config \
--volume=${PWD}/config:/config \
--volume=/etc/secrets/${KEY}:/certs/${KEY} \
gcr.io/google.com/cloudsdktool/cloud-sdk:latest \
  bq query \
  --use_legacy_sql=false

Where:

--env set the container's value for CLOUDSDK_CONFIG which depends on the first --volume flag which maps the host's config that we created in ${PWD} to the container's /config.
The second --volume flag maps the host's /etc/secrets/${KEY} (per your question) to the container's /certs/${KEY}. Change as you wish.
Suitably configured (), you can run bq

I've not tried this but that should work :-)


Predict the number of primaries after a split-brain situation

Question: I am trying to avoid a split brain situation using automatic split brain recovery policies explained at http://www.drbd.org/users-guide/s-configure-split-brain-behavior.html
How to predict which condition we are involved in? How to predict the number of primaries after split brain? Is it all accidental?
Answer: How many nodes do you have? More than two?
Anyway I found the following setup to be the best to recover from split-brains:

after-sb-0pri: discard-zero-changes
after-sb-1pri: discard-secondary
after-sb-2pri: disconnect

So first we throw away any differences in the bitmaps where no changes were written. Second - if there was some fencing active and some higher-level switched one side to primary - then throw away the secondary changes - this keeps the most recent changes, but propably your now secondary has not been in the primary role long. Third if that did not help you have to resolve this manually.
I might cite Douglas Admams here: "Don't get bitten" (from "Last Chance to See"). There are many possible ways on how to "get bitten" by a split brain. So it depends on your specific setup and why you got into the split-brain situation.
I try to avoid these by using at least three different hearbeat-lines for the clustering above. These three lines should not have any common point of failure. There is at least one very intelligent (commercial) cluster solution that stops reacting if the reaction could lead to a split brain situation. But for the small money solutions stick to the rule of at least three really independent lines...


Converting SAS EWMA code to Python

Question: I have the following SAS code that uses PROC FORECAST that I would like to replicated with the Python Pandas pandas.stats.moments.ewma
proc forecast data=ewma method=expo
  interval=weekday weight=(0.05) /*i.e. lambda=0.95*/
  nstart=20 lead=0
  out=out_ewma outfull;
  id date;
  var sq_gspc cross_returns;
run;

My DataFrame in Pandas is set up to mimic the ewma dataset in SAS -- same column names and everything, including same starting values. However, I can't seem to get the same values calculated with Pandas, probably due to a lack of understanding of the SAS options and how to set up the same calculation with Pandas. For example, to add the sq_gspc and cross_returns columns to my Pandas DataFrame, I'm doing the following:
ewmadf['f_sq_gspc']       = pd.ewma(ewmadf["sq_gspc"],       span=20, freq="D")
ewmadf['f_cross_returns'] = pd.ewma(ewmadf["cross_returns"], span=20, freq="D")

How do I replicate the PROC FORECAST here with the Python parameters?
Edit: SAS documentation provides the following:

For METHOD=EXPO, n beginning values of the series are used in forming
  the exponentially smoothed values S1, S2, and S3, where n is the value
  of the NSTART= option. The parameters are initialized by fitting a
  time trend regression to the first n nonmissing values of the series.
Answer: Short answer is that I don't think you can. Pandas doesn't provide anything like the nstart option or many of the other options that SAS provides. It's not entirely clear to me without looking at the source what exactly pandas is doing here since the docs don't follow the literature I'm familiar with.
You'll find more fully featured exponential smoothing in this PR for statsmodels. We still don't have anything like an nstart parameter. We estimate the starting values heuristically from suggestions in the literature, but you could compute them yourself and pass them in. It's not done yet. I'm still implementing the optimization for starting values and parameters.
https://github.com/statsmodels/statsmodels/pull/1489
Comment: Thanks! I very much appreciate all of the statsmodels work!

Converting SAS EWMA code to Python


How do you sketch arcsin(arcsin(x))?

Question: When I sketch sin(x), arcsin(x) and arcsin(arcsin(x)) on Geogebra, there is a slight difference between the second and third graphs. I thought that perhaps because you're doing an 'inverse of an inverse' that you might get back to the original function but there is something different going on. Can anybody please explain why the gradients are slightly different (endpoints are the same) and how I can show this algebraically?
Comment: "Inverse of an inverse" would be $\sin(\arcsin(x))$ since $\sin$ is the inverse of $\arcsin$. The function $\arcsin(\arcsin(x))$ would be like "inverse twice", and in this case $\arcsin$ is not the inverse of $\arcsin$.
Comment: Indeed, $\sin(\arcsin(x))$ will give the line $y=x$ (restricted to the appropriate domain). However, sketching $\arcsin(\arcsin(x))$ is more difficult to do by hand. One observation: if you know how to sketch $\arcsin(x)$, then for small values of $x$ we have $\arcsin(x)\approx x$, so $\arcsin(\arcsin(x))$ roughly looks like $\arcsin(x)$ for small $x$, and curves away slightly as $x$ gets bigger.
Comment: @Dave Agreed as I thought sin(arcsin(x)) would give the line y=x on the graph. I guess I want to know how to go about sketching this using algebra to help me visualise it :)
Comment: @Dave you're right it is tricky but one of my students asked what's going algebraically and it'd be great to point them in the right direction at least :)
Answer: You could have them compute the Taylor series as far as they want.  Alpha gives
$$x + x^3/3 + (7 x^5)/30 + (64 x^7)/315 + (4477 x^9)/22680 + (28447 x^{11})/138600 + O(x^{12})$$  I think the intuitive terms are the first two.  We know $\arcsin x \approx x$ and the correction is $+\frac {x^3}6$, so taking two arcsins should give twice the correction.
Comment: Thank you! I was kinda hoping for an intuitive visualisation, perhaps using the unit circle and y=sqrt(1-x^2) and doing some sort of compound function like f(f(x)). Do you have any idea if that is something worth investigating because I'm not finding much on it at the mo...
Comment: I don't think so.  I am basically using the chain rule, $(f(f(x)))'=f'(f(x))f'(x)$
Answer: Of course $\sin^{-1} x$ and $\sin^{-1} (\sin^{-1} x)$ have different slopes:  they are different functions!
You know the latter goes through $(-\pi/4, -\pi/2)$, $(0,0)$ and $(\pi/4, \pi/2)$ and is monotonically increasing and antisymmetric.  That gets you close.
But why not just plot it?
Comment: Thank you for your input. I plotted the graphs out which was easy enough and yes, I can get values by putting them into the calculator. I guess what I'm trying to determine is an intuitive explanation as to what is going on 'in the background'. I'm referring to the change in domains and ranges, the different gradients (yes I've differentiated to show the different functions) and maybe trying to use the unit circle to help algebraically. How do you solve arcsin(arcsin(x)) = 0 for example to get the values you mentioned. Arcos(arcos(x)) is very different for example. Waffling now!

How do you sketch arcsin(arcsin(x))?


Problem with Primary Key in a Partial View shared by Create and Edit views

Question: I have a partial view (user control) that is shared by my Create and Edit views.  When I use it in the Edit view, I have to to include an hidden field (Html.HiddenFor) to prevent a 'Row changed or not found' error in my data service, but when I use it in the Create view, I have to remove the PK hidden field, to prevent an error over trying to insert into an identity column.
It is not feasible to not use identity columns in this application, so how can I 'switch' that PK hidden field on or off depending on which action has been invoked?
Post Action Code:
    [HttpPost]
    public ActionResult Edit(JobCardViewData viewData)
    {
        try
        {
            jobCardService.Update(viewData.JobCard);

Edit View Excerpt:
<% Html.RenderPartial("JobCardInput", Model); %>

Partial Excerpt:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Poynting.Installation.Web.ViewData.JobCardViewData>" %>
<% using (Html.BeginForm())

Answer:
when I use it in the Create view, I
  have to remove the PK hidden field, to
  prevent an error over trying to insert
  into an identity column.into an identity column.

Leave the hidden field and update the Create action to check if the value is 0 or null (I assume that JobCard is an argument type of the Create action). Another thought would be to re-create a new JobCard object, which excludes setting the id value, and send the new object to the jobCardService create method.

so how can I 'switch' that PK hidden
  field on or off depending on which
  action has been invoked?

You could possibly create a HtmlHelper to render the hidden field for you. Check the ViewContext RouteData collection for the the action name output the hidden field accordingly if required. (Pseudo-code..)
public static MvcHtmlString HiddenTest(this HtmlHelper htmlHelper, string name)
{
    string currentAction = htmlHelper.ViewContext.RouteData.Values["action"].ToString();
    if (currentAction = "Edit"){
     return htmlHelper.Hidden(htmlHelper, name);
    }
   return null;
}

Comment: my problem here with your first suggestion is the JobCardId is int, so it's never null, and the value the controller is getting back from the view (when using the hidden field) is 0, which goes with the jobCard to the servive.  Your second looks good, and I've actually done alomst that without enclusing in  helper. Thanks!
Comment: Completely agree on the first option - an int will never be null, however in your controller you can check if it is 0 and then re-create a new JobCard object from the posted values.
Answer: can you have your PK in the url?
ThingController/Create
ThingController/Edit/1234
Comment: On the get edit action, it is in the url (value 1), but when I click Save, in the post edit action it is set to 0 in the url, unless I include that hidden field for it.
Comment: In the create post that does the save, save your data and get the id, the redirect to the edit page with the id
Comment: @Anthony, I'm not trying to edit following a create.  I'm trying to edit from the list my Index view, and I have the id when I call edit.
Comment: are you specifying the form post url? could you post the code for your partial and post action?
Comment: your id is on the JobCardViewData object? if so you are not updating it, you are only updating the sub-object JobCardViewData.JobCard


cost estimation in software development project, Function Points?

Question: I have this quick question regarding cost estimation using Function Points.
We are doing a small (course project) project for a small company and it's for free, of course. Our instructor wants us to provide a cost estimate of the project using Function Points.
Computing the Function Points is somewhat straight forward (sort of).
Our problem now is on deriving other values (metrics) e.g. length of project duration, rate for the cost of the project per function points.
Obviously, we don't have historical data to based our estimate on. Is there some sort of "typical" cost per function point that we could follow out there? Please help.
Answer: Software Engineering by Hans van Vleet quotes that one function point is 100 lines of COBOL (!), if that's any good to you. There's data out there for converting lines of code to staff-months, project duration, etc.
Do you have access to a library? Start with a general book on software engineering, or one of Steve McConnell's various books. They will contain data, and references to more data.

Rapid Development
Code Complete 2
I mustn't forget Software Estimation. Personally I haven't yet read it that, but his other books are excellent.

Be aware that tracking progress and controlling the project scope are probably at least as important to success as the original estimate.
Answer: Here are some formulas that Capers Jones devised from relatively high number of counted projects:
Given you have your FP count you can determine :

Schedule in calendar months: FP^0.4
Defect potential: FP^1.25
Software development staffing levels: FP/150

You might go for industry standards for your technology to obtain FP/Person Months or Hours/FP if you don't have historical data (which is your case).
Answer: A simple GOOGLE will give you MANY results to start from

Cost estimation in software
engineering
Handbook for Software Cost
Estimation
Comment: You might also want to take into account. Estimate the time and then relize that it will probably take 2 time longer, **MINIMUM** to actually complete. Between things that you missed in the original spec, and the client changing the spec, you will surely miss the correct total. Give yourself enough time to complete the task. Break the bigger task into smaller, so that you can easily map the end result.
Comment: well, i think it' safe to assume that most methods actually give you an estimated measure of the 'size' of the product i.e. function points, person-months (COCOMO), etc, which we've done already. What I am asking for is another set of estimates (cost per function points, person-month per functions) that we could multiply with the function value that we already have. tnx btw
Comment: Unfortunately this will be heavily dependant on the team experience. This will become more of an art than an actual science. http://www.codinghorror.com/blog/2006/07/how-good-an-estimator-are-you-part-iii.html. http://www.amazon.com/exec/obidos/ASIN/0735605351/codinghorror-20
Comment: and since we don't have any experience to based out estimate upon, what are our available options then? is there any? tnx, perhaps i'll just pop a figure into the formula and give this as a rationale: "'coz we say so", ehehe
Answer: There are Function Points to SLOC conversion tables, for example this one by QSM Software
(shows amount of SLOC per function according to complexity rank).
There's also Weighted Micro Function Points method that outputs development duration, which gained popularity over the last 10 years or so
(there are tools like ProjectCodeMeter that make it a breeze to use)


Javascript document.title doesn't work in Safari

Question: I'm using Safari 6.0.5.
I open a new empty window, try to change the title to 'debug window', nothing happens. With a check function checking every 10 milliseconds, it says the window.document.title is 'Debug Window', still the new Window title bar says it is 'untitled'.
var debug_window    =   window.open('', 'debug_window', 'height=200');

debug_window.document.title     =   'Debug Window';

    function check()
    {

    debugLog(1, 'title:' + debug_window.document.title);
    if(debug_window.document) { // if loaded
        debug_window.document.title = "debug_window"; // set title
    } else { // if not loaded yet
        setTimeout(check, 10); // check in another 10ms
    }
     }
     check();

The output in the debugLog is:
17:35:04.558: title:
17:35:04.584: title:debug_window

What is going wrong here that the new window is still called 'untitled'?
Thanks!
Comment: Yes probably, there some bugs in Safari. It's pity, that it's not working.
Comment: `debug_window.document.getElementsByTagName("title")[0].childNodes[0].nodeValue = "Debug Window";` ;) or first create title element and then append it
Comment: Try this... http://jsfiddle.net/GKDev/93QFk/
Comment: @Givi, it still says untitled at your link...
Comment: My own code works in Chrome, it is Safari that is bugging me; Your code works too in Chrome. Thnx!
Answer: Now the second argument to window.open() is a frame/window-name and serves also as the default title. This is eventually overridden by the document loaded into this window. Opening the document-stream and inserting a basic html-document should serve the purpose:
var debug_window  = window.open('', 'debug_window', 'height=200');
debug_window.document.open();
debug_window.document.write('<!DOCTYPE html>\n\n\n<title>Debug Window</title>\n\n\n');
debug_window.document.close();

var debug_body = debug_window.document.getElementsByTagName('body')[0];
// write to debug_window
debug_body.innerHTML = '
Message
';

So you would be setting up a basic document inside the window, just as it would be loaded by the server (by writing to the "document stream"). Then you would start to manipulate this document like any other.

Edit: Does not work in Safari either.
Other suggestion: set up a basic document (including the title) on the server and inject the   content into its body on load. As a bonus, you may setup CSS via stylesheets.
var debug_window  = window.open('debug_template.html', 'debug_window', 'height=200');
debug_window.onload = function() {
  var debug_body = debug_window.document.getElementsByTagName('body')[0];
  debug_body.innerHTML = '...';
  // or
  // var el = document.createElement('p');
  // p.innerHTML = '...';
  // debug_body.appendChild(p);
  debug_window.onload=null; // clean up cross-reference
};

And on the server side something like
<!DOCTYPE html>

    <title>Debug Window</title>
    <link rel="stylesheet" href="debug_styles.css" type="text/css" />

If this still should not work (e.g.: writing to the debug-window's document is without effect), you could call your app from inside the debug-window by something like:

(So you would check if the opener – your App – exists and hasn't been closed in the meantime and then call a callback-function "debugCallback()" in your app with the debug-window and its document as arguments.)
Comment: Just tried this myself, Safari seems to be a special breed here. Inspecting the title via DOM shows the correct title, but it does not show up in the window's title bar. – You may try to load a document with the basic HTML (including the title) and inject your content into its body as soon as it has loaded.
Comment: Thank you, your code works in Chrome, but not in Safari. Probably Safari is the bottle neck...
Answer: Try:
var debug_window = window.open('about:blank', 'debug_window', 'height=200');

Comment: Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem. It's also recommended that you don't post an answer if it's just a guess. A good answer will have a plausible reason for why it could solve the OP's issue.


Starting point of Vinogradov-Korobov method

Question: Let's define, for $n,k,P\in\Bbb N$
$$
J_{k,n}(P):=\int_0^1\cdots\int_0^1\left|\sum_{x=1}^Pe(\alpha_1x+\alpha_2x^2+\cdots+\alpha_nx^n)\right|^{2k}\,d\alpha_1d\alpha_2\cdots d\alpha_n\;\;,
$$
where $e(x):=e^{2\pi ix}$.
Observing now that $|z|^2=z\bar z$ and that $\int_0^1e(kx)\,dx$ equals $1$ if $k=0$ and vanishes for any other integer value of $k$, how can I show that $J_{n,k}(P)$ expresses all the integer solutions of the system
$$
x_1+x_2+\cdots+x_k-x_{k+1}-x_{k+2}-\cdots-x_{2k}=0\\
x_1^2+x_2^2+\cdots+x_k^2-x_{k+1}^2-x_{k+2}^2-\cdots-x_{2k}^2=0\\
\vdots\\
x_1^n+x_2^n+\cdots+x_k^n-x_{k+1}^n-x_{k+2}^n-\cdots-x_{2k}^n=0\\
$$
where $1\le x_1,x_2,\dots,x_{2k}\le P$ ?
I'm trying to rewrite $J_{k,n}(P)$ in different ways, but I think it's something that should be seen quite quickly, not writing down all the details... but I can't see how.
Can someone helps me?
These kind of subjects are the starting point of the Vinogradov-Korobov method in the theory of the Riemann Zeta Function (I'm reading 6th chapter of Ivic Book).
Comment: Are you really indexing sums by $x$?
Comment: @b00nheT: yes. The Ivic's book does so. Here $x$ is an integer.
Answer: The idea is to expand out the integrand; we write it as
\[\prod_{j = 1}^{k} \left(\sum_{x_j = 1}^{P} e\left(\alpha_1 x_j + \cdots + \alpha_n x_j^n\right)\right) \times \prod_{j = k + 1}^{2k} \left(\sum_{x_j = 1}^{P} e\left(-\alpha_1 x_j - \cdots - \alpha_n x_j^n\right)\right).\]
We then expand everything and group like terms, obtaining
\[\sum_{x_1 = 1}^{P} \cdots \sum_{x_{2k} = 1}^{P} \prod_{\ell = 1}^{n} e\left(\alpha_{\ell} \left(x_1^{\ell} + \cdots + x_k^{\ell} - x_{k + 1}^{\ell} - \cdots - x_{2k}^{\ell}\right)\right).\]
We now interchange the order of summation and integration. The key point is that the integral will vanish unless the coefficient of $\alpha_j$ is $0$ for all $j \in \{1,\ldots,n\}$. This happens precisely when $x_1,\ldots,x_{2k}$ are solutions to the system of equations.


Spring XD integration with hortonworks sandbox

Question: I am trying to do the Hortonworks tutorial "Using Spring XD to stream Tweets to Hadoop for Sentiment Analysis"
As part of the step I am using the command:
xd>xd-shell --hadoopDistro hadoop20

xd> hadoop config fs --namenode hdfs://10.0.0.27:8020

xd> hadoop fs ls /

At this point I get a timeout exception.
Thus, I used the next step of creating a stream
xd>stream create --name ticktockhdfs --definition "Time | HDFS"

At this point I get the following error:

Caused by: java.net.ConnectException: Call to localhost/127.0.0.1:8020
  failed on  connection exception: java.net.ConnectException: Connection
  refused: no further  information
          at org.apache.hadoop.ipc.Client.wrapException(Client.java:1142)
          at org.apache.hadoop.ipc.Client.call(Client.java:1118)
          at org.apache.hadoop.ipc.RPC$Invoker.invoke(RPC.java:229)
          at com.sun.proxy.$Proxy52.getProtocolVersion(Unknown Source)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

I am using a Windows 7 laptop where I have the Hortonworks Sandbox.
In the Hortonworks sandbox setting I have:
1) Network --> Disabled the NAT driver
2) USing the Bridged Adapter --> Intel(R) Contrino(R) Ultimate-N 6300 AGN.
I am new to this, so pardon me if I have done small mistake
Answer: I wonder if you have the correct IP address for the Hortonworks Sandbox - did you see that address as the Sandbox started up? See if you can connect to the Sandbox using http://10.0.0.27:8888 in a browser.
What version of Spring XD and Hortonworks Sandbox are you using? It should work with Hortonworks Sandbox 1.3. The latest Sandbox 2.0 isn't supported yet in an XD milestone release (should be in the next release).
-Thomas


Dúvida em recebimento de dados

Question: Tenho um sistema em um computador que enviará dados para outro sistema em outro computador. O sistema que receberá os dados precisará ficar lendo esses dados recebidos em tempo real e automático.
Mas minha dúvida em construir o sistema é de como posso fazer para ele saber em tempo real e automaticamente que recebeu os dados do outro sistema?
Utilizo java..
------------------ EDIT ------------------
Estou fazendo um projeto de TCC, um computador que ficaria no balcão do estabelecimento teria um programa que o usuário cadastra os pedidos das pessoas. Ai teria um botão de enviar o pedido, ai esse botão enviaria os dados do pedido para um computador que fica na cozinha do estabelecimento. Mas nesse computador da cozinha, seria um outro sistema que fica "escutando" a chegada destes pedidos, ou seja teria que ser automático para saber quando um pedido chegou.
Comment: Partindo do principio que será uma arquitetura cliente/servidor com um outro cliente lendo as informações, se foi o que entendi, você pode usar `Sockets / Threads` que irão ficar `ouvindo` para processar as informações.
Comment: @RodrigoLima Neste caso a solução mais fácil serve: o computador do balcão salva o pedido numa base de dados compartilhada e o software no computador da cozinha tem um timer que de tantos em tantos segundos verifica a base. Se para o TCC você precisa elaborar uma solução mais complexa, então é melhor inventar um problema mais complexo também, onde daí sim a solução poderia passar por socket ou sistema de filas de mensagens.
Comment: @RodrigoLima Chat é um tipo de aplicativo que apesar de simples faz todo sentido usar socket. De quaquer modo eu não sei os objetivos ou critérios do TCC né. De repente aceitam o lance dos pedidos. Só que na vida real seria pouco provável investir numa solução mais complexa para isso do que simplesmente ficar checando a base. Outras opções (onde eu me lembro de já ter usado socket): monitoramento em "tempo real" de equipamentos industriais, notificação de atualização de estado em sistemas de terceiros, servidor de aplicativos proprietário, filas de mensagens entre sistemas...
Comment: Como você irá fazer o envio dos dados?
Comment: Bom estudo. http://www.devmedia.com.br/java-sockets-criando-comunicacoes-em-java/9465
Comment: Rodrigo, você quer uma indicação de tecnologia ou quer uma solução pronta para o seu problema? Esses sistemas já existem ou serão criados? Por quem? É um projeto acadêmico ou um sistema de verdade? Que tipos de dados serão transmitidos? Qual a natureza da comunicação? Precisa haver resposta? Poderia definir melhor o que seria "tempo real"? Quais ações o outro sistema precisa executar e qual o tempo de resposta esperado? Há algum risco se houver demora? Há possibilidade de haver eventos de comunicação executando simultaneamente?
Comment: Estou fazendo um projeto de TCC, um computador que ficaria no balcão do estabelecimento teria um programa que o usuário cadastra os pedidos das pessoas. Ai teria um botão de enviar o pedido, ai esse botão enviaria os dados do pedido para um computador que fica na cozinha do estabelecimento. Mas nesse computador da cozinha, seria um outro sistema que fica "escutando" a chegada destes pedidos, ou seja teria que ser automático para saber quando um pedido chegou.
Comment: Entendi, poderia me citar um exemplo, de em que tipo de sistema o Socket pode ser usado?
Answer: Em tempo real mesmo pode ser difícil, para não dizer impossível.
Algum atraso você deverá ter, já que tem a rede entre os computadores no meio.
A melhor forma de fazer a comunicação é uma arquitetura de cliente servidor mesmo, com um dos sistemas enviando e outro recebendo dados.
Em Java, vale a pena dar uma olhada em como funciona a parte de Sockets e de rede para mandar e receber pacotes em UDP ou TCP (padrão de comunicação com ou sem conexão).

Dúvida em recebimento de dados


Hide the email address when searching for users

Question: When using the Drupal custom search form, and searching for users (search/user), the user's email address is displayed to administrator users. I want to hide it, even to the administrator users.
How can I do this?
Comment: If you are logged in as administrator, you'll see the email. Normal users should not see it. Try logging in as a regular user if you have not done so already.
Comment: Is this email normally hidden?
Comment: Yes, I already did that. Only being an administrator I am able to see the email of the user. But my requirement is to hide the email from search result list for admin also.
Answer: I think there is no such an option to hide email addresses from drupal system. You can create your own search-results.tpl.php in your theme or use template_preprocess_search_results() in your template.php to alter the user names.
Answer: Only user with the Administer users permission are able to search user by email and and view email on user search result. This permission also give them many right like editing the users' profiles, including seeing and editing their email address.
If you really want to grant this permission the some administrative users, allow them the access the other features requiring the Administer users permission but hide the email address in the user search results, then implementing HOOK_preprocess_search_result() (without the 's') in your custom theme or module is a good way to remove the email addresses. In your hook implementation, you will want to remove the email addresses from $variables['title'] which contains the username followed by the email address. You can retrieve the user object in $variables['result']['user'] and use $variables['result']['module'] == 'user' to check if the result is a user search result.


How to prove that there are $n$ natural numbers that are less or equal than $n$ and what properties are allowed to use in induction.

Question: Let $n \in \mathbf{N}$. I wondered how to prove that there are exactly $n$ natural numbers that are smaller or equal than $n$. This seems somewhat circular which confuses me. I guess the way to do this is by induction and using the successor, but again, the circularity that I see feels weird. So my idea would be: induction over $n$.
The case $n=1$ is clear by definition and if the induction holds for $n$, then we at least have $n$ elements that are less or equal than $s(n)$, as well as $s(n)$ itself, making it at least $s(n)$ elements. If there would be another natural number $m$ with $m \leq s(n)$, then it has to hold that $m \leq n$, since we assumed it to be a different element. Hence it is one of the $n$ elements and the desired result follows.
I also wondered whether this property is allowed to use as a property in the induction and what properties are. For example, I read something like: for all $n$ the notion $A_n$ is defined. Is "is defined" a property I can proof with induction? Are there limits of what properties I can proof for $\mathbf{N}$ using induction and if so, what are they, meaning, which properties are allowed?
Answer: I would say much your proof is good. The structure is certainly correct, and many of the details as well. Two small remarks though:
First, I am not sure that you can do the base case simply 'by definition'. That is, is it a definition that $1$ is the only number smaller or equal to $1$? It depends on exactly what definitions and axioms you work with, but probably the base case is not so trivial. For the base case you need to show that $1 \leq 1$, and that for any number $n \neq 1$, it holds that $n \not \leq 1$.
Second, in the inductive step, you need to make sure that $s(n)$ is not one of the numbers that are smaller or equal to $n$. So, you need to show (or at least point out) that $s(n) \not < n$, so that when you add $s(n)$ to the $n$ numbers smaller or equal to $n$, you actually increase the set size by $1$ (as opposed to having $s(n)$ already in the set of numbers smaller or equal to $n$)
But yes, it is very good of you to include that part that says that if $m$ is a number other than the $n$ numbers that are smaller or equal to $n$, as well as other than $s(n)$, then $m \not \leq s(n)$. You indeed need that part to ensure that $s(n)$ is the only number that is not smaller or equal to $n$, but that is smaller or equal to $s(n)$. Well done!
Finally, note that with these small corrections, it turns out that what you do in the inductive step very much mirrors what you do in the base case: you show that there is at least one object such that .... and that there is at most one such object ...
Answer: For each $n \in \mathbb{N}$, let $A_n = \{k \in \mathbb{N} : k \leq n\}$. I would interpret your statement formally as $|A_n| = n$. I think that this is actually the definition of "having $n$ elements": a set $S$ has $n$ elements means there is a bijection from $S$ to $A_n = \{1, 2, \dots, n\}$.
Comment: Rather than being by definition, wouldn't it follow from the existence of the identity bijection?
Comment: @Joe I haven't learned set theory axiomatically. But in many books on informal set theory, the definition of "$|S| = n$" is "there exists a bijection $f \colon \{1, 2, \dots, n\} \to S$.
Comment: Yes, but $|\{1,\ldots,n\}|=n$ is not part of the definition you just gave, so to show that we need to show that there is a bijection from $\{1,\ldots,n\}$ to itself, which is trivial, the identity function from $\{1,\ldots,n\}$ to itself, but we technically need to show that.
Comment: @Joe Yes that is true.


Who is the best striker (best goals/appearances ratio) with 25/50/100+ national caps?

Question: Zlatan Ibrahimovic recently had his 50 goals milestone (also a national record for Sweden) prior to with 100 appearance for the team. With 50 goals in 100 games he's averaging a goal in every second game which is as far as I can tell a great ratio, making him one of the most prominent strikers of modern football.
Which brings me to my question, who is the "best" striker in football history, judging by the goals/appearances ratio? In order to avoid outliers with only a few caps, I chose to focus on veteran strikers who have played at least 25/50/100 games for their national team.
Comment: A cap limit is needed, but limiting to 100+ caps removes quite a few veterans from previous eras, like Pelé, Gerd Müller, Ferenc Puskás and Sándor Kocsis, who are more than statistical outliers. So good question, but don't expect a definitive answer to the "best" in history.
Comment: @posdef Min. 25 games, [Poul Nielsen](http://en.wikipedia.org/wiki/Poul_Nielsen) 1.37; Min 50 games, [Ferenc Puskás](http://en.wikipedia.org/wiki/Ferenc_Pusk%C3%A1s) 0.99...
Comment: What I have just realized about this Wiki, is that it is *most goals* for each country, not *highest ratio*! My answer will need to be revised because the question asks for best goal ratio, which this Wiki does not necessarily tell us. E.g., Klose has the most goals for Germany, but Gerd Muller actually has a *better ratio*...
Comment: Just to clarify, best goal/appearance ratio for National team games *only*, right?
Comment: @Fillet agreed, I had to put a limit and went with 100 as it's relevant for Zlatan's accomplishment. It would be interesting to check that stat with 50 caps as well, I agree.
Comment: @posdef - Will do. Please update your question to ask about 25 game minimum, and 50 game minimum as well so the additional information in my answer will be related to  your question :-)
Comment: According to that wikipedia table it is not possible to reply to the question. E.G: it can be a player from Iran with 108 goal in 108 caps (ratio = 1) or a brazialian with 76 goal in 100 caps (ratio = 0.76)...
Comment: I thought that it might be interesting to ask the same questions about goals scored at the club level: http://sports.stackexchange.com/questions/5761/which-soccer-players-have-more-goals-than-caps-at-the-club-level  (Although I do not think there will be many players who managed something like that.)
Answer: Since this answer will probably need occasional updates, I have made it community wiki.
The post is compiled from these sources:1

More goals than caps at fifa.com (Wayback Machine)
List of footballers with 50 or more international goals at Wikipedia. (Link to an older revision, around the time when the first version of this posts was compiled.)
Wikipedia articles about individual players.

Below is the list of players having more goals than caps which have played at least 25/50 international games.
25+ caps

Poul Nielsen (Denmark) 1.37 (52 goals in 38 games)
Gunnar Nordahl (Sweden) 1.30 (43 goals in 33 games)
Sven Rydell (Sweden) 1.14 (49 goals in 43 games)
Ernest Wilimowski (Poland, West Germany) 1.13 (34 goals in 30 games)

50+ caps

Sándor Kocsis (Hungary) 1.102 (75 goals in 68 games)
Gerd Müller (Germany) 1.097 (68 goals in 62 games)

100+ caps
According to the sources I cited above, there are no players in this category with an average number of goals above 1. The best goals-per-game ratio of any player with 100+ caps is that of Ali Daei (Iran), at 0.74 (109 goals in 148 games).
The players with at least 100 caps and average at least 0.50 can be found in the Wikipedia article: List of men's footballers with 50 or more international goals.

Ferenc Puskás is close to 1 goal per match ratio with 84 goals in 85 matches if we only count his appearances for Hungary. After emigration he also played in 4 international matches for Spain.
Another near-miss is Kunishige Kamamoto (Japan) with 75 goals in 76 appearances.
Also Luis Artime (Argentina) was very close to make the above list, with 24 goals in 25 appearances.

1 See also the comments to Nicholas V.'s answer and the links mentioned there.
Comment: I am not sure about the reason, but Godfrey Chitalu is now missing from the list on Wikipedia. Here is a link to [an older revision](http://en.wikipedia.org/w/index.php?title=List_of_footballers_with_50_or_more_international_goals&oldid=630729397) where he was still included.
Answer: Information on record scorers by country is available on Wikipedia.
With the table sorted by Goal scoring ratio, the highest goals per international game meeting the minimum national caps is listed below:
Min. 100 Caps:

Godfrey Chitalu, with a ratio of 0.73 goals per international game played.

Min. 50 Caps:

Ferenc Puskás, with a ratio of 0.99 goals per international game played.

Min. 25 Caps:

Poul Nielsen, with a ratio of 1.37 goals per international game played.

Assuming Wikipedia's data is accurate.
Comment: Agree with @Ale, except that is it not only possible: According to [wikipedia, Gerd Müller](https://en.wikipedia.org/wiki/Gerd_M%C3%BCller) has scored 68 goals in 62 appearances, so the above list (including only the top scorers by country in terms of total goals) is the wrong source to answer this question.
Comment: According to this table is it possible that a player from Iran has scored 108 gol with 108 caps (for example) with a ratio of 1. So I think this table do not reply correctly, mostly for >25 and >50 caps
Comment: For example, Sandor Kocsis has 1.10 average from 68 games, see [here](http://en.wikipedia.org/wiki/Hungary_national_football_team#Top_goalscorers).
I think that [this link](http://www.fifa.com/world-match-centre/news/newsid/106/577/9/index.html) might help. (It was given in the Wikipedia article you mentioned in your answer.)
Comment: As far as [Puskás](http://en.wikipedia.org/wiki/Ferenc_Pusk%C3%A1s) is concerned, it should be mentioned that the ratio 0.99 is calculated only from his games for Hungary. After his emigration, he also played 4 games for Spain, but did not score any goals.
Comment: That's it! In fact for min 50 caps and min 25 caps the reply is more difficult
Comment: @arne.b, yeah, I've recognized this in the question's comments, I just need some time to get around to revising this answer.
Comment: [This list](http://en.wikipedia.org/wiki/List_of_footballers_with_50_or_more_international_goals) seems to help with 100+ caps; since in order  to beat Chitalu's the player would have to score at least 73 goals.
Comment: @Martin - yep. I should have mentioned this on my answer's comments, instead I referenced on the *question's* comments. This is all pretty clear, don't worry. Just need some time to revise the answer =)
Comment: @NicholasV. I have posted another answer, based on some of the links mentioned in my comments here. I see no harm in having two answers. I just wanted to mention this to you - so that you are aware of the other answer in case you start working on revising yours.


Rest above a note in a piano piece

Question: I am playing a piece and wondering, what the heck is this rest doing here above this note?

The piece is in 3/4, so I see no purpose in the 1/4 rest.
I've been googling around but did not find any proper explanation. Most answers says that the piece has more then one voice. It obviously does, but I still don't get it.
Comment: You have two voices there (signified by the different stem directions). One voice has a half and a quarter note, the other a quarter rest and a half note.
Comment: @11684 It is the Menuett in G major from Christian Petzold and you are actually right :), it was attributed to Bach, as it is located in BWV 114. It is the 25th verse(?)
Answer: Let's look at what going in the bass clef. You are playing a B for beats 1 and 2 and then playing another B on beat 3, but you also play a D for beats 2 and 3 in the bass. Because you play the D on beats 2 and 3 and the B is also being played on beats 1 and 2, the rest is used to show you what beat to start playing the D.
Without the rest in, the notation would tell you to play the D for beats 1 and 2 instead of 2 and 3. The rest is necessary to show where to play the D. It looks odd, but it's the best way to notate what is happening.
If the lower staff was written as two separate parts in the bass they would look like this:
<code>X:1
K:G
M:3/4
L:1/4
V:1 clef=bass
V:2 clef=bass
%%score 1 | 2
[V:1]
z  D2  |
[V:2]
B,2 B,  |
</code>
Comment: A way to think about this is that there are two voices  on the bass clef: the lower plays 1/2 b, 1/4 b;  the upper plays 1/4 rest, 1/2 d.  The voices are distinguished by the directions of the note stems.
Comment: The description of what everything means is correct, but I don't think it's entirely accurate that "Without the rest it, the notation would tell you to play the B for beats 1 and 2 instead of 2 and 3. The rest in necessary to show where to play the D."  I think it'd be more accurate to say that "the rest makes it explicit where the D should be played."  If every implicit rest were included, much printed music would be much more crowded.
Comment: In this case, the fact that the D half note in the bass clef aligns with the the G eighth note on beat two of the treble.  Even if the quarter rest weren't marked, it'd be rather strange to notate the B and D half notes in the bass clef starting on the first beat in this way.  That said, I don't think that including the quarter rest here is uncommon for *piano* music.  In handbell music, though, where all players are reading from the same score, but are only responsible for a few bells, the rests (where a player needs to damp a bell) are very often left implicit.
Comment: @JoshuaTaylor, you are right. In most music that has multiple voices on a staff, unless no voice at all plays at a particular point, most of the rests are left out. Otherwise the music would be so cluttered as to be unreadable. The Minuet in G by Bach the OP is working on is a beginner piece, so I wonder if the rest is left in to help explain the idea of voices to a beginning player. Otherwise, it would look to a beginner like there are 5 beats in that measure.
Comment: Because this is the accepted and most upvoted answer to the canonical "multiple voices" question, consider updating to make explicit that it applies to "double note" examples as in https://music.stackexchange.com/q/133043/70803.
Answer: It's effectively written as three parts. The treble clef is one line. The bass notes with stems going down is the bass part, comprising B minim and another B crotchet. Then there's the 'middle line', played with the left hand. Obviously it's a D minim, stem up, but that leaves the first beat of this bar with nothing to play. Thus a crotchet rest. You can't mark a rest with an up stem or down stem!
Answer: First, it's 3/4: a crotchet note counts for 1 beat, a quaver counts for 1/2 beat and a minim counts for 2 beats; the bar contains 3 beats in total.
Second, there are 3 voices in this bar: 2 voices for bass clef, 1 voice for treble.

Third, how to play with your right and left hand:

The right-hand plays a crotchet (d2) count for 1 beat.
The left-hand "plays" the crotchet rest and half of the minim (b) simultaneously count for 1 beat.
The right-hand plays 2 quaver notes (g1 and #f1) count for 1 beat.
The left-hand plays half of the minim (d1) and the left half minim note (b) simultaneously count for 1 beat.
The right-hand plays the last crotchet note (g1) for 1 beat.
The left-hand plays the left half minim (d1) and the crotchet (b) simultaneously count for 1 beat.
Answer: There are two separate "layers" of music occurring on the second staff.  As you can see, the notes with downward stems already fill the bar, making 3 beats.  The rest is part of the upper layer of notes, which begins with one beat of rest and continues with 2 beats on the D.

Rest above a note in a piano piece


Laravel 5.2 named route usage with variable parameter

Question: I have a route like this:
// Open New Subscription page
Route::get('/account/subscriptions/create/{menu}', ['uses' => 'Subscriptions\SubscriptionController@create', 'as' => 'subscription.create']);

In my blade template I use the named route like this:

But this format does not work.
How do I pass the variable menu a value while still using the named route (rather than hard coding a url in the href)?
Answer: You can pass your route parameters as the second argument to route() helper:
 'p11-c3']) !!}">

Make sure you're using correct names. Your routing defines subscription.create route while your template refers to organisations.index route.
Comment: Hi @jedrzej.kurylo, you ROCK! Thanks!! And pushing my friendship, do you have a suggestion for this Q? http://stackoverflow.com/questions/34554021/blade-template-and-radio-buttons-select-first-in-foreach-loop


How to filter SVN branch in Hudson's POLL SCM?

Question: We're using Hudson on an SVN repository that hosts a number of projects. One of these projects takes a long time to build, even if no files were changed. Right now Hudson's "Poll SVN" detects that the subversion repository has changed and will try to build the project, even if that change was in a different project.
Is there a way to set up "Poll SCM" to only respond to changes in a certain branch?
Answer: How do you configure the Repository URL of the project (http://subversion.server/svn/project/trunk) or is it the main path of your repository (http://subversion.server/svn)?
If your Project consists of different modules that are spread out across the repository, you need to configure every location individually by adding more SVN locations.
Comment: It is set to the trunk, but that trunk consists of a number of related applications. Most applications build in a short timespan, but one of the projects takes a really long time. Moving it elsewhere is not an option, as the other projects depend on it.
Comment: So just build that one project. 'http://subversion.server/svn/trunk/Long_Project'
Comment: I believe he wants to build everything BUT Long_Project
Comment: You said that the other projects depend on the long one. If the long project doesn't depend on the small projects, than have 2 jobs, 1 for the long project and 1 for all other ones. If the job with the small projects gets triggered because of a code change in the long one it isn't a problem, since they all depend on the long one. The long one gets build when it needs to be build, because it is only triggered if there is a code change. If you need more help, then please specify what programming language you use, what the dependencies are, if you use maven or not.... In essence, way more detail.
Answer: If your repository looks like this:
svn://svn-server/repo/trunk/project-one/
svn://svn-server/repo/trunk/project-two/
svn://svn-server/repo/trunk/very-big-project/
svn://svn-server/repo/branches/project-one/
svn://svn-server/repo/tags/
(etc.)

Then set Hudson up like this:
Repository URL: svn://svn-server/repo/trunk/very-big-project
If the projects are independent (and don't need to be branched and tagged together) it might make more sense to have separate trunks for each project:
svn://svn-server/repo/project-one/trunk/
svn://svn-server/repo/project-one/branches/
svn://svn-server/repo/project-one/tags/
svn://svn-server/repo/project-two/trunk/
svn://svn-server/repo/project-two/branches/
(etc.)

Then Hudson would be
Repository URL: svn://svn-server/repo/very-big-project/trunk


UISearchController - not playing well with child view controllers

Question: I have an issue where my current configuration is:
UITableViewController -> UINavigationController -> A ViewController for swapping out 2 child view controllers.
Each child view controller has a UISearchController associated with them. When the UISearchBar activates, it never seems to have the correct position.
extension MySearchViewController: UISearchControllerDelegate {

    func willPresentSearchController(searchController: UISearchController) {
        var adjustedOrigin = searchController.searchBar.frame.origin
        //FIXME: There's some odd behavior with embedded child VCs where the status bar adjustments are not taken into consideration
        adjustedOrigin.y += UIApplication.sharedApplication().statusBarFrame.height
        searchController.searchBar.frame.origin = adjustedOrigin
        definesPresentationContext = false
        navigationController?.definesPresentationContext = true
        navigationController?.extendedLayoutIncludesOpaqueBars = true
    }

    func didPresentSearchController(searchController: UISearchController) {
        definesPresentationContext = true

    }

    func didDismissSearchController(searchController: UISearchController) {
        var adjustedOrigin = searchController.searchBar.frame.origin
        //FIXME: There's some odd behavior with embedded child VCs where the status bar adjustments are not taken into consideration
        adjustedOrigin.y -= UIApplication.sharedApplication().statusBarFrame.height

        searchController.searchBar.frame.origin = adjustedOrigin
    }

}

You can see in the above that the origin is adjusted as I'm trying to manually correct the offsets of the UISearchBar, which is by far not preferred. I've attempted checking off (in numerous areas) the display under  from the storyboard and via code almost everywhere within the hierarchy. I can't seem to find the offsetting culprit. By default, the UISearchBar will appear all the way under the status bar as such:

This is without my manual adjustments which are still a bit off.
Does anyone have a solution for this?

Edit 1:
Further proof that something in a parent VC is messing up the offset, the actually superView of the UISearchBar is offsetted by -20 when presenting. Hence the following corrects the issue:
import UIKit

class MySearchController: UISearchController {

    override func viewDidLoad() {
        super.viewDidLoad()
        edgesForExtendedLayout = .Top
        extendedLayoutIncludesOpaqueBars = true
        automaticallyAdjustsScrollViewInsets = true

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print(active)

        if active && searchBar.superview!.frame.origin != CGPoint.zero {
            searchBar.superview?.frame.origin = CGPoint.zero
        }
    }
}

Comment: Did you check if you have any weird constraints any of the VC's child or not?
Comment: I'm not sure what you mean by that. The UISearchController is separate from auto layout constraints on the child VCs. The only thing that would be affected is the UISearchBar (which is in a container when injected into the UISearchController during presentation mode). The UISearchBar has translates mask constraints set appropriately to not utilize a specified constraint based layout.
Comment: For the most part, this is definitely something communicating something up the chain for whatever is communicating the contextual offsets, that much I know.
Comment: @TheCodingArt did you ever manage to find a fix for that?
Comment: @jbouaziz there wasn't a concrete answer beyond a small hack I used to manually correct the behavior I saw. I'll attach an answer below that maybe able to at least assist.
Answer: The following was the only way I found that could reliably adjusted for the status bar offset the search controller was incorrectly adjusting for.
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    //FIXME: Unfortunate hack required to adjust for offset of -20 pulled from ????? where ?????
    guard let searchBarContainerView = searchBar.superview where (active && searchBarContainerView.frame.origin != CGPoint.zero) else {
        return
    }
    searchBarContainerView.frame.origin = CGPoint.zero
}

Note that the physical origin was offset by -20 being the height of the status bar. The correction was to ensure the origin was set to 0 forcefully.
Also note that this is an overridden method within the UISearchController subclass.
Answer: For future reference: usually the key in this kind of weirdness is who is defining the presentation context.
From the docs:
https://developer.apple.com/documentation/uikit/uiviewcontroller/1621456-definespresentationcontext
When a context-based presentation occurs, UIKit starts at the presenting view controller and walks up the view controller hierarchy. If it finds a view controller whose value for this property is true, it asks that view controller to present the new view controller. If no view controller defines the presentation context, UIKit asks the window's root view controller to handle the presentation.
So basically you have to make sure that the right view controller in your hierarchy is setting that to definesPresentationContext to YES. No offsets or frame modifications are needed if this is correctly placed. In your case is probably your parent VC the one that needs to define the presentation context and make sure that no child VC sets that to YES.
Comment: If you reference the code above, that exact value has been manipulated too down with no success. I have that particular flag set appropriately and did (back when this was made) manipulate it to match what I expected without success. So unless you have a working code sample for this situation, this answer means nothing and contributes nothing to the question beyond posting documentation.
Comment: my feeling is that you are misunderstanding the usage of the definesPresentationContext as you are disabling it on willPresent and enabling back on didPresent, IMHO this flag tells which view controller in the hierarchy of parent/childVC is going to be responsable for presenting the searchVC so it's constraints are applied to keep the view in the proper place, so set it to true on the presenter of the search bar. In my own experience when you have to tweak offsets, frames etc... to keep things into place it's usually a bad smell that means something is conceptually wrong. hope this helps.
Comment: I don't misunderstand the usage, but ok. There was a reason todo this back here when testing this scenario. Regardless, this doesn't provide a solution rather just an opinionated commentary.