Move class div up in DOM with Javascript?

Question: I'm trying to move a class div (i.e. 'topbar') out of its container and above a div with id (i.e. 'body'). Would this be possible with JavaScript?
Tried something like this without luck:
  document.getElementsByClassName('topbar').appendChild(document.getElementsById('body'));

Updating the question for better understanding. I want to move topbar above the body div.
The html:

Comment: Try to explain better
Comment: you are trying to append the document body. can you post your full code and explain what you are trying to do
Comment: Do you want to insert the "topbar" div above "body" div?
Comment: Yes thats correct. updated the question.
Answer: something like this?

var container = document.getElementById('container');
var content1 = document.getElementById('content1');
var subContainer = document.getElementById('subContainer');
var body = document.body;
var content2 = document.getElementById('content2');
container.insertBefore(content1, subContainer);
body.insertBefore(content2, container);
#container {
    padding:10px;
    background-color: lightgray;
}
#subContainer {
    border: 1px solid black;
    background-color: gray;
}

        Content 1 here blah blah blah

        Content 2 here blah blah blah

        Content 3 here blah blah blah

Comment: Working with just Id´s is something I managed to do. But I wanted to move a class div outside it´s container (div id) and above it.
Comment: @InfotheekSE, check my edited post, is that what you're looking for?
Answer: It looks like you a trying to move the topbar element to be directly before and element with the class body. This can be achieved using the insertBefore() method: JSFIDDLE DEMO
window.onload = function () {

  //find the element to insert before and then get its parent element
  var beforeElement = document.getElementById('body');
  var parentElement = beforeElement.parentNode;

  //find the element we want to move
  //you need the array syntax because 'getElementsByClassName' returns an array of matching elements (even if there is only one match)
  var moveElement = document.getElementsByClassName('topbar')[0];

  //insert the moveElement into the parentElement before the theFirstChild
  parentElement.insertBefore(moveElement, beforeElement);

};

Note: since this code accesses and manipulated the DOM, you need to wrap this whole block in a window.onload = function () { ...script goes here... }; to ensure the DOM has loaded before the script runs.insertBefore() method reference
Comment: He didn't mentioned about where he want to put the topbar.....as a first child of "body" or just above "body"?
Answering such unclear question encourages spoon feeding...
Comment: Close! This placed the div below the target id. I want it to be placed above. @JRulle
Comment: Hmm that didnt work. The div with the id "body" is the first div in the dom, Before this its only a body tag. Does it need a parent element to work? Thanks for the help!
Comment: It should work because it will treat the `` as the parent element. Here is a functional [**JSFIDDLE**](http://jsfiddle.net/jrulle/an5nqcy6/) demonstrating the working code. I also simplified the above to be a singular answer rather than a series of edits.


A statement on exact sequences of R-modules.

Question: My question is related to the answer of this post:
Exact sequence of $A$-modules.
I am trying to understand this answer, but I am stuck at the following statement.
Given is a sequence $A\stackrel {f}{\longrightarrow } B\stackrel {g}{\longrightarrow } C\longrightarrow 0$ of left R-modules. Given is that $g$ "induces" (what does this mean in this context?) an isomorpism $\mbox{coker } (f) = B/\mbox{im } (f)\cong C$. Prove that $A\stackrel {f}{\longrightarrow } B\stackrel {g}{\longrightarrow } C\longrightarrow 0$ is exact, i.e., $g$ is surjective and $\mbox{im } (f) = \ker (g)$. Can anybody help me to prove this? Because I do not see it.
Is there a dual statement?
Comment: An algebraist may shout me down here but I believe the term 'induced' arises from the first isomorphism theorem. In that, if $g$ is surjective then $B$ is isomorphic to $B / \ker g$ for which the result follows since the above sequence is exact, hence $\ker g = \text{Im} f$.
Comment: Why is $C$  isomorphic to $B/ \ker g$ ?
Comment: A typo in my first comment, I meant to write $C$ is isomorphic to $B / \ker g$. In answer to you recent comment, it is by the first isomorphism theorem, check the wiki link for some details https://en.wikipedia.org/wiki/Isomorphism_theorem#First_isomorphism_theorem
Comment: The first isomorphism theorem states that $B/ \ker g\cong \mbox{im } g$. Note that it is not given that the sequence is exact, it has to be proven that the sequence is exact.
Answer: If $h:P\to Q$ is a homomorphism of some sort (of groups, modules, rings, etc.), then the statement that $h$ induces a homomorphism $\widetilde{h}:P/S\to Q$ for a given subobject $S$ of $P$ (subgroup, submodule, ideal, etc.) implicitly says that $S\subseteq\ker(h)$, and that $\widetilde{h}$ is defined on cosets by $\widetilde{h}(p+S)=h(p)$ for any $p\in P$.
The key facts are that

$\widetilde{h}$ is injective $\iff$ $S=\ker(h)$, and
$\widetilde{h}$ is surjective $\iff$ $h$ is surjective

so if we're told that $h$ induces an isomorphism $P/S\cong Q$, then we know that $S=\ker(h)$ and that $h$ is surjective (or in other words that $Q=\mathrm{im}(h)$).
Thus, if you're given a sequence of maps of left $R$-modules $$A\xrightarrow{\;\;f\;\;}B\xrightarrow{\;\;g\;\;}C\longrightarrow 0$$
and told that $g$ induces an isomorphism $B/\mathrm{im}(f)\cong C$, then by the two facts above, you can conclude that $\mathrm{im}(f)=\ker(g)$ and that $C=\mathrm{im}(g)$ (i.e., that $g$ is surjective).
Answer: "g "induces"" means that the map $$\begin{matrix}B/Im(f)&\longrightarrow&C\\\overline{x}&\longmapsto&g(x)\end{matrix}$$ is an isomorphism.
Now, given $y\in Im(f)$ then $\overline{y}=\overline{0}$, so $\overline{y}\longmapsto 0=g(y)$. Therefore $Im(f)\subseteq Ker(g)$. For other hand, if $x\in Ker(g)$, then $g(x)=0\in C$. Thus, $\overline{x}$ belongs to kernel of the isomorphism. Hence $x\in Im(f)$ and so $Ker(g)\subseteq Im(f)$.
Since $Im(f)=Ker(g)$, then the sequence is exact in $B$ and $B/Ker(g)=B/Im(f)$ is isomorphic to $C$ and $Im(g)$. Therefore $C=Im(g)$. It follows that the sequence is exact.


Erro no Spring Framework: Não foi possível localizar nem carregar a classe principal

Question: Estou seguindo algumas aulas de um workshop de Spring, mas não consigo prosseguir por conta do erro: Não foi possível localizar nem carregar a classe principal. Segue abaixo o código que contém a função main:
<code>package com.algaworks.vinhos;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class OficinaSpringFrameworkApplication {

    public static void main(String[] args) {
        SpringApplication.run(OficinaSpringFrameworkApplication.class, args);
    }
}
</code>
Segue abaixo a estrutura de pastas:
Comment: Como vc está executando o projeto? Pelo Maven? Gradle? IDE? Onde está sendo exibido este erro?
Comment: Eu estou executando o projeto pelo Spring Tool Suite, o erro é exibido no console da IDE. Antes de compilar uma mensagem é exibida alertando que o projeto possui erros.
Comment: Você pode incluir a estrutura de pastas do seu projeto?
Comment: Estrutura de pastas adicionadas no post
Answer: Essa mensagem no STS poderá ser problema de repositório do Maven.
Já me aconteceu um projeto que estava a funcionar, deixar de funcionar e começar a dar esse erro após baixar outras libraries para outro projeto.
Fazer o Maven - Update Projet e esperar até ao fim do STS atualizar, poderá resolver o problema.
Answer: Olá, estava com esse problema, coloquei a pasta do meu projeto no disco "C".
Acredito que seja um problema de visibilidade do Maven e Spring.
Esse arquivo demo é um teste de projeto, nesse diretório rodou tranquilamente


What is it used to parallellize machine learning (RandoForest, SVM, etc) training and to accelerate inference?

Question: I would like to know what is it used to parallelize ML models and to optimize them?
DEEP LEARNING
When using Deep Learning usually a GPU is used for training and inference (deployment). This is understandable as GPUs have thousands of cores and Deep learning uses tensors. So, GPUs are used to parallelize using CUDA.
And in the deployment phase, TensorRT or TensorFlow-TRT are used in order to optimize the layer graph:

Elimination of layers whose outputs are not used
elimination of operations which are equivalent to no-op
the fusion of convolution, bias and ReLU operations, etc).

But in the case of Machine Learning, what do we have to parallelize and optimise?
MACHINE LEARNING
CPUs do not have as many cores as GPUs but have a larger memory capacity. Machine learning models, usually are not as complex as Deep Learning ones.
Obviously, TensorRT nor TensorFlow-TRT will be used with SVM, RandomForest, etc; as there are no tensors. So, How can we optimize ML models?
In scikit-learn there is "n-jobs" to parallelize. But, will it work when using GPUs? Or is it neccessary to usa CUDA? Or do ML algorithms need to be rewritten in order to parallelize (see: PSVM: Parallelizing Support Vector Machines on Distributed Computers).
Thank you
Answer: Machine learning models, with the exception of neural networks, generally do not use the GPU. However, some algorithms can utilize multiple cores/threads. This depends on the algorithm. If the algorithm can easily be broken into multiple independent processes which don't depend on each other's output, then it can be run in parallel. For example, with a random forest, you can train multiple trees at the same time on different threads. For other algorithms, like SVM, it is more difficult or impossible without changing how the algorithm works (see PSVM). Scikit-learn's support vector classifier does not support multi-threading, as an example. However, if you're training multiple models, such as multiple SVMs, you can always train them in parallel.
Comment: @RyanVolpi All modern GBDTs have GPU implementations, now mostly CUDA-based. In case of XGBoost it makes a large difference, as it is relatively slow in the CPU (compared to LightGBM). Catboost has even multi-GPU support (but usually does not improve training times beyond 1 GPU).
Comment: But in the case of deployment? when the model is already trained? Do we just put the model in a server and that is all? No need to accelerate the inference for the many people/machines that might use it?
Answer: I find it hard to tell, what exactly the question is. "Deep Learning" and "Machine Learning" are not disjunct terms. Deep Learning is a special case of Neural Network learning which is a special case of Machine Learning. As Ryan Volpi explained, different parts of Machine Learning lend differently to parallelisation. Neural Networks often perform well on GPUs and with them Deep Learning.
A different question is the meaning of n-jobs in Python's scikit-learn and whether that addresses GPUs. We find the answer in the scikit-learn FAQ on https://scikit-learn.org/dev/faq.html :

FAQ: Will you add GPU support?
Answer: No, or at least not in the near future. The main reason is that GPU support will introduce many software dependencies and introduce platform specific issues. scikit-learn is designed to be easy to install on a wide variety of platforms. Outside of neural networks, GPUs don't play a large role in machine learning today, and much larger gains in speed can often be achieved by a careful choice of algorithms.

And then there is the question of "Is is necessary to use CUDA?". CUDA is a parallel computing platform and programming model developed by NVIDIA for general computing on GPUs. So at this time CUDA is a requirement to use NVIDIA GPUs for machine learning/neural networks but often you do not have to use CUDA yourself but rather software that makes use of it for you.
Comment: Whether machine learning models are deployed in interpreted or compiled form is an individual decision made by those who deploy it. In many cases interpreted solutions will be performant enough.
Comment: In deployment, the DeepLearning model needs to be quantised and compiled to accelerate inference when using GPUs and TPUs. Does something similar exist when using MachineLearning? Or is a server enough to manage requests of people/machine who need to use the model?


Android Studio: Problema invisivel?

Question: Olá, estou a fazer uma app para calcular a melhor compra entre 2 produtos, neste caso é papel higiénico.
No título pus problema invisivel porque o android studio 3 não deteta nenhum erro na compilação, no entanto, quando executo a aplicação, quando clico no botão comparar a aplicação dá erro e pede para ser reiniciada, sem explicar onde está o erro. Deixo aqui os códigos para ver se alguém me pode ajudar, pois não encontro o erro, nem o android studio, lool
Ficheiro xml:
<?xml version="1.0" encoding="utf-8"?>

<TextView
    android:id="@+id/textView2"
    android:layout_width="420dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="24dp"
    android:layout_marginStart="24dp"
    android:layout_marginTop="28dp"
    android:text="Comparar 2 preços de papel higienico para saber qual é o mais barato. Preencha os dados e clique no botão Comparar!"
    android:textSize="18sp" />

<EditText
    android:id="@+id/editPrecoA"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/textView2"
    android:layout_alignStart="@+id/textView2"
    android:layout_below="@+id/textView3"
    android:layout_marginTop="19dp"
    android:ems="10"
    android:hint="Preço"
    android:inputType="numberDecimal"
    android:textSize="14sp" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editPrecoA"
    android:layout_alignStart="@+id/editPrecoA"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="41dp"
    android:text="Papel Higiénico A"
    android:textSize="18sp" />

<EditText
    android:id="@+id/editRolosA"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/editPrecoA"
    android:layout_alignLeft="@+id/editPrecoA"
    android:layout_alignRight="@+id/editPrecoA"
    android:layout_alignStart="@+id/editPrecoA"
    android:layout_below="@+id/editPrecoA"
    android:ems="10"
    android:hint="Nº Rolos"
    android:inputType="number"
    android:textSize="14sp" />

<EditText
    android:id="@+id/editMetrosA"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/editRolosA"
    android:layout_alignLeft="@+id/editRolosA"
    android:layout_alignRight="@+id/editRolosA"
    android:layout_alignStart="@+id/editRolosA"
    android:layout_below="@+id/editRolosA"
    android:ems="10"
    android:hint="Metros por rolo"
    android:inputType="number"
    android:textSize="14sp" />

<EditText
    android:id="@+id/editPrecoB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/editPrecoA"
    android:layout_alignBottom="@+id/editPrecoA"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_marginEnd="21dp"
    android:layout_marginRight="21dp"
    android:ems="10"
    android:hint="Preço"
    android:inputType="numberDecimal"
    android:textSize="14sp" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignLeft="@+id/editPrecoB"
    android:layout_alignStart="@+id/editPrecoB"
    android:text="Papel Higiénico B"
    android:textSize="18sp" />

<EditText
    android:id="@+id/editRolosB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editPrecoB"
    android:layout_alignStart="@+id/editPrecoB"
    android:layout_below="@+id/editPrecoB"
    android:ems="10"
    android:hint="Nº Rolos"
    android:inputType="number"
    android:textSize="14sp" />

<EditText
    android:id="@+id/editMetrosB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editRolosB"
    android:layout_alignStart="@+id/editRolosB"
    android:layout_below="@+id/editRolosB"
    android:ems="10"
    android:hint="Metros por rolo"
    android:inputType="number"
    android:textSize="14sp" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textResultadoB"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="15dp"
    android:onClick="calcular_produtos"
    android:text="Comparar" />

<TextView
    android:id="@+id/textResultadoA"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editMetrosA"
    android:layout_alignStart="@+id/editMetrosA"
    android:layout_centerVertical="true"
    android:text="....." />

<TextView
    android:id="@+id/textResultadoB"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/editMetrosB"
    android:layout_alignStart="@+id/editMetrosB"
    android:layout_alignTop="@+id/textResultadoA"
    android:text="....." />

<TextView
    android:id="@+id/textResultadoFinal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/textView3"
    android:layout_alignRight="@+id/textView3"
    android:layout_below="@+id/button"
    android:layout_marginEnd="27dp"
    android:layout_marginRight="27dp"
    android:layout_marginTop="69dp"
    android:text="....." />

Agora o ficheiro da class
package com.blogspot.comprasinteligentes;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Main2Activity extends AppCompatActivity {

    EditText editPrecoA, editPrecoB, editRolosA, editRolosB, editMetrosA, editMetrosB;
    TextView textResultadoA, textResultadoB, textResultadoFinal;
    Button button;

    Double NumRolosA, NumRolosB, TotalMetrosA, TotalMetrosB, NumMetrosA, NumMetrosB, ValorPorMetroA, ValorPorMetroB, PrecoA, PrecoB, Dif, Poupanca;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        //Procura os valores dos objetos
        editPrecoA = (EditText)findViewById(R.id.editPrecoA);
        editPrecoB = (EditText)findViewById(R.id.editPrecoB);

        editRolosA = (EditText)findViewById(R.id.editRolosA);
        editRolosB = (EditText)findViewById(R.id.editRolosB);

        editMetrosA = (EditText)findViewById(R.id.editMetrosA);
        editMetrosB = (EditText)findViewById(R.id.editMetrosB);

        textResultadoA = (TextView)findViewById(R.id.textResultadoA);
        textResultadoA = (TextView)findViewById(R.id.textResultadoB);
        textResultadoFinal = (TextView)findViewById(R.id.textResultadoFinal);

        button = (Button)findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            //Ao clicar em Comparar então vai calcular o produto mais barato
             // Contas ==========================================
             // TotalMetros = NºRolos x Metros por rolo
             // ValorPorMetro = Preco / TotalMetros

             // Dif = ValorPorMetroA - ValorPorMetroB

             // Poupança = Did x TotalMetros

             //================================================

                NumRolosA = Double.parseDouble(editRolosA.getText().toString());
                NumMetrosA = Double.parseDouble(editMetrosA.getText().toString());

                TotalMetrosA = NumRolosA * NumMetrosA;

                NumRolosB = Double.parseDouble(editRolosB.getText().toString());
                NumMetrosB = Double.parseDouble(editMetrosB.getText().toString());

                TotalMetrosB = NumRolosB * NumMetrosB;

               PrecoA = Double.parseDouble(editPrecoA.getText().toString());
               ValorPorMetroA = PrecoA / TotalMetrosA;

                PrecoB = Double.parseDouble(editPrecoB.getText().toString());
                ValorPorMetroB = PrecoB / TotalMetrosB;

             if (ValorPorMetroA > ValorPorMetroB) {
                 Dif = ValorPorMetroA - ValorPorMetroB;
                 Poupanca = Dif * TotalMetrosB;

                 //Mostra resultados
                 textResultadoFinal.setText("Vencedor: Papel Higiénico A\nPoupa nesta embalagem: " + String.valueOf(Poupanca));
             }

             if (ValorPorMetroA < ValorPorMetroB) {
                 Dif = ValorPorMetroB - ValorPorMetroA;
                 Poupanca = Dif * TotalMetrosA;

                 //Mostra resultado
                 textResultadoFinal.setText("Vencedor: Papel Higiénico B\nPoupa nesta embalagem: " + String.valueOf(Poupanca));
             }

             if (ValorPorMetroA == ValorPorMetroB) {
                 Dif = ValorPorMetroA - ValorPorMetroB;
                 Poupanca = Dif * TotalMetrosA;

                 textResultadoFinal.setText("Vencedor: Ambos custam o mesmo!");
             }

             textResultadoA.setText("Preço por metro: " + String.valueOf(ValorPorMetroA));
             textResultadoB.setText("Preço por metro: " + String.valueOf(ValorPorMetroB));
            }

     });

    }

Comment: Olá! ver o erro no LogCat [veja esse link](https://developer.android.com/studio/debug/am-logcat.html?hl=pt)
Comment: Cara, é IMPOSSÍVEL não ter um LogCat com o erro, mas eu acredito que no TextView com ID **editPrecoA** tem um **android:layout_below="@+id/textView3"** sendo que o **textView3** nem foi criado ainda
Comment: Olá, passei o editPrecoA para baixo do textView3, no entanto, não funciona. O programa diz que sofreu uma falha de sistema.
Answer: Você errou aqui:
textResultadoA = (TextView)findViewById(R.id.textResultadoA);
textResultadoA = (TextView)findViewById(R.id.textResultadoB);
textResultadoFinal = (TextView)findViewById(R.id.textResultadoFinal);

Tem 2 textResultadoA
Correto:
textResultadoA = (TextView)findViewById(R.id.textResultadoA);
textResultadoB = (TextView)findViewById(R.id.textResultadoB);
textResultadoFinal = (TextView)findViewById(R.id.textResultadoFinal);

Comment: Grande Amigo! Funciona! Você descobriu a agulha no palheiro!
Obrigado por ver esta falha que me escapou, nem sei como (talvez do copiar e colar).
Comment: Opa, estamos aí ! Não esqueça de ver a forma que o ramaral passou !
Comment: A minha resposta estava errada.
Comment: Estava ? Você só passou como usar com public ao invés de fazer no onCreate não foi ?
Comment: @CelestinoXP não esqueça de marcar como resolvida.
Comment: A minha resposta partia do principio errado de que se o atributo `android:onClick` é usado ele tem de ser implementado. O que não é verdade se se usar o `setOnClickListener()`.
Comment: Ah entendi... é que de costume uso tudo o máximo fora do onCreate, para de pois conseguir manipular as propriedades, ações, etc dos elementos.
Comment: Veja [Vantagem e desavantagem entre onClick e setOnClickListener](https://pt.stackoverflow.com/q/161388/2541)
Comment: Opa ! Vou ver ! Valeu @ramaral ! Obrigado
Comment: @RaoniBZ como faço para marcar como resolvida?
Comment: Ao lado da resposta tem um "V". Clica nele que ficará verde.

Android Studio: Problema invisivel?


Number of particular paths of even length

Question: Let $W_n=\{ w=a_1a_2\cdots a_{2n}: a_i\in\{1,-1\},\ a_1+\cdots+a_j\geq 0,\ \forall\ 1\leq j\leq 2n\}$. Let $W_n^k=\{w\in W_n:w\ \text{does not cross the line}\ y=k  \}$. Is there any way to find $\# W_n^k$?
Example: if $n=2$, then $\# W_2=6$ and $\# W_2^1=1$ and $\#W_2^2=4$.
Comment: Did you check OEIS?
Comment: For fixed $k$ you could use the "transfer matrix method".
Comment: @Jair Taylor: can you give me some reference about that, please?
Comment: @J.Max You can look at e.g., Ch 4.7 of Stanley's [EC1](http://www-math.mit.edu/~rstan/ec/ec1.pdf), but this may be a bit more general then you need. I'll put up an answer.
Comment: @JairTaylor I've always wondered, why the transfer-matrix-method seems so poorly documented online
Comment: This Was my first time of hearing that.
Answer: Fix $k$ and let $a_{n,i}$ be the number of paths of length $n$ with step sizes $\pm 1$ that never leave the strip $\{0, 1, \ldots, k\}$ and end in state $i$, $0 \leq i \leq k$.  If $0 < i < k$, so $i$ is not on the boundary, there are two ways that we could have arrived at the state $i$: either from $i+1$ or $i-1$.  So $a_{n,i} = a_{n-1, i-1} + a_{n-1, i+1}$.  Furthermore, $a_{n, 0} = a_{n-1, 1}$ and $a_{n, k} = a_{n-1, k-1}$ since if we are on the bottom / top we must have come from just above / below.  Thus we have a linear recurrence.  If we write the recurrence as a matrix equation, we get (e.g., for k = 3)
$$ \left( \begin{array}{cc}
a_{n, 0} \\
a_{n, 1} \\
a_{n, 2} \\
a_{n, 3}
\end{array} \right) =
\quad
\left( \begin{array}{cccc}
0 & 1 & 0 & 0 \\
1 & 0 & 1 & 0 \\
0 & 1 & 0 & 1 \\
0 & 0 & 1 & 0 \\
\end{array} \right)\left( \begin{array}{cc}
a_{n-1, 0} \\
a_{n-1, 1} \\
a_{n-1, 2} \\
a_{n-1, 3}
\end{array} \right)
$$
So inductively,
$$ \left( \begin{array}{cc}
a_{n, 0} \\
a_{n, 1} \\
a_{n, 2} \\
a_{n, 3}
\end{array} \right) =
\quad
\left( \begin{array}{cccc}
0 & 1 & 0 & 0 \\
1 & 0 & 1 & 0 \\
0 & 1 & 0 & 1 \\
0 & 0 & 1 & 0 \\
\end{array} \right)^n\left( \begin{array}{cc}
1\\
0 \\
0 \\
0
\end{array} \right)
$$
since the path starts in state $0$.
Then you may quickly compute $a_{n,i}$, and $$\#W_n^k = \sum_{i=0}^k a_{2n, k}.$$  For $k = 3$ this gives OEIS sequence A001519. If you want an explicit formula, you could diagonalize the matrix; OEIS gives the formula $$(\phi^{2n-1} + \phi^{1-2n})/\sqrt{5},$$ $\phi=(1+\sqrt{5})/2$ the golden ratio.  I don't know whether there is a formula for general $k$.


$f(x + iy) = u(x,y) + iv(x,y)$ holomorphic implies that $F(x,y) = (u(x,y), v(x,y))$ is differentiable

Question: My question comes from section 1.6 of Complex Analysis (4th edition) by Serge Lang:
Let $U$ be an open subset of $\mathbb{C}$ and let
\begin{align*}
    f(x + iy) = u(x,y) + i v(x,y), \qquad x + iy \in U
\end{align*}
be a complex-valued function on $U$. Lang argues that if $f$ is holomorphic at some point $z = x + iy$, then the real vector field associated with $f$ is differentiable at $(x,y)$. However, I don't quite follow the argument. The relevant passage is below:

At a fixed $z$, let $f'(z) = a + ib$. Let $w = h + ik$, with $h,k$ real. Suppose that
$$
     f(z + w) - f(z) = f'(z) w + \sigma(w) w,
$$
where
$$
     \lim_{w \to 0} \sigma(w) = 0.
$$
Then
$$
      f'(z) w = (a + ib)(h + ik) = ah - bk + i(ak + bh).
$$
On the other hand, let
$$
     F: U \to \mathbb{R}^2
$$
be the map such that
$$
     F(x,y) = \big( u(x,y), v(x,y) \big).
$$
We call $F$ the (real) vector field associated with $f$. Then
$$
    F(x + h, y + k) - F(x,y) = (ah - bk, bh + ak) + \sigma_1(h,k) h + \sigma_2(h,k) k, \hspace{1cm} (1)
$$
where $\sigma_1(h,k), \, \sigma_2(h,k)$ are functions tending to $0$ as $(h,k)$ tends to $0$. Hence if we assume that $f$ is holomorphic, we conclude that $F$ is differentiable in the sense of real variables, and that its derivative is represented by the (Jacobian) matrix
$$
    J_F(x,y) =
    \begin{pmatrix}
          a & -b \\
          b & \phantom{-} a
    \end{pmatrix}
    =
    \begin{pmatrix}
        \dfrac{\partial u}{\partial x} & \dfrac{\partial u}{\partial y} \\[10pt]
        \dfrac{\partial v}{\partial x} & \dfrac{\partial v}{\partial y}
    \end{pmatrix}.
$$

My questions: How was equation (1) obtained? Moreover, if it appears that $\sigma = \sigma_1 + i \sigma_2$, in which case $\sigma_1$ and $\sigma_2$ are real-valued functions. But then in the right-hand side of (1) we are adding the scalar quantity $\sigma_1(h,k) k + \sigma_2(h,k) k$ to the vector $(ah - bk,bh + ak)$...how does that make sense?
Here is my attempt at deducing the differentiability of $F$: We have
\begin{align*}
    F(x,y) &= \Big( \text{Re}\big(f(x + iy) \big), \text{Im} \big(f(x + iy) \big) \Big) \\[5pt]
           &= \big( \text{Re}\big(f(z) \big), \text{Im} \big(f(z) \big) \big)
\end{align*}
and
\begin{align*}
    F(x + h, y + k) &= \Big( \text{Re}\big(f(x + h + i(y+k)) \big), \text{Im} \big(f(x + h + i(y+k)) \big) \Big)  \\[5pt]
    &= \Big( \text{Re} \big(f(z + w) \big), \text{Im}\big(f(z+w) \big) \Big)
\end{align*}
Now using the fact that $\text{Re}(z_1 + z_2) = \text{Re}(z_1) + \text{Re}(z_2)$ and $\text{Im}(z_1 + z_2) = \text{Im}(z_1) + \text{Im}(z_2)$, it follows that
\begin{align*}
    F(x + h, y + k) - F(x,y) &=  \big( \text{Re} \big(f(z + w) \big), \text{Im}\big(f(z+w) \big) \big) - \big( \text{Re}\big(f(z) \big), \text{Im} \big(f(z) \big) \big)  \\[5pt]
    &= \big( \text{Re} \big( f(z + w) - f(z) \big), \text{Im} \big( f(z + w) - f(z) \big) \big).
\end{align*}
Now writing $\sigma(w) = \sigma(h + ik) = \sigma_1(h,k) + i \sigma_2(h,k)$, we have
\begin{align*}
    f(z + w) - f(z) &= f'(z) w + \sigma(w) w \\[3pt]
    &= (a + ib)(h + ik) + \big[\sigma_1(h,k) + i \sigma_2(h,k) \big] (h + ik) \\[3pt]
    &= (ah - bk) + i(ak + bh) + h \sigma_1(h,k) - k \sigma_2(h,k) + i \left[k \sigma_1(h,k) + h \sigma_2(h,k) \right]  \\[3pt]
    &= \big[ ah - bk + h \sigma_1(h,k) - k \sigma_2(h,k) \big] + i \big[ak + bh + k \sigma_1(h,k) + h \sigma_2(h,k)  \big].
\end{align*}
Hence, I get
\begin{align*}
  & F(x + h, y + k) - F(x,y)  \\[3pt]
 = \; &\big( ah - bk + h \sigma_1(h,k) - k \sigma_2(h,k), ak + bh + k \sigma_1(h,k) + h \sigma_2(h,k) \big) \\[5pt]
    = \; & \big(ah - bk, ak + bh \big) + \big( h \sigma_1(h,k) - k \sigma_2(h,k), k \sigma_1(h,k) + h \sigma_2(h,k) \big),
\end{align*}
which is different than what the book has...So does the book have a mistake, or did I make a mistake in my calculation?
Answer: $\sigma_1, \sigma_2$ are not the functions as you defined them in your proof. Let us write
$$\sigma(w) = \sigma(h,k) = \bar \sigma_1(h,k) + i \bar \sigma_2(h,k)$$
with real-valued functions $\bar \sigma_1, \bar \sigma_2$. Then we get
\begin{align*}
  & F(x + h, y + k) - F(x,y)  \\[3pt]
   = \; & \big(ah - bk, ak + bh \big) + \big( h \bar \sigma_1(h,k) - k \bar \sigma_2(h,k), k \bar \sigma_1(h,k) + h \bar \sigma_2(h,k) \big) \\
= \; & \big(ah - bk, ak + bh \big) + \big(\bar \sigma_1(h,k),\bar \sigma_2(h,k)\big)h  + \big(-\bar \sigma_2(h,k), \bar \sigma_1(h,k)\big)k .
\end{align*}
Now take $\sigma_1(h,k) = \big(\bar \sigma_1(h,k),\bar \sigma_2(h,k)$ and $\sigma_2(h,k) = \big(-\bar \sigma_2(h,k), \bar \sigma_1(h,k)\big)$.
These are functions with values in $\mathbb R^2$ tending to $0$ as $(h,k)$ tends to $0$.
Comment: Thank you very much! Would've been nice if the book had properly defined $\sigma_1$ and $\sigma_2$...


Generating URLs with fromUri and the language prefix, base vs internal

Question: What is the recommended way to generate non-route URLs that include the language prefix?
Context: In CiviCRM, an open source third-party project that integrates with Drupal, we have a function that generates internal URLs (a wrapper over the CMS-specific function).
Since not all URLs referenced have a proper route, so far fromUri has given the best results (rather than fromRoute).
However, the URLs generated by fromUri do not seem to include the language prefix for multi-lingual configurations when using base as the prefix. The language prefix is included with internal, but if I understand correctly, internal should only be used for user-specified links, such as a link field.
Example on a site that has English and French, with French being the default language:
print \Drupal\Core\Url::fromUri("base:/admin")->toString() . "\n";
print \Drupal\Core\Url::fromUri("internal:/admin")->toString() . "\n";

$ drush scr test.php
/civicrm/dashboard?reset=1
/fr/civicrm/dashboard?reset=1

I also tried passing in the $language object, but the behaviour is the same:
$language = \Drupal::languageManager()->getCurrentLanguage();

print \Drupal\Core\Url::fromUri("base:/admin", [
  'language' => $language,
])->toString() . "\n";

Related question: Generating arbitrary internal URLs
Comment: Also interestingly, core barely uses `'base:/` by the looks of things; just in tests and a few edge cases. Not really sure what that means exactly though :)
Comment: _internal should only be used for user-specified links, such as a link field_ Do you have a reference for that? The [docs](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AfromInternalUri/8.6.x) don't appear to mention anything in that vein, just that `internal` is for paths relative to the Drupal/Symfony root
Comment: The [fromUri doc](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Url.php/function/Url%3A%3AfromUri/8.7.x) says: "The internal: scheme should be avoided except when processing actual user input that may or may not correspond to a Drupal route."
Comment: Hmm, not sure I agree with that Just do a search for `'internal:/` in core, there's tons of them being used outside of user input
Comment: Interesting, thank you! I'm still curious why the different behaviour, but for now this helps us move forward.
Answer:
Drupa8 - as a Symfony application - abstracts paths with routes. So paths may change, the route stays.
So the cited "The internal: scheme should be avoided except when processing actual user input that may or may not correspond to a Drupal route." means: If you can, use a route.
If you can not use routes, the right prefix for routed paths is internal:.
In contrast, base: was introduced for use cases like README.txt which is unknown to the symfony router and served directly by the web server.

You can find background in these issues, and help improve the docs:

Remove the base: scheme in favour of user-path:/internal: [#2422995] which concluded that we still need the base scheme
Evaluate and document each use of base: in core [#2417827] which then was started to at least document usages of the base scheme
Url::fromUri DocBlock does not mention base: and internal: custom schemes [#2877023] which is about improving the docs
Comment: I've recently seen that Url::fromUri will not add the currently set language if the path is not defined. Here is an example: https://git.drupalcode.org/project/h5p/-/blob/2.0.0/modules/h5peditor/src/H5PEditor/H5PEditorUtilities.php#L141

Is that a bug or feature?


JS Replacing part of a version number within a file

Question: I need to replace the version number in a file via JS and I'm having trouble targeting only the specific part that I need. I've read the contents of the file into a variable and will overwrite the entire file with the modified content. The file looks like this (standard wordpress style.css):
/******************************************************************
Theme Name: Starter Theme
Theme URI:
Description: Custom Wordpress starter theme
Author:
Author URI:
Version: 1.0.0
Tags: fluid-layout, responsive-layout, translation-ready

License: WTFPL
License URI: http://sam.zoy.org/wtfpl/
------------------------------------------------------------------*/

.sticky {}          /* DO NOT EDIT THIS */
.gallery-caption {} /* THESE ARE USELESS */
.bypostauthor {}    /* THEY ARE ONLY TO KEEP THEME CHECK HAPPY */

And the part in question is this Version: 1.0.0
There's a few nuances that seem to make this difficult. I only need to change the third number (0), as the first two (1.0) are reserved for manual editing and need to be kept the way they are (so I cannot just replace the whole string or line). I've been trying to extract only the last number via substring and/or regex but can't seem to figure out how to do that properly (as the content around it isn't static, plus the version string ends with a newline). Any help would be greatly appreciated.
Answer: Enumerate through each line using readline / a for loop depending upon browser/nodejs and and look for string version, change the number accordingly.
Comment: That's basically what I'm doing, but I'm having trouble targeting only the last number within the version string and replacing that specifically.
Comment: You could take the whole line of version as string and split them by . Str.split('.'). Replace the last element by the desired number and join again. No regex trouble that way.
Answer: let newVersion = 3;
content = content.replace(/^Version: \d+\.\d+\.\d+$/mg, function(match, index) {
    return match.replace(/\.\d+$/, '.' + newVersion);
});

Comment: It seems to lose the dot before the last number, but other than that this is EXACTLY what I was looking for! Thank you so much!
Comment: yeah, forgot about the dot :) now is ok


Am I specifying my lmer model correctly?

Question: I've scoured Google and this site and I am still confused about the lmer function in the lme4 library.
I have some data collected from different psychiatric wards, which have a multilevel structure. To simplify, I'll pick two level 2 and two level 1 variables, although I actually have a few more.
Level 2- WardSize [this is the number of people on the ward] & WAS [this is a measure of how "nice" the ward is]
The grouping variable that tells R who's in which ward is called "Ward"
Level one- Gender [this is gender, obviously] & BSITotal [this is a measure of symptom severity]
Outcome is Selfreject, which again is what it sounds like.
I have this formula:
help=lmer(formula=Selfreject~WardSize+WAS+Gender+BSITotal+(1|Ward))
I'm hoping this means "each individual has a score related to their own Gender and symptom severity, and also a ward-level effect relating to the size of the ward and how "nice" it is"
Is this correct? The thing that's confusing me is that I can't see how R can tell which are level 1 and which level 2 variables, except for the ward level intercept given at the end.
If anyone could explain the notation so an idiot like me can understand that would be even better.
Many thanks!
Answer: Your model specification is fine.
The varying intercept for Ward, specified in lmer as you've done with (1 | Ward), is saying that subjects within each ward might be more similar to each other on Selfreject for reasons other than WardSize or Gender, so  you are controlling for between-ward heterogeneity.
You can think of the "1" as a column of 1s (i.e., a constant) in the data to which an intercept is fit. Usually the "1" is implied automatically in lm, for instance
lm(Y ~ X1 + X2)

actually specifies
lm(Y ~ 1 + X1 + X2)

Now that you have your basic model, you can start asking further questions like "Does the relationship between BSItotal and Selfreject differ between wards?"
lmer(formula=Selfreject ~ WardSize + WAS + Gender + BSITotal + (1 + BSITotal | Ward))

That is, both the intercept and the slope of BSITotal can differ between wards.
If you haven't picked it up yet, Gelman & Hill's Data Analysis Using Regression and Multilevel Model/Hierarchical Models is a great book that explains fitting models like this with lmer.
Answer: Here is a link to an explanation by Douglas Bates (who wrote lme4) as to why it's not necessary to specify the level for fixed effects.
Comment: Welcome to the site, @Breyer. I suspect this is a helpful contribution. Would you mind giving a brief summary of the argument there, so readers can decide if it's what they're looking for, or in case of future linkrot?
Comment: Thanks for the welcome @gung. Sure, Bates explains that it's not necessary to specify levels for fixed effects because the lme4 package is written for mixed models, including but not limited to multilevel/hierarchical models. This means the computational methods do not rely on the specification of levels, as is the case for specialized multilevel regression software (HLM etc) that leverage the nested data structure in computation.


Regex para aspas simples

Question: Gostaria de remover as aspas simples no meio de um texto, ignorando as do inicio e fim, se caso existir.

1º Caso: 'Texto e pala'vras' = 'Texto e palavras'
2º Caso: Texto e pala'vras = Texto e palavras
Comment: Realmente precisa de uma regex? `str_replace()` não resolve o problema?
Comment: não posso substituir todas, tenho que preservar as aspas simples do inicio e do fim.
Answer: Você pode usar a regex (?<!^)'(?!$).
A sintaxe (?<! determina um lookbehind negativo, ou seja, ele verifica se algo não existe antes da posição atual. Dentro deste lookbehind temos o marcador ^, que significa "início da string".
Em seguida temos o próprio caractere '.
Logo depois temos (?!, que determina um lookahead negativo. De forma similar ao lookbehind, ele verifica se algo não existe depois da posição atual. Dentro dele temos o marcador $, que significa "final da string".
Ou seja, a regex pega todos os caracteres ' (aspas simples), desde que não estejam no início ou no final da string. Assim, podemos usar esta regex na função preg_replace (lembrando de escapar o caractere ' com \):
$texto = '\'Texto e pala\'vras\'';
$texto = preg_replace('/(?<!^)\'(?!$)/', '', $texto);
echo $texto;

O preg_replace substitui todas estas aspas por uma string vazia (ou seja, na prática estas aspas são removidas da string). O resultado é 'Texto e palavras'.
Comment: Era tudo que eu precisava.
Não sabia que dava para usar o lookahead dessa forma.
Muito obrigado.
Answer: Pode resolver esse problema alternativamente com str_replace() e substr(). Primeiro são removidas todas as aspas simples, depois é feita uma checagem com substr() se o primeiro e o último caracteres são aspas simples e no final printf/sprintf() monta o template final.

function removerAspas($str){
    $str = trim($str);
    $aspaInicio  = substr($str, 0, 1) == "'" ? "'" : '';
    $aspaFim = substr($str, -1, 1)  == "'" ? "'" : '';
    $strLimpa = str_replace("'", '', $str);

    return sprintf("%s%s%s", $aspaInicio, $strLimpa, $aspaFim);
}

echo removerAspas("'Texto e pala'vras'") .PHP_EOL;
echo removerAspas("Texto e pala'vras#'") .PHP_EOL;
echo removerAspas("'#Texto e pala'vras") .PHP_EOL;
echo removerAspas("Te'x'to' 'e' pala'vras") .PHP_EOL;

Exemplo - ideone

Regex para aspas simples


How can I restore removed menu items?

Question: I create a menu "XXXX" move "Create content" and all of it's children to "XXXX" then remove XXXX menu. now I miss "Create content", how can I restore them?
Comment: I have updated my answer. The code is now more generic, and it should work in more cases. Keep in mind what I reported in my answer: The code could catch the wrong row, if there are more rows with a link path equal to node/add. It excludes the row added by the Shortcut module, but not similar rows added from other modules.
Answer: You can execute the following query.
if ($mlid = db_query("SELECT mlid from {menu_links} WHERE link_path = :path AND menu_name NOT LIKE :menu", array(':path' => 'node/add', ':menu' => db_like('shortcut-set-') . '%'))->fetchField()) {
  db_update('menu_links')
    ->fields(array('menu_name' => 'navigation', 'plid' => 0))
    ->condition('mlid', $mlid)
    ->execute();
  db_update('menu_links')
    ->fields(array('menu_name' => 'navigation', 'plid' => $mlid))
    ->condition('link_path', db_like('node/add/') . '%', 'LIKE')
    ->condition('menu_name', db_like('shortcut-set-') . '%', 'NOT LIKE')
    ->execute();
}
else {
  // There isn't any row for node/add.
}

What the code does is the following.

It finds the database row where the link path is node/add, and where the menu name doesn't start with shortcut-set-, which is the menu name used from the Shortcut module for its shortcut sets; as the default shortcut set used from that module contains a link that points to node/add, the code exclude that link. If there are other rows that would point to node/add, you need to edit the first query to exclude them.
For the row found from the first query, it changes the menu name to navigation, and plid (the parent link ID) to 0.
For any row whose link path matches the SQL regular expression node/add/%, it sets plid to the mlid previously found.

In the code I used db_like(), even in this case was not strictly necessary. The purpose of db_like() is escaping any character that for the SQL regular expressions has a specific meaning. Suppose that I would change the code to find any database row whose link path is node/%, where % is the character that is really present in the link path; without db_like(), the query would find any row where the link path starts with node/, which would include more rows than the ones where the link path is node/%.
As the code is using two update queries, it should use transactions. In that way, if the second query would fail, the database would be left in a consistent state, which means that the rows for node/add, and node/add/[content type] will be part of the same menu. If the first query is executed, and the second one fails, you would have node/add that is part of a menu, while any node/add/[content type] link would be part of a different menu (or some of the node/add/[content type] links will be part of a menu, and other node/add/[content type] links will part of another menu).
if ($mlid = db_query("SELECT mlid from {menu_links} WHERE link_path = :path AND menu_name NOT LIKE :menu", array(':path' => 'node/add', ':menu' => db_like('shortcut-set-') . '%'))->fetchField()) {
  $transaction = db_transaction();
  try {
    db_update('menu_links')
      ->fields(array('menu_name' => 'navigation', 'plid' => 0))
      ->condition('mlid', $mlid)
      ->execute();
    db_update('menu_links')
      ->fields(array('menu_name' => 'navigation', 'plid' => $mlid))
      ->condition('link_path', db_like('node/add/') . '%', 'LIKE')
      ->condition('menu_name', db_like('shortcut-set-') . '%', 'NOT LIKE')
      ->execute();
  }
  catch(Exception $e) {
    // One of the queries failed; rollback the database to the previous status.
    $transaction->rollback();
  }
}
else {
  // There isn't any row for node/add.
}

PS: As the only way to find the menu item is too look for its link path, there could be more than one row using that link path. It is important the code excludes those rows that are not the correct one, and that is what my code does when it excludes the rows there the menu name starts with shortcut-set-. Unfortunately, it is not possible to write code that generic enough to work in any condition.

How can I restore removed menu items?


Optimization of java code for reducing complexity

Question: I am actually new to java libraries. I dont know what this code is doing.
I have been given a task to optimize this. Any help will be useful.
I mean to ask whether str.equals(local) checks for entire string aur for particular index value in the for loop.
public void fnc(String str, int[] ar1)
    {
        String local = "findnumber";
        for(int i=0; i<ar1.length; i++)
        {
            if(str.equals(local) && ar1[i] * 2 > 10)
            {
                Integer ip = new Integer(ar1[i]);
                ip = ip * 2;
                System.out.print(ip.toString());
            }
        }
    }

Comment: Like if I asked you "What do you mean by a cat?  A feline or a piece of earthmoving equipment?"  ... and you answered "I mean the whole cat".
Comment: `if(str.equals("findnumber")) for(int i: ar1) { i*=2; if(i>10) System.out.print(i); }`
Comment: There is no need to do the multiplication twice. Since its result is needed for the comparison, you have to do it before the comparison. You can call `toString()` on an object only (like an `Integer` instance), but that's obsolete here, as [`print(int)`](https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html#print-int-) will already do the intended action.
Comment: Please show your attempts. There's lots of easy things to improve in here, but there's little learning advantage for you in just telling you the answer.
Comment: What do you mean by complexity?  Computational complexity of the algorithm?  Complexity in terms of humans reading / understanding the code?
Comment: "whether str.equals(local) checks for entire string aur for particular index value" Nope, it just checks whether `str` equals `local`. Nothing to do with the loop index.
Comment: complexity of the algorithm as a whole @StephenC
Comment: @AndyTurner i have placed the **str.equals(local)** condition above the loop body.
Comment: do you think  replacing
`ip = ip * 2;
 System.out.print(ip.toString());`
with
`System.out.print(ip * 2.toString());`
 will be useful??
Comment: *"complexity of the algorithm as a whole"* - that does NOT answer my question.  The question was ... what do you mean by complexity.  Your answer is "circular".
Answer: The big O complexity of the algorithm is O(N) where N is the array size.  You cannot improve on that ... for the arguments provided and producing the same output.
There are some things that can be done to improve efficiency though.

Hint: look for a computation that is performed on each loop iteration that could be performed once.
Hint: look for some unnecessary object creation1
Hint: unnecessary use of a reference type.

There are one or two other questionable micro-optimizations, but see if you can spot them without any hints.  (I say "questionable" because I suspect that the JIT compiler would do the same optimization itself.)
One final note: the actual speed of the code will be dominated by the print statement, and its ability of the OS to write stuff to (for example) the console.   And probably by JVM startup / warmup effects ... unless the fnc method is called many times.

1 - Notwithstanding anything else, new Integer(...) is the wrong way to convert an int to an Integer.
Comment: @Stephen C: [Escape analysis is supported and enabled by default in Java SE 6u23 and later](http://docs.oracle.com/javase/7/docs/technotes/guides/vm/performance-enhancements-7.html#escapeAnalysis)…
Comment: @Stephen C: it does, if Escape Analysis can prove its pure local nature, which is the case here. Of course, using `Integer.valueOf` (or just autoboxing) to denote the irrelevance of the object identity explicitly is still better. However, as you already stated, the printing operation will dominate the speed, so it may be the case that the JIT doesn't look at this loop…
Comment: Everything you can do with this simple loop falls into the micro-optimization category of that "the JIT can do that" sort. As long as they are also removing unnecessary repetition or obsolete processing steps, in other words, also remove visual clutter from the source code, there is nothing wrong with that. Micro-optimization is bad only, when the code readability suffers from it or too many development time is spent on it…
Comment: @Sandeep - No.  It is converting an `int` to an `Integer`,  But do you need to convert to an `Integer`?
Comment: @Sandeep - that is not relevant.  You can tell what the type of `arr` is from the method signature!
Comment: can i ask though what does
`Integer ip = new Integer(ar1[i]);`
doing here is it converting an integer element to integer again.
Comment: @Holger - If you explicitly `new` an object, it is doubtful that the JIT compiler will optimize that away.
Comment: @Holger - yes, but is escape analysis enabled by default?  I thought not .....
Comment: @StephenC I was given only these lines of code with task of optimization. I don't know what actually this function is used for
Comment: @StephenC @Holger thank you, the answer was helpful.. Specially the conversion of `int`to `Integer`
Comment: @StephenC how can one tell `arr` from method signature.. sorry if that too basic question
Comment: @Holger - didn't know that.  But even so, it is unclear that the JIT can figure out that the code can be rewritten to use an `int`.  The transformation entails replacing non-static `Integer.toString()` with static `Integer.toString(int)`.  That's a big ask for a non-sentient optimizer.
Comment: @Sandeep - sorry `ar1`.  But the answer is **by reading it**.  What is the type of `ar1`?  What does the method declaration say?  And what does that mean the type of `ar1[i]` is???
Comment: @StephenC the method is performing very simple task of checking whether input string to method is "findnumber" if it is than print those element of array which when multiplied by 2 is greater than 10. The question is isn't converting `int`to `Integer` irrelevant
Comment: But the CODE >>is<< converting an `int` to an `Integer`.  And converting an `int` to an `Integer` when you don't need to is something that can be optimized!!   So it is totally relevant.
Comment: But I'm not going to spend any more time of this.  You have had enough of my time.
Comment: so i can actually remove the line `Integer ip = new Integer(ar1[i]);` and directly write  System.out.print(ar1[i]*2);   it will be fine know??
Comment: @StephenC THANK YOU really
Comment: @Holger escape analysis is just that - *analysis* of the scope of an object. After it, there could be many things happening like *biased-locking*, *scalar replacement*. The thing is this has to hit `C2` compiler to be even analyzed with escape analysis and that `might` not happen at all.
Comment: @Eugene: that's what I already said, [the printing operation will dominate the speed, so it may be the case that the JIT doesn't look at this loop](https://stackoverflow.com/questions/44629876/optimization-of-java-code-for-reducing-complexity/44630095?noredirect=1#comment76246291_44630095)…
Comment: @Holger I don't know why but I sort of thought your hint was something like, don't worry about it - the JIT will take care; from the first comment. I guess that was not your intention...


Can I update PowerShell / WinRM / WinMF via command line?

Question: Taking a new Windows Server 2012 installation, I need to get it fit for hosting and automation.
That means getting it ready for remote PowerShell and DSC, which means installing the latest version of the Windows Management Framework, and then configuring WinRM for HTTPS and Basic Authentication.
I've not really 'engineered' Windows since 2008, but it seems that solving this egg-chicken problem requires a mouse and a browser.
And yet a couple of non-GUI footprints of Windows Server exist today, so what's the quick solution to getting these basics setup (at a command line) so that I can move on to automating the more advanced configuration of the host?
It kinda strikes me that there should be a single CmdLet in-the-box to get this fundamental stuff up and going.
Is there?
Comment: "Is there?" No, there is not a magic 'do what I mean' cmdlet.
Comment: As a programmer building apps for major global brands, we identify common use-cases, user journeys, and build easy-to-use experiences for our customers, like Apple did with the iPhone and took over the world. Microsoft has half-done this with `winrm quickconfig` so its not too far a leap to think that there might be a few simple steps to get this basic, basic stuff going. And I wasn't far off, see my answer.
Comment: @LukePuplett this is true, but realize the iPhone is a consumer facing device. The 'shell' of a server is not, nor should it be, consumer facing, it doesn't matter if it's Windows or Linux, there's no 'flip switch and it's working' cmdlet or script unless a sysadmin decides to make one. You're a programmer, you should probably leave server setup to a sysadmin, and don't assume 'anybody can do it'. Assuming there is a common use case from one server to the next is extremely dangerous, because there isn't. Even if there was, who's to say testing PS DSC scripts would fall in that category?
Comment: So I'm not a consumer of Windows? Okay mate. And look at my LinkedIn profile. I was Windows PSS engineer for Microsoft and then spent 7 years engineering award winning automation systems for a bank with 30,000 servers. Don't come on SO and tell me what I can and cannot touch. Because I think in terms of use-cases and useability, I became a software developer, because I have empathy for humans experiencing a product. Windows sucks in this respect. I also started the Unofficial Windows Uservoice that became official and is now the feedback tool in Windows 10.
Answer: I actually gave up. Here's how far I got. From PowerShell:
PS> iwr https://chocolatey.org/install.ps1 -UseBasicParsing | iex
PS> choco install powershell

Reboot.
From elevated Command Prompt:
> winrm quickconfig
> winrm set winrm/config/service/auth @{Basic="true"}
> winrm set winrm/config/service @{AllowUnencrypted="false"}

And then I realised I'd need to make a certificate somehow and that would require makecert and that would require automating the installation of the Windows SDK, then I'd have to install the certificate, and some other documentation said something about WinRM not working with self-signed certificates and then thinking that after spending a week getting all that working only to discover that WinRM won't work anyway and then I lost the will to live.
I'm a programmer. I wanted to have a development Windows Server box for testing some PS DSC scripts out on but don't have an installation key to install it locally in Hyper-V and Microsoft haven't figured out to just give Windows Server away for free for developers yet, so I thought I'd use my free Azure time and setup a free VM and just use that over the web, but that requires HTTPS and so we're back to the problems above.
Hopefully my contract won't be renewed and I can just use .NET Core and Linux and Docker on the next job.
Edit
Stumbled randomly across this gem of a post about setting up SSL but without makecert:
https://4sysops.com/archives/powershell-remoting-over-https-with-a-self-signed-ssl-certificate/
Comment: Well, for home use, ServerFault isn't the appropriate venue for the question, sorry to say. It's in the FAQ.
Comment: You know you can download a free eval copy of Windows Server which is good for either 90 or 120 days?
Comment: I tried, the form goes round and round in circles, and its no good long term anyway.
Comment: Before anyone else downvotes, the first two commands answer the headline question.
Comment: FYI, in a standard enterprise environment with AD, using Windows Certificate Services, a PKI, and/or GPOs will help handle this. I don't know if that's an option for you in your planned hosting environment.
Comment: Thanks. It's fine at work, which is why I gave up, because I may as well get the ops guys to sort it, but for home and using disposable dev VMs on Azure, or for a startup where AD and big enterprise Windows environment is costly and superfluous, there's too much friction compared to lighter, alternative stacks.
Comment: "Anything in a home or development environment" -- Wha?! I can't even...
Comment: There's a good history of reasons for that, and if you'd like to discuss it, that's what the Meta sites are for.


Load jQuery after DOM, how can I make $.ready() available to my page before jQuery is loaded?

Question: I want to late load jQuery, but I have a small amount of inline javascript the runs on $.ready().  Since jQuery isn't loaded, these lines throw an error and never run.  Is there a way I can make $.ready() an available function, but wait on execution until jQuery is loaded?
Thanks!
Comment: Replace ready with a function call, create a function and put that function inside $.ready()
Comment: Is this useful? http://stackoverflow.com/questions/1828237/check-if-jquery-has-been-loaded-then-load-it-if-false
Answer: One option for a generic way to solve this is to put your inline javascript in a function and add that function to a globally accessible array - don't call it yet.  These are essentially functions that you want to schedule for document.ready() when document.ready is available.
Then, when you do load jQuery, you set up a document.ready() handler that cycles through all the functions in that array and calls them.
// declare global at the top of your web page
var readyFns = [];

// in your inline code, add a function to the readyFns array
readyFns.push(myInlineFn);

// when your jQuery code loads, do this:
$(document).ready(function() {
    for (var i = 0; i < readyFns.length; i++) {
        readyFns[i]();
    }
});

If you want to use anonymous functions, you can do the middle step like this:
// in your inline code, add a function to the readyFns array
readyFns.push(function() {
   // put your code here
});

Comment: @Beachhouse - I added anonymous functions to my answer.
Comment: I like this, I think it'll work.  But is there a way to do this with anonymous functions like jquery does? readyFns.push(function() { }); perhaps?
Answer: Instead of using .ready, you could use the non-jQuery equivalent such as window.onload, but these tend to be somewhat incompatible with .ready, so I'm not sure if they will work for your needs.
Someone apparently has extracted jQuery's ready function so it can be used alone: http://code.google.com/p/domready/
Comment: +1 domready could be what I'm looking for, but the code looks like there's a bit of overhead in there to do this.
Answer: You should:

replace ready with a function call e.g. example();
create a function e.g. example() { }
put that function inside (document).ready()
Comment: Very very simple answer, but I need to check as to how this would work.  I have more than one ready block that loads before the DOM, I think this would limit me to one usage.


For every ring R, every left R-module M can be imbedded as a submodule of an injective left R-module

Question: Prove that for every ring $R$, every left $R$-module $M$ can be imbedded as a submodule of an injective left $R$-module
Comment: page 197 of [Hungerford](https://books.google.com/books?id=t6N_tOQhafoC&pg=PA194&lpg=PA194&dq=hungerford+algebra+Every+unitary+module+A+over+a+ring+R+with+identity+may+he+++embedded+in+an+injective+K-module.&source=bl&ots=cSN7kvU6Wh&sig=o_DgA2AiXjqbcvuJIuN-EeVrk0w&hl=en&sa=X&ved=0ahUKEwipsbKclJvMAhWB1iwKHTgsB-UQ6AEIHjAA#v=onepage&q&f=false)
Answer: There is a standard dualization trick : for any $R$-module $A$, write $A^* = Hom_\mathbb{Z}(A,\mathbb{Q}/\mathbb{Z})$, which is a $R$-module. This gives a contravariant functor from the category of $R$-modules to itself.
Then write $A^*$ as quotient of a free module : $\bigoplus_{i\in I} R \to A^*\to 0$. Dualizing : $0\to A^{**}\to \prod_{i\in I} R^*$ (this is exact because $\mathbb{Q}/\mathbb{Z}$ is an injective $\mathbb{Z}$-module, since it's divisible).
Now $R^*$ is injective (because $Hom_\mathbb{Z}(R,\bullet)$ has a left adjoint and $\mathbb{Q}/\mathbb{Z}$ is injective, so it's sent to an injective object), so $\prod_{i\in I} R^*$ is injective.
We conclude by the fact that the canonical $A\to A^{**}$ given by $a\mapsto ev_a$ (the evaluation map at $a$) is injective, so $A\to A^{**}\to \prod_{i\in I} R^*$ is an injective morphism to an injective $R$-module.


Include backend name/ip in response headers in haproxy

Question: I am stuffing haproxy in front of 3 riak nodes with HTTP. I want the backend name and/or ip in the response headers. Something like:
X-Proxy-Backend: riak-1 10.0.0.1

or whatever.
How can I make this happen?
Comment: This works for me: https://stackoverflow.com/a/43106728/843804
Answer: You can use the cookie function to add the serverid into your response. For example:
cookie SERVERID insert indirect
server webA 192.168.1.11:80 cookie A check

This will insert a cookie called SERVERID=A into the HTTP headers.
Answer: If you want a header, you can use the srv_id ACL like so:
rspadd X-Backend-Server:\ server1 if { srv_id 1 }
rspadd X-Backend-Server:\ server2 if { srv_id 2 }

You'll have to keep it in sync when you add/remove backend servers, but it works.


simple PHP echo not working

Question: I am trying to learn basics of php.So I tried following example as in http://www.w3schools.com/
<!DOCTYPE html>

A Header

<?php
echo "My first PHP script!";
?>

This code was working two days ago. But now PHP part doesn't work.I have read this thread,but It is not that problem. Please help. Thank you.
Comment: What does "PHP part doesn't work" mean? Do you see the PHP tags in the HTML source or nothing at all?
Comment: also, I suggest using a better resource to learn PHP than w3schools; there are many places on the web that will give you better advice.
Comment: Yeah, that's not going to work. You need a web server.
Comment: are you running it via a web server with PHP enabled?
Comment: you need to install xampp or wamp or lamp in your machine...
Comment: There are too many possible causes for this. Please **add details to narrow the answer set or to isolate an issue** that can be answered in a few paragraphs.
Comment: I am simply running it on browser from local hard drive.
Comment: You can't run a server side language (php) without a server to interpret the server side commands. In bare basic terms, the browser only reads out the text sent to it from the server.
Comment: Possibly your wamp server has not completely started is the icon in green colour for wamp server
Answer: Make sure that your web-server can execute php-scripts. Go through this: http://php.net/manual/en/install.php
Comment: I tried (http://www.php.net/manual/en/tutorial.firstpage.php) tutorial  too it prints only **Hello World
'; ?>**
Comment: Giv the code you tried
Comment:

PHP Test

Hello World'; ?>

Answer: I recommend you start learning PHP using this website http://www.developphp.com/list_php.php#Getting_Started_with_PHP_Programming it has everything you need to get you started, tutorials are nice and easy to follow :)
Check the Installation section and then maybe have a look at this one http://www.developphp.com/view_lesson.php?v=194 to solve your problem.
Hope it helps!- Good Luck!

simple PHP echo not working


Probability of observing the same value for 10th percentile in two different samples

Question: Edited:
I have a categorical variable comprising of values from 1 to 7 with these probability:
<code>score   1        2       3      4       5       6   7
p       0.01    0.01    0.03    0.05    0.2   0.3   0.4
</code>
In two different samples from the two different populations, I found the same value for 10th percentile (i.e. 4) in observed data. I want to find the likelihood of having exactly the same value for 10th percentile.
FYI, the scores are answers to a scale and probabilities are proportions for each category in a normative sample.I want to be able to do this in R.
P.S.: any suggestion on calculating cumulative distribution of a variable with above-mentioned properties is appreciated.
Thanks.
Comment: Do you mean 'at least 10%', 'at most 10%' or 'exactly 10%'?
Comment: @Glen_b I meant exactly 10% but would be happy to learn other possibilities like 'at least 10%' and 'at most 10%'.
Comment: The proportion of times that exactly 1000 observations out of 10000 fall below 4 will be quite small (it's actually possible to compute this number, there's no need to simulate it).
Comment: @Glen_b The reason is that in a survey from two different samples from two different populations I found the same value for 10th percentile. I want to know how likely is to find the same value for 10th percentile in a variable.This is why I thought that a simulation would be proper.
Comment: Finding the same value for the 10th percentile is rather different from what you're asking about.
Comment: @Glen_b Actually I wasn't sure if I'm using the right term or not. Those probabilities are observed proportions in normative sample so I thought of using them as probabilities for observed values in samples.
Comment: Note that your first line (1-5) doesn't fit your table (1-7). To answer the original question as worded (take care with the phrasing of 'below 4'), you can evaluate the probability as `dbinom(1000,10000,.05)`. If you want to simulate it, you could use `rbinom`. Perhaps you could explain the original problem in more detail in your question.
Comment: @Glen_b Thanks.I just edited the question.I'm not sure if we can use Binomial distribution for this data as the scores are for a variable with 7 categories. I also want to use those probabilites in my calculation.
Comment: The question you're answering is binomial, since an observation either falls in the required region or it doesn't.
Comment: Are you sure you're asking the right question? Since you picked the value 4 only after seeing the data, wouldn't it be more appropriate to ask about the probability that the two cumulative distributions would be the same at one or more of the the first six score values? And wouldn't it be even more appropriate to ask about the probability that *some* such easily-noticeable feature of the two distributions would be the same?
Comment: @RayKoopman As I said to Glen_b, I'm not pretty sure about terminology. Your point could be also true about cumulative distributions but when the 10th percentile of two cumulative distribution is the same does it mean that the two cumulative distribution are the same?
Comment: @Glen_b Is there anyway to accommodate those probabilities and generate cumulative distribution?
Comment: See https://stats.stackexchange.com/questions/182442/probability-of-getting-the-exact-same-letters-in-scrabble-2-turns-in-a-row
Answer: I think this problem is intractable. This is because you noticed something odd and then want to find how likely it is. But you could have noticed anything else odd that happened. Thus, this is a problem of finding how likely a coincidence is, given that one happened.
However, if you want to pursue this further, Persi Diaconis has done some work on this, e.g. Methods for Studying Coincidences
Comment: It can be seen from this perspective as well. Indeed this coincidence given the fact that the two samples and population are different was surprising for me.
Comment: The link is dead, can you replace it?


gitlab runner use SSH instead of http

Question: I have a self-hosted instance of gitlab, and a container in proxmox (Linux runner 5.4.203-1-pve #1 SMP PVE 5.4.203-1 x86_64 x86_64 x86_64 GNU/Linux) I'd like to use as runner.
The self-hosted instance has disabled https acces to repositories (only ssh is allowed).
My pipeline fails with
Fetching changes with git depth set to 20...
Reinitialized existing Git repository in /home/gitlab-runner/builds/gryU5_uD/0/path/to/repo/.git/
remote: HTTP Basic: Access denied. The provided password or token is incorrect or your account has 2FA enabled and you must use a personal access token instead of a password. See http://gitlab.company.cz/help/topics/git/troubleshooting_git#error-on-git-fetch-http-basic-access-denied
fatal: Authentication failed for 'http://gitlab.company.cz/path/to/repo.git/'

The runner was created following the gitlab manual (in runneers->add runner).
Now this answer Gitlab Build Runner on Windows uses HTTP instead of SSH suggest I create a new user for the runner if I understand correctly (and add the ssh key to this user). I hope there is another solution.
EDIT:
-> add
[[runners]]
...
  clone_url = "ssh://firstname.lastname@example.com"
...

to /etc/gitlab-runner/config.toml, add the public key of the system as deploy key (and authorise it for the repo), create ~/.ssh/config with contents
Host gitlab.company.cz
  Preferredauthentications publickey
  IdentityFile ~/.ssh/id_rsa
  StrictHostKeyChecking no

and I can manually clone the repo to the server. The pipeline still fails on permissions though... perhaps i am logged as root and I need to set this logged as user "gitlab-runner"? How do I achieve that?
Current pipeline output:
Getting source from Git repository
00:00
Fetching changes with git depth set to 20...
Initialized empty Git repository in /home/gitlab-runner/builds/gryU5_uD/0/path/to/repo/.git/
Created fresh repository.
Host key verification failed.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

Edit2:
Right, so of course the deploy key is useless. What you need to do is to edit the .ssh/config for the gitlab-runner user.
Answer: As i mentioned in the edits, the working way is to add the settings
Host gitlab.company.cz
  Preferredauthentications publickey
  IdentityFile ~/.ssh/id_rsa
  StrictHostKeyChecking no

to the /home/gitlab-runner/.ssh/config

gitlab runner use SSH instead of http


Any resource/codes on how fiddler works?

Question: I need to track http/url requests & redirects from a windows forms application using C#. It should handle both IE & firefox. Not sure if Fiddler is open-source but if i'm not mistaken, it's written using .NET. Sample codes or online articles on how to listen to http/url requests & redirects will be appreciated.
Thanks!
Comment: Hi Leon, could you mark the relevant answer as accepted?
Answer: Fiddler works as standard HTTP proxy. There is no magic here. See HTTP protocol for details. In both IE/Firefox, you need to set Fiddler (or your custom program) as proxy, and then browser will use it for all outgoing requests. Proxy is responsible for forwarding request to correct server, and returning response. Proxies are typically used for 1) caching, 2) controlling access (and avoiding firewalls), 3) debugging.
See also Open Source Proxy Library for .Net for .NET proxy library (just quick googling... I have no experience with it).
Comment: is there any information out there that I can use to build my own HTTP proxy like `fiddler`?where to start? do I have to write it in c++?
Answer: You'd probably be interested in the new FiddlerCore library: http://fiddler.wikidot.com/fiddlercore


Earliest-*known* use of a double leading tone cadence?

Question: Background
For those who do not know, the double leading tone cadence was perhaps the single defining characteristic of Ars Nova.  Earlier music styles used much simpler cadences (movement by 3rds, 4ths and 5ths was very common).  Ars Nova was arguably the first style of music to popularize resolving to the tonic by a half-tone.
Because triadic music had not yet been invented during this period, it doesn't make much sense to analyze the cadence using any modern notational system.  However, for a song in the key of C, it is reasonable to represent the cadence as Bm/D | C5.  Other variants of the cadence may exist, but this is the one I am most interested in.
Question
When is the earliest-known use of a double leading tone cadence?
Scholarly consensus seems to indicate that Ars Nova began somewhere roughly around 1300 to 1320, which means I can probably rule out any song composed earlier than the 14th century.
Here are three possible contenders to the claim:

Guillaume de Machaut - He is well-known for penning Messe de Nostre Dame, which does indeed contain a double leading tone cadence, and is probably one of his earlier works.  We cannot say for certain though.
Francesco Landini - Born 25 years later than Machaut, so this puts him at an immediate disadvantage.  He is included however because his use of the cadence appears to be much more prominent than Machaut's.  This may indicate that he has more familiarity with the cadence, which lends to an (unlikely) theory that he may have penned some earlier compositions which were lost to time.
The composer(s) for Roman de Fauvel - Since it can be dated as early as 1310 AD, this would likely predate any compositions by Machaut (and Landini for sure).  However, I cannot find any references indicating whether or not the songs make use of double leading tone cadences.  Perhaps someone with a better ear than me can verify?
Answer: The double leading-tone cadence is certainly not the "single defining characteristic" of Ars Nova.
As to the chronology, Philippe de Vitry (born before Machaut, and one of the "inventors" of Ars Nova, to whom the eponymous treatise "ars nova" is ascribed) used double leading-tones in his isorhythmic motets. See, for example, the end of Tuba sacrae/In arboris/Virgo Sum.
However, double leading-tones were in use even before Ars Nova. You would have to go through the repertoire or secondary literature carefully to find the earliest instance. But as an example from the 13th century, see the end of the motet L'autre jour/Au tens pascour/In seculum from the Bamberg Codex. (It's an example in Taruskin's Oxford History of Western Music, Vol. 1, p. 222-224). On the other hand, this example has E and B (musica recta found on the F-Lydian scale) as leading-tones, so it doesn't count if you only consider subsemitonia which are "sharpened" by way of music ficta as leading-tones.
Incidentally, double leading-tones in cadences with suspension (the ones that sound most striking to modern ears) appear a lot later.
Comment: Wow, it appears it was wrong on multiple counts - thanks for clearing this up!  Most of the background in my question was learned through talking with others, but clearly I should get into the books a little more


What is a graph contraction?

Question: The following is a homework assignment:

Let $B$ be the set of bridges of a connected graph $G$. If $G'$ is obtained from $G$ by contracting each connected component of $G − B$ to a vertex, then $G'$ is a tree whose edges correspond to the edges in $B$.

My problem is that I'm not sure that they mean by "contracting each connected component of $G-B$ to a vertex". What do they mean by contracting?
Comment: Replace each connected component of $G-B$ by a single vertex.
Answer: Given a subset $S\subset V$ of vertices of $G$, the contraction of $S$ to a vertex $v$ in $G$ is a graph $G'$ with vertex set $(V\setminus S)\cup\{v\}$ and who has all of the edges of $G$ whose ends are both in $V\setminus S$ and also an edge from $v$ to $u$ for all edges of $G$ with one end in $S$ and the other in $u\in V\setminus S$.  (Sometimes, people add a loop of $v$ for every edge with both ends in $S$, but it is clear from context that this is not the case here.)
TL:DR - you replace all of the vertices that you are contracting with a single vertex and keep all of the connections to the rest of the graph.  In your case, you are contracting many subsets at the same time, but it shouldn't be a difficulty to see how that works.
Your proof will be shorter than this post. ^_^
Comment: But if we contract each connected component to a vertex than this vertex is not connected to anything right?

What is a graph contraction?


db_fetch_object returning null

Question: This is the line:
$row = db_fetch_object($result);

While $result is valid but $row is getting a null value which I've checked with is_null.
As per this function's @return value, it can only return FALSE in failure.
Also mysql_db_object states the same.
What could be the reason it is returning null?
Comment: FALSE !== NULL ...
Comment: What is the actual query?
Answer: Actually, db_fetch_object() could also return NULL, contrary to what the documentation says. The documentation assumes you aren't passing to the function a value that for PHP is equivalent to FALSE, for example NULL, an empty array, or an uninitialized variable. If the function gets a value that for PHP is equivalent to FALSE, the function will not execute any instruction, and it will return NULL.
function db_fetch_object($result) {
  if ($result) {
    return mysql_fetch_object($result);
  }
}

The same is true for other database engines, for example PostgreSQL, which uses the following function.
function db_fetch_object($result) {
  if ($result) {
    return pg_fetch_object($result);
  }
}

This is usually not a problem, since the function should normally be called as in the following snippets.
 if ($category = db_fetch_object(db_query('SELECT cid, title, block FROM {aggregator_category} WHERE cid = %d', $id))) {
    $block['subject'] = check_plain($category->title);
    $result = db_query_range('SELECT i.* FROM {aggregator_category_item} ci LEFT JOIN {aggregator_item} i ON ci.iid = i.iid WHERE ci.cid = %d ORDER BY i.timestamp DESC, i.iid DESC', $category->cid, 0, $category->block);
    $read_more = theme('more_link', url('aggregator/categories/' . $category->cid), t("View this category's recent news."));
  }

  while ($item = db_fetch_object($result)) {
    $items[] = theme('aggregator_block_item', $item);
  }

In both the cases, the control statements will not be executed, since for them NULL is equivalent to FALSE.

db_fetch_object returning null


How to solve # 7 in SQLZOO select names section

Question: All:
I am learnig SQL now, but stuck at   #7   of

http://sqlzoo.net/wiki/SELECT_names

Bahamas has three a - who else?

Find the countries that have three or more a in the name

Thanks
Comment: Does it matter if it's an 'a' or an 'A', i.e case sensitive or case insensitive?
Comment: Is this a homework assignment?  Happy to answer it, but just asking.
Comment: @TimBiegeleisen No, it is from SQLZOO, just self study
Comment: @Kuan Please review the answers given below.
Answer: Try using the LIKE operator:
SELECT name FROM world
WHERE name LIKE '%a%a%a%'

If you want to do case-insensitive search for either a or A then you can use the LOWER() function:
SELECT name FROM world
WHERE LOWER(name) LIKE '%a%a%a%'

Edit:
We could also use REGEXP here:
SELECT name FROM world
WHERE name REGEXP '(.*[a]){3,}';

However, for this particular example, I would go with LIKE, because it probably would perform better, and less of an overhead, than using REGEXP.
Comment: I think this is correct but their system doesn't recognise this answer as good yet in the list of countries all countries have 3 or more 'a' letters.
Comment: Afghanistan has 3 a's, but with different case.
Comment: Case insensitive or not?
Comment: @jarlh The link he provided gave this example: `Bahamas has three a - who else?`  I will update my answer to include an option for both upper and lower case.
Comment: @jarlh The OP does not go _nearly_ into this depth of concern...so why are you splitting hairs here?  The OP used lowercase `a`, which means either it wants all lowercase `a` or _all_ `a/A` regardless of case.
Comment: @TimBiegeleisen, sorry if I wasn't clear enough, just gave an example of a country name with three a's, but not returned if looking just for lower case a.
Comment: I updated my answer to give a query which takes `LOWER()` of the `name` column to get around this problem.
Answer: Try this query:
SELECT name
FROM world
WHERE LEN(name) - LEN(REPLACE(name,'a', '')) > 2

Comment: @jarlh yours is a trap question
Comment: @Kuan: Change to this as replace takes 3 arguments.

SELECT name
FROM world
WHERE LEN(name) - LEN(REPLACE(name,'a', '')) > 2
Comment: LEN is product specific, and no dbms is specified in the question. Which dbms does LEN work with?
Comment: @DrewPierce Yeah he hit me with a trap too but I got out of it ^ ^
Answer: I'm trying to solve this lecture with regular expressions but couldn't match this correctly.
regexp '(.*[a]){3,}'

Should match 3 or more 'a', which it does but:
"Sao Tomé and Príncipe" with 2 a's is matched by LIKE '%a%a%a%' which is the correct answer.
Im curious what's going wrong here?
Comment: Your `REGEXP` pattern is correct, [see here](http://rextester.com/VTDJF11924).  Maybe there was some other problem with your query.  In any case, I would go with `LIKE` for this particular question.
Answer: SELECT name
FROM world
WHERE LENGTH(name) - LENGTH(REPLACE(lower(name),'a', '')) >= 3

Answer: This is worked for me:
SELECT name FROM world WHERE name LIKE '%a%a%a%';


Compartilhamento de link no Facebook

Question: Estou fazendo um sistema para o meu curso e encontrei um grande problema na parte onde devo compartilhar o link do site diretamente no Facebook.
Tenho o botão em meu site que faz abrir direto a janela de publicação do Facebook, estou mandando este link para ser compartilhado:
http://localhost/BAC....pag=lerMais.php?&codigo=3

Porém, quando o link vai para o Facebook, clico nele para abri-lo, mas o link vai apenas:
http://localhost/BAC...pag=lerMais.php

Ou seja, ele apaga o &codigo=3. Como consertar esse erro?
function mensagem (codigoConteudo) {
    var link = "http://www.facebook.com/sharer.php?u=http://localhost/BACKUPS_TCC/09/Sistema3009/areaAdm.php?pag=lerMais.php&codigo="+codigoConteudo;
    window.open(link, 'facebook_share', 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no',"gl");
}

Answer: Tenho a impressão de que seja porque o valor passado (que é uma URL inteira) não está devidamente codificado para URL. Tente:
var link = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent("http://localhost/BACKUPS_TCC/09/Sistema3009/areaAdm.php?pag=lerMais.php"+codigoConteudo);

Comment: FUncionou cara, muito obrigado!!! valeu mesmo :)
Comment: @MatheusLuz por favor, se a resposta funcionou, marque ela como correta, leia por favor [Como e por que aceitar uma resposta?](http://meta.pt.stackoverflow.com/a/1079/3635)

Compartilhamento de link no Facebook


Examples for Type I and Type II errors

Question: I was checking on Type I (reject a true H$_{0}$) and Type II (fail to reject a false H$_{0}$) errors during hypothesis testing and got to to know the definitions. But I was looking for where and how do these errors occur in real time scenarios. It would be great if someone came up with an example and explained the process where these errors occur.
Comment: See http://xkcd.com/882/ for an illustrated example of Type I errors in a "real time scenario." Perhaps after reading that you could come up with an analogous example of Type II errors.
Comment: It is not obvious to me what "real time scenarios" means. Do you mean "real world" perhaps?
Comment: Yeah Thomas,I meant real world.I have been reading few examples as given below,but what I wanted to know is that the reason why that happens.Does it have to do something with the sample size or kind of sample we take?
Comment: Wikipedia makes this sound way *way* more complicated than it is, so thanks all answerers for the simpler explanation :)   https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#Example
Answer: A picture is worth a thousand words. Null hypothesis: patient is not pregnant.

Image via Paul Ellis.
Comment: @AlecosPapadopoulos And yet explaining humor carries its own problems. The OP has already indicated a familiarity with textbook explanation.
Comment: Not sure how you get that. The null hypothesis on the left is "not pregnant", and the error is Type I. Har har. The null hypothesis on the right is also "not pregnant" and the error is Type II. Har har.
Comment: ...and a word generates a thousand images. For the benefit of all readers, of all levels of knowledge and understanding, perhaps it would be useful after the picture, to explain how and why it represents examples of type I and type II errors.
Comment: So, I guess the null hypothesis in the left picture is "Pregnant" and the doctor _falsely asserts_ it ("false positive"), while in the right picture the null hypothesis is also "Pregnant" and the doctor _falsely negates_ it (false negative)?
Comment: You seem to have mistakenly edited your post to mention that the null hypothesis is "pregnant", whereas it is of course "not pregnant".
Comment: I get that because I do not have a fully clear knowledge of Hypothesis testing, and also, the terms "false positive" and "false negative" don't have any specific meaning to me (so I try to interpret them using only logic and not knowledge), since nobody in my field uses them. So I try to make sense of this very funny picture and the _intuitive_  null hypothesis is "Patient is pregnant" -because, usually, people don't go about asking the question "Am I not pregnant?" (again, everyday, "reasonable" logic here). CONTD
Comment: @AlecosPapadopoulos It seems like you are miffed that I am not answering a different question. *Null hypothesis* (i.e. H$_{0}$) $\ne$ "asking [a] question".
Comment: @amoeba ACK! What a moron I am! Thank you. Corrected.
Comment: CONTD Moreover nobody has told me that the "null hypothesis" is so called because historically it represented an assumption of "null effect" - so I just think that the "null" word just corresponds to the subscript $0$, just an ordering convention, nothing more. Alas, statistics is not particularly intuitive and so I got it all wrong... now, I believe that there is a positive probability that some readers will make the same mistakes as those I wrote in my first comment -and this is why I suggested that after the funny picture, include some explanation so that your answer may not be misleading.
Comment: Wikipedia makes this sound way *way* more complicated than it is, so thanks for the simpler explanation :)   https://en.wikipedia.org/wiki/Type_I_and_type_II_errors#Example
Answer: Let's say you are testing a new drug for some disease. In a test of its effectiveness, a type I error would be to say it has an effect when it does not; a type II error would be to say it has no effect when it does.
Answer: Type I error /false positive: is same as rejecting the null when it is true.
Few Examples:

(With the null hypothesis that the person is innocent), convicting an innocent person
(With the null hypothesis that e-mail is non-spam), non-spam mail is sent to spam box
(With the null hypothesis that there is no metal present in passenger's bag), metal detector beeps (detects metal) for a bag with no metal

Type II error /false negative: is similar to accepting the null when it is false.
Few Examples:

(With the null hypothesis that the person is innocent), letting a guilty person go free.
(With the null hypothesis that e-mail is non-spam), Spam mail is sent to Inbox
(With the null hypothesis that there is no metal present in passenger's bag), metal detector fails to beep (does not detect metal) for a bag with metal in it

Other beautiful examples in layman's terms are give here:
Is there a way to remember the definitions of Type I and Type II Errors?
Comment: In Type II (false negative), shouldn't it be "spam email is sent to inbox"?
Answer: The boy who cried wolf.
I am not sure who is who in the fable but the basic idea is that the two types of errors (Type I and Type II) are timely ordered in the famous fable.
Type I: villagers (scientists) believe there is a wolf (effect in population), since the boy cried wolf, but in reality there is not any.
Type II: villagers (scientists) believe there is not any wolf (effect in population), although the boy cries wolf, and in reality there is a wolf.
Never been a fan of a examples that taught which one is "worse" as (in my opinion) it is dependent on a problem at hand.
Answer: Null hypothesis is: "Today is not my friends birthday."

Type I error: My friend does not have birthday today but I will wish her happy birthday.
Type II error: My friend has birthday today but I don't wish her happy birthday.
Comment: These are not serious answers.

Examples for Type I and Type II errors


PP REST API charge tax and shipping without sending address?

Question: Using the REST API, how can I charge tax or shipping if I send the user to PayPal to collect shipping information (and pay, of course)?
Doing some research it almost seems like that isn't possible, but I can't imagine that being the case. If I have to collect shipping information myself, the value prop for using PP is greatly reduced.
Comment: I'm wondering if the proper workflow is to send the "sub-total" in the initial payment/create call, and then update the price with shipping and tax info as part of the payment/execution call?
Comment: Well, sending a new amount in the execution call doesn't change the original created payment... so still an issue
Comment: Similar question although no answer + workaround with IP: http://stackoverflow.com/questions/23464542/set-shipping-fee-based-on-users-shipping-address-paypal-rest-api
Answer: With the REST API, just like the Classic API, a PayPal payment is executed in three steps:
1) Send initial information to PayPal to get a token. Redirect customer to PayPal. Customer authorizes payment.
2) Get payment details (like the shipping address)
3) Confirm payment.
So, in this case, after getting the shipping address, you display an order review page to the customer where it will generate the shipping options and tax amount to the customer. They then have to select a "Confirm Order" button which will then finalize the charge to PayPal with the new tax/shipping and final amount.
In API terms, the final step is done with the /execute command. This accepts the payer_id you received in step 2, and a transactions array that supports a new amount object.
The amount object includes a details object that includes shipping, tax, handling fee, insurance, etc.
Include the details the customer decides on your review page and PayPal will charge the updated amount to the customer's funding source of choice.
Comment: When I tried this last year, sending a new amount object did not actually update the transaction. Is this fixed now?
Comment: I just installed the SDK and tested this out by adding in the new shipping amount. I did the initial send over as $20 with $1.50 shipping and then changed it on the execute to $31 with $2.50 shipping and it took it without issue. Seems like they fixed it.


Agrupamento e Soma no Oracle

Question: Eu tenho um registro de Clientes
ID    NOME  GRUPO
2033  JOAO  FORNECEDORES
2044  MARIA MANUTENCAO
2055  JOSE  FORNECEDORES

E tenho um registro de compras efetuado por cada cliente
ID_CLIENTE  VALOR_COMPRA
2033        4.000
2033        1.130
2044        8.930
2044        4.430
2055        4.023

Como realizar uma consulta que me retorne o gasto por grupo?
GRUPO         TOTAL_GASTO
FORNECEDORES  9.153
MANUTENCAO    13.360

E por cada cliente?
   CLIENTE  TOTAL_GASTO
   JOAO     5.130
   MARIA    13.360
   JOSE     4.023

Answer: Você pode utilizar a cláusula GROUP_BY em conjunto com a função SUM:
SELECT cli.grupo,
       SUM(com.valor_compra) AS total_gasto
  FROM clientes cli
       INNER JOIN compras com ON com.id_cliente = cli.id
 GROUP BY cli.grupo;

No caso do cliente:
SELECT cli.nome AS cliente,
       SUM(com.valor_compra) AS total_gasto
  FROM clientes cli
       INNER JOIN compras com ON com.id_cliente = cli.id
 GROUP BY cli.grupo

GROUP BY

A GROUP BY clause groups a result into subsets that have matching values for one or more columns.

Em tradução livre:

A cláusula GROUP BY agrupa o resultado em grupos que correspondam a uma ou mais colunas.

SUM

SUM is an aggregate function that evaluates the sum of the expression over a set of rows.

Em tradução livre:

SUM é uma função agregada que resolve a soma da expressão sobre o conjunto de linhas.

Agrupamento e Soma no Oracle


Translating a TensorFlow LSTM into synapticjs

Question: I'm working on implementing an interface between a TensorFlow basic LSTM that's already been trained and a javascript version that can be run in the browser.  The problem is that in all of the literature that I've read LSTMs are modeled as mini-networks (using only connections, nodes and gates) and TensorFlow seems to have a lot more going on.
The two questions that I have are:

Can the TensorFlow model be easily translated into a more conventional neural network structure?
Is there a practical way to map the trainable variables that TensorFlow gives you to this structure?

I can get the 'trainable variables' out of TensorFlow, the issue is that they appear to only have one value for bias per LSTM node, where most of the models I've seen would include several biases for the memory cell, the inputs and the output.
Answer:
Internally, the LSTMCell class stores the LSTM weights as a one big matrix instead of 8 smaller ones for efficiency purposes. It is quite easy to divide it horizontally and vertically to get to the more conventional representation. However, it might be easier and more efficient if your library does the similar optimization.
Here is the relevant piece of code of the BasicLSTMCell:
concat = linear([inputs, h], 4 * self._num_units, True)

# i = input_gate, j = new_input, f = forget_gate, o = output_gate
i, j, f, o = array_ops.split(1, 4, concat)

The linear function does the matrix multiplication to transform the concatenated input and the previous h state into 4 matrices of [batch_size, self._num_units] shape. The linear transformation uses a single matrix and bias variables that you're referring to in the question. The result is then split into different gates used by the LSTM transformation.
If you'd like to explicitly get the transformations for each gate, you can split that matrix and bias into 4 blocks. It is also quite easy to implement it from scratch using 4 or 8 linear transformations.