Install Debian Backports kernel automatically

Question: I've got the following pinnings set:
Package: linux-image-amd64
Pin: release a=wheezy-backports
Pin-Priority: 1001

Package: *
Pin: release a=wheezy-backports
Pin-Priority: 499

I get the following error:
$ sudo apt-get install linux-image-amd64
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 linux-image-amd64 : Depends: linux-image-3.16.0-0.bpo.4-amd64 but it is not going to   be installed
E: Unable to correct problems, you have held broken packages.

The policies seem to be correct:
$ apt-cache policy linux-image-amd64
linux-image-amd64:
  Installed: 3.2+46
  Candidate: 3.16+63~bpo70+1
  Package pin: 3.16+63~bpo70+1
  Version table:
     3.16+63~bpo70+1 1001
        499 http://ftp.nl.debian.org/debian/ wheezy-backports/main amd64 Packages
 *** 3.2+46 1001
        500 http://ftp.nl.debian.org/debian/ wheezy/main amd64 Packages
        100 /var/lib/dpkg/status

$ apt-cache policy linux-image-3.16.0-0.bpo.4-amd64
linux-image-3.16.0-0.bpo.4-amd64:
  Installed: (none)
  Candidate: 3.16.7-ckt4-3~bpo70+1
  Version table:
     3.16.7-ckt4-3~bpo70+1 0
        499 http://ftp.nl.debian.org/debian/ wheezy-backports/main amd64 Packages

So I don't get the error. What am I doing wrong?
I'm trying to use puppet to upgrade all Wheezy machines to the backports kernel (a reboot streak is planned), which is why I want to solve it correctly. I could manually login to all servers to run:
sudo apt-get install -t wheezy-backports linux-image-amd64

Which works, but is not as convenient.
UPDATE
As requested:
/etc/apt/preferences.d$ cat linux-image
Package: linux-image-*
Pin: release a=wheezy-backports
Pin-Priority: 1001

Package: *
Pin: release a=wheezy-backports
Pin-Priority: 499

/etc/apt/preferences.d$ sudo apt-get update
Hit http://debian.kumina.nl wheezy-kumina Release.gpg
.
.
.
Reading package lists... Done
/etc/apt/preferences.d$ sudo apt-get install linux-image-amd64
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 linux-image-amd64 : Depends: linux-image-3.16.0-0.bpo.4-amd64 but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
/etc/apt/preferences.d$ aptitude why-not linux-image-3.16.0-0.bpo.4-amd64
Unable to find a reason to remove linux-image-3.16.0-0.bpo.4-amd64.

Answer:
sudo apt-get install -t wheezy-backports linux-image-amd64

it is not convenient I know .. but it is the right way to do things without having troubles in future (IMHO of course)
Comment: This doesn't have enough upvotes
Comment: - if debian has engineered its system to work one way I "suppose" they have their good reason ;) (see [backports Instructions](http://backports.debian.org/Instructions/))
- pinning the entire source you give a higher priority to a wide number of packages being recompiled from testing and unstable and not tested as the stable couterparts
- the philosophy using `-t` is to let the package to install its dependencies .. "do strictly what you need" ..
- its a while list approach: do what you are aware to do, when you need
Comment: What troubles in the future would you expect with this?
Answer: Check what that package depends on and what those dependencies need as well.
For example I see this for my machine:
#apt-cache  show linux-image-amd64
Package: linux-image-amd64
<snip>
Depends: linux-image-3.16.0-4-amd64

and
# apt-cache  show linux-image-3.16.0-4-amd64
Package: linux-image-3.16.0-4-amd64
<snip>
Depends: kmod | module-init-tools, linux-base (>= 3~), debconf (>= 0.5) | debconf-2.0, initramfs-tools (>= 0.110~) | linux-initramfs-tool
Pre-Depends: debconf | debconf-2.0

Check if dependencies are taken from backports as well.
Comment: I don't see anything about pinning dependencies version in your question. you need to configure higher priority for packages needed for linux-image-3.16.0-0.bpo.4-amd64. check this out: ```Depends: kmod | module-init-tools, linux-base (>= 3~), debconf (>= 0.5) | debconf-2.0, initramfs-tools (>= 0.110~) | dracut (>= 0.40+1-1~) | linux-initramfs-tool```. If you using `dracut` for example, Wheezy has version `020-2 0`, while backports have `040+1-1 0`. In thiks case you need to increase priority of Dracut package to be taken from backports as well.
Comment: It will, if you enforce it with `-t wheezy-backports`. But this enforcement will also install all newer versions for not installed dependencies from backports as well, regardless of fact if stable versions are enough or not. If you need to install only limited and controlled number of packages from backports, you need to track the dependencies and manually pin them. If you don't care about that, sure go ahead and do full `-t *backports`.
Comment: That's already explained in my question...
Comment: Wouldn't those be pulled in as well when I install it via 'apt-get -t wheezy-backports install linux-image-amd64'?
Comment: Ah got it, you're right. I needed to fetch initramfs-tools from backports as well and then it can be done automatically. Thanks!
Answer: Change the top line in your preferences to
Package: linux-image-*

Run
apt-get update

Try to install again.  If you still get the error, check
aptitude why-not linux-image-3.16.0-0.bpo.4-amd64

Comment: Doesn't work. Added the command output to my question.
Comment: OK, thanks for trying.  I'd be inclined to use the `aptitude` resolver interactively to identify the problem.  Maybe `linux-*` to include other dependencies?  Is it feasible to add `APT::Default-Release "wheezy-backports";` to the configuration temporarily?
Comment: We actually remove aptitude from all our servers, I had to install it to do the test. So that won't be feasible. Adding the config option temporarily is not feasible and, honestly, not really a nice solution :) I'm pretty sure this should be doable with apt-get without any hacks, just can't figure out how!


Are there integer solutions to $9^x - 8^y = 1$?

Question: This came up in proving non-regularity of a certain language (powers of 2 over the ternary alphabet). Any clue to the above equation could help me move forward.
Edit:
Of course, $x = 1, y = 1$ is a solution. I am looking for non-trivial solutions.
Comment: yes x=1,y=1 is a soution
Comment: @avinash: out of curiosity, how does this come up in proving non-regularity of the language you describe?  The approach which first occurs to me is totally different.  Are you using the pumping lemma?
Comment: @Qiaochu: Yes, I was trying pumping lemma. But it's going nowhere. How did you solve it?
Comment: @avinash: the approach I thought of is unnecessarily complicated.  There is a theorem of Berstel which implies that if the language you're looking at is regular, then the number L_n of words of length n must be eventually periodic, and I believe one derives a contradiction from here.
Comment: @Qiaochu: Since I was getting nowhere near the solution, I have posted it as a separate question at http://cstheory.stackexchange.com/questions/2083/ .
Answer: Except $x=1$ and $y=1$ there aren't any.
We have that
$$3^{2x} - 1 = 8^y$$
i.e
$$ (3^x + 1)(3^x - 1)  = 8^y$$
Thus we must have that
$$3^x + 1 = 2^m, 3^x - 1 = 2^n$$
Thus $$2^m - 2^n = 2$$
i.e
$$ 2^n(2^{m-n} - 1) = 2$$
Thus $n=1$ and $m=2$.
Comment: @user: If A*B = a power of 2 = 2^y, then, both must be powers of 2. (I am counting 1 to be a power of 2 = 2^0). This is because any prime that divides A, must divide 2^y and hence must be 2.
Comment: You didn't use the assumption that x>1; you got n=1 which implies x=1. :-) (Many times a proof by contradiction can be simplified if you try to rewrite it without the contradication… it's usually worth a shot to see if it gets simpler.)
Comment: @Shree: Right, I will just delete that line.
Comment: @Moron, pardon my ignorance, but can you explain why it must be true that $3^x+1=2^m$ and $3^x-1=2^n$?
Comment: @Aryabhata Does this proof assume that $x,y\geq0$?
Comment: @Servaes: Yes. The case when at least one of them is $\lt 0$ is trivial and uninteresting.
Answer: The only solution is $x=y=1$. This is a special case of Catalan's conjecture which was proven by Mihailescu in 2002: the only solution in natural numbers of $x^a - y^b = 1$ with $a,b\gt 1$ is $x=3$, $a=2$, $y=2$, and $b=3$.
But as Moron points out, it can be deduced much more elementarily.
Answer: Equation $\rm\ 3^{2x}-2^{3y}=1\ $ is an instance of various special cases of Catalan's Conjecture.
First,$\ $ making the specialization $\rm\ \ \: z,\:p^n = 3^x,2^{3y}\ $ below yields $\rm\ x = 1 = y\ $ as desired.
LEMMA$\ \ $ $\rm z^2 - p^n = 1\ \ \Rightarrow\ \ z,\:p^n = \:3\ ,\:2^3\ $  or $\ 2,\:3\ $ for $\rm\ \ z,\:p\:,n\in \mathbb N,\ \ p\: $ prime
Proof $\rm\ \ \ (z+1)\:(z-1)\: =\: p^n\ \  \Rightarrow\ \ z+1 = p^{\:j},\ \ z-1 = p^k\ $ for some $\rm\ j,\:k\in \mathbb N$
$\rm\quad \:\Rightarrow\ \ \ \ 2\ =\ p^{\:j} - p^k\ =\ p^k\: (p^{\:j-k}-1) \ \Rightarrow\ p^k=2\ $ or $\rm\ p^k = 1 \ \Rightarrow\ \ldots$
Second, it's simply the special case $\rm\: X = 3^x,\ Y = 2^y\: $ of $\rm\ X^2 - Y^3 = 1\:,\: $ solved by Euler in 1738. Nowadays one can present this solution quite easily using elementary properties of $\rm\ \mathbb Z[\sqrt\[3\]{2}]\:$, e.g see p.44 of Metsankyla: Catalan's Conjecture: another old diophantine problem solved. See also this MO thread and this MO thread and Schoof: Catalan's Conjecture. Note also that Catalan equations are a special case of the theory of generalized Fermat (FLT) equations, e.g. see Darmon's exposition.


Simplify: $[ (A_1 \cap B_1) \times A_2 \times \dotsb \times A_n ] \cup \dotsb \cup [ A_1 \times \dotsb \times A_{n-1} \times (A_n \cap B_n) ]$

Question: I've just started studying Measure Theory. I was a little bit stuck on simplifying a set theoretic expression when I tried to prove a little problem from my reference book. Here I pose my problem in a general set theoretic manner:

Given two finite families of indexed sets $\{A_k\}_{k=1}^n$ and $\{B_k\}_{k=1}^n$, for some $n \in \mathbb{N}$. Can we simplify
$$ \tag{1}
\Big[ (A_1 \cap B_1) \times A_2 \times \dotsb \times A_n \Big] \cup \dotsb \cup
\Big[ A_1 \times \dotsb \times A_{n-1} \times (A_n \cap B_n) \Big]
$$
into a form of large union operation?

Here is my attempt:

I directly put the large union operation into the following expression:
$$ \tag{2}
\bigcup_{k=1}^n \left[ \left( \prod_{\alpha=1}^{k - 1} A_\alpha \right) \times \big( A_k
\cap B_k \big) \times \left( \prod_{\beta = k + 1}^{n} A_\beta \right) \right]
$$
My concern is, when $k = 1$, we have
$$ \tag{3}
\left( \prod_{\alpha = 1}^0 A_\alpha \right) \times (A_1 \cap B_1) \times
\left( \prod_{\beta = 2}^n A_\beta \right)
$$
and when $k = n$ we have
$$ \tag{4}
\left( \prod_{\alpha = 1}^{n-1} A_\alpha \right) \times (A_n \cap B_n) \times
\left( \prod_{\beta = n+1}^n A_\beta \right)
$$
within the square braces, each of which is syntactically error. I presume
$$ \tag{5}
\prod_{\alpha = 1}^0 A_\alpha = \prod_{\varnothing} A_\alpha
$$
and
$$ \tag{6}
\prod_{\beta = n+1}^n A_\beta = \prod_{\varnothing} A_\beta
$$
and hence expression $(2)$ is precisely equal to expression $(1)$.

My big question is: $\textbf{are these presumptions allowed?}$ If it's not the case, then is there any better solution instead of writing down expression $(1)$?
Any help is highly appreciated. Thank you.
Answer: Yes, that is possible. Generally an empty product is taken to be the neutral element for this operation. For the cartesian product there is no neutral product, but we can just invent a formal neutral element, and all is fine.
A different simplification could be simply:
$$ \{(a_1,\ldots,a_n)\in A_1\times\ldots\times A_n\mid \exists k: a_k\in B_k\}$$
EDIT: Since you are specifying measure theory, maybe you also want to simplify this to disjoint union? Like
$$\bigcup_{k=1}^n \left(\prod_{l<k}A_l\setminus B_l\right)\times (A_k\cap B_k)\times\prod_{l>k}A_l$$
Comment: I see. Initially, I was not sure whether my invention was allowed. But I get it clear from your answer and from my search at other place. Your simplification in set builder notation is very good and clear. I could've made use of it anyway. Thanks.

Thanks again for the latest suggestion. I'll take it under consideration. It'll be useful once I deal with the main topics in Measure Theory. At the moment, I am still reading and working on an introductory topic (about the measure of elementary sets of R^n).
Comment: I am using 'An Introduction to Measure Theory' by Terrence Tao (which I directly download from his blog).
To be honest, I have no formal university education background in math (I have a bachelor degree in Engineering), but I really am interested in pure math, so I study pure math by myself.
Comment: Okay. In measure theory one often wants to have unions of disjoint sets, because then (under certain limitations) the measure of the union is the sum of the measures.


Is it wrong to discover the factors using EFA and then do CFA for compartive purpose on the same data set?

Question: I have initially done EFA to extract the factors then conducted CFA to confirm those factors and secondly for the comparative purpose. Example factors that were extracted through EFA were further used from the comparative purpose.. The sample size of 500 was split into two parts, 250 each between private and government school for comparative purpose based on the regression value derived through CFA. Both EFA and CFA was done on the same data set.
Comment: For a similar phenomenon elsewhere, this is called double-dipping, or [circular analysis](https://en.wikipedia.org/wiki/Circular_analysis)
Answer: Welcome to CV, Sunita.
Generally speaking, yes, this would be an ill-advised approach. You can think of EFA as a data-driven theory-building approach, and CFA as a researcher-decision-driven theory-testing approach. In essence, running both analyses on the same sample of data would be akin to asking "What do the data tell me the latent structure looks like...?" [EFA] then to conclude, "A-ha! Just as I thought! The latent structure looks just like what the data told me!" [CFA]. In other words, the CFA in this instance is not particularly informative (see our paper, Sakaluk & Fisher, 2016 if you want more of an elaborated version of this [and related] arguments, though note while we think this is the typical way "confirmatory" is understood/meant now, this was not the original meaning of the term when it was introduced to the factor analysis literature)
One approach that is somewhat common is for researchers to randomly split their sample when they have a sufficiently large data set: one sample for EFA, and another for CFA. This way, the test of the adequacy of the measurement model is conducted on a distinct subset of data than that which informed the initial measurement model. However, it sounds as though you already ran (or want to run) both analyses on the very same data, which limits the informativeness of the CFA in the ways I've described.
One thing I would consider asking yourself is: why is it important for you to conduct a CFA at this stage of research? You can still use the outputs of EFA in subsequent analyses like regression (or exploratory structural equation modeling, if you want to keep these analyses in "latent space", see Asparouhov & Muthén, 2009). Likewise, you can get indexes of model fit for exploratory models like EFAs (see Fabrigar et al., 1999, or Fabrigar & Wegener's 201 book) and ESEMs if that's what motivated you to attempt the CFA. Depending on your software options, this is included either as standardized output (many R packages, Mplus, SAS), or you can use some freely available resources to calculate them from standard output (e.g., from SPSS). If it's helpful, I can link to those resources if that's the situation you find yourself in.
References
Asparouhov, T., & Muthén, B. (2009). Exploratory structural equation modeling. Structural Equation Modeling, 16(3), 397-438.
Fabrigar, L. R., Wegener, D. T., MacCallum, R. C., & Strahan, E. J. (1999). Evaluating the use of exploratory factor analysis in psychological research. Psychological Methods, 4(3), 272.
Fabrigar, L. R., & Wegener, D. T. (2011). Exploratory factor analysis. Oxford University Press.
Sakaluk, J. K., & Fisher, A. N. (2019). Measurement memo I: Updated practices in psychological measurement for sexual scientists. The Canadian Journal of Human Sexuality, 28(2), 84-92. (OA preprint: https://psyarxiv.com/tb62k/)


Mudar valor da variável dentro de classe anônima

Question: Gostaria de saber o motivo que sempre que dentro de uma classe anonima tento mudar o valor de uma variável "externa" ela não, muda continua na mesma. Teria algo similar que poderia fazer que fosse dar o mesmo resultado?
Usei o Thread como exemplo, mas em qualquer classe anônima isso acontece. (Inclusive no Android)
public class Teste {

    public boolean umIgualUm = false;

    public Teste() {
        fazerAlgo();
    }

    public void fazerAlgo() {

        new Thread() {
            public void run() {
                if (1 == 1) {
                    System.out.println("Entra aqui");
                    umIgualUm = true;
                }
            }
        }.start();

        System.out.println(umIgualUm); //Exibe false

    }

}

Exemplo Android
public class UsuarioDAO {

    public boolean metodoDeuCerto = false;

    public UsuarioDAO(){}

    public boolean cadastrarUsuario(Usuario usuario) {

        ParseUser parseUser = new ParseUser();
        parseUser.setUsername(usuario.getNome());
        parseUser.setEmail(usuario.getEmail());
        parseUser.setPassword(usuario.getSenha());

        parseUser.signUpInBackground(new SignUpCallback() {
            @Override
            public void done(ParseException e) {
                if(e == null) { //Quer dizer que deu certo
                    metodoDeuCerto = true;
                }else{
                    e.printStackTrace();
                    metodoDeuCerto = false;
                }

            }

        });

        return metodoDeuCerto;

    }
}

Comment: Na verdade acredito que seja por conta da sincronia em que as coisas dentro da classe anônima acontecem. Como no exemplo postado ao startar a thread o System.out.println é executado logo em seguida e não deu tempo de terminar o processo do run()
Comment: Tem a certeza que isso acontece no caso de não ser "numa Thread"? No uso de "uma Thread" acontece porque quando  linha `System.out.println(umIgualUm);` é executada a linha `umIgualUm = true;` (pode) não (ter sido)foi executada.
Comment: Com qual outra classe anonima eu poderia testar?
Comment: No Android pode testar por exemplo num `OnClickListener`, atribuído a um botão.
Comment: Coloquei o exemplo do Android, que está acontecendo realmente.
Comment: Nesse exemplo acontece o mesmo. O método `done()` é chamado, pela implementação de `signUpInBackground()`, após a linha `return metodoDeuCerto;` ter sido executada.
Comment: E como fazer para poder dar um retorno para o usuario se deu certo ou não o cadastro? Pois já que não posso fazer assim, nem dar o return por dentro do metodo da classe anonima (claro). Como fazer?
Comment: Depende de como quer informar o usuário. No entanto, qualquer que seja essa forma, ela tem de ser feita dentro do método `done()` ou em um método chamado por ele.
Comment: Precisava informar essa o usuario, retornar ou a Exception ou um boolean, mas precisava retornar pq não é essa classe que irá cuidar de avisar o usuario com alguam mensagem.
Comment: Nesse caso passe o SignUpCallback ao método `cadastrarUsuario()` ou, talvez melhor, crie um nova interface/classe para receber o resultado.
Comment: Teria alguma forma de esperar o SignUpCallback  terminar para poder retornar?
Comment: Se de facto é isso que quer, pode, veja a [documentação](http://parseplatform.org/Parse-SDK-Android/api/com/parse/ParseUser.html#signUpInBackground())
Comment: Certo, mas ainda não entendi como esperar o meu thread "principal" fazer esperar por esse em especifico. Desculpa, não sou tão experiente com java.
Comment: É por isso que eu não lhe vou dizer como. Não quero contribuir para que você comece a aprender de forma errada :)
Comment: Bom andei pesquisando e nao consegui nada tao referente. Queria a ideia de pegar o Thread da classe UsuarioDAO  e pedir para esperar ou algo assim. Tenho a ideia de usar o metodo join() mas nao sei de que forma exatamente. Sinceramente, consegue me dar uma ajuda, gostaria de gazer isso logo, estou ficando aflito.
Answer: Há dois problemas aqui:

O método start pode demorar para de fato iniciar a nova thread. Com isso o System.out pode acabar executando primeiro.
Variáveis podem ficar em caches específicas de threads, e com isso, threads diferentes podem enxergar valores diferentes para a mesma variável ao mesmo tempo. Para contornar-se este problema pode-se usar sincronização ou fazer as variáveis serem volatile (algo que instrui a JVM a não permitir que elas sejam mantidas em caches separadas por threads). Uma outra possibilidade é usar um AtomicBoolean.

O problema não tem nenhuma relação com o fato de a variável estar sendo acessada de dentro da classe anônima. O problema é ela estar sendo acessada de outra thread.
Se você vê esse problema acontecendo quando usa uma classe anônima que não seja uma Thread, solicito que mostre esse código.
Quanto ao seu segundo código, o métodosignUpInBackground cria uma thread nova para executar o que está na classe anônima, o que significa que o método cadastrarUsuario executará o return sem esperar o signUpInBackground ser concluído.
De fato, o método signUpInBackground() retorna uma Task<Void>.
O que é a classe Task de acordo com a documentação?

Represents the result of an asynchronous operation.

Traduzindo para o português:

Representa o resultado de uma operação assíncrona.

O que é uma operação assíncrona?
Significa que o processo que a inicia não aguarda pelo seu término, que produzirá algum resultado apenas em um futuro incerto. Ou seja, o seu método cadastrarUsuario não está de fato cadastrando um usuário, está apenas pedindo que um usuário seja cadastrado e retornando imediatamente. Note que isso não implica que o usuário foi de fato cadastrado em momento algum. Você teria que esperar a Task terminar para saber isso.
Nos dois casos, o problema é que o que aparece no corpo da classe anônima, só é executado muito tempo depois do método principal já ter retornado, e ainda por cima é executado em outra thread.
Comment: Então, criei esse exemplo somente em Java, mas estou na realidade trabalhando em um projeto Android, que usa também uma classe anonima (não é Thread) e acontece a mesma coisa.  O exemplo em Java criei para simplificar. E por exemplo, se eu quisesse usar em vez do boolean, fizer isso "Excpetion ex = null", depois quando eu tentasse modificar, ele continuaria como null, mesmo passando algo diferente. Posso mandar feito em Android, usando o Parse.
Comment: Citei exemplo do Android
Comment: @Hamon Resposta editada.
Comment: Certo e como posso fazer o retorno certo? O método até cadastra no banco de dados o usuário, mas não chega a mudar boolean (que já temos a explicação para isso), mas como faria para poder dar um retorno, da melhor forma possivel? Sem muita perda de otimização
Comment: @Hamon , você precisará programar assincronamente.
Comment: Desculpa, sou meio leigo, como?
Answer: Como já disseram antes, você não pode mudar o valor de uma variável dentro da thread e testá-la logo em seguida. Provavelmente o seu teste (if, println, ou o que seja) irá ser chamado antes da thread ser iniciada.
Uma das formas corretas a se trabalhar, seria: (Com seu próprio exemplo)
public class Teste {

    public Teste() {
        fazerAlgo();
    }

    public void fazerAlgo() {

        new Thread() {
            public void run() {
                System.out.println("Entra aqui");

                if (1 == 1) {
                    metodoDeuCerto();
                } else {
                    metodoNaoDeuCerto();
                }
            }
        }.start();
    }

    public void metodoDeuCerto() {
        System.out.println("Deu certo!");
    }

    public void metodoNaoDeuCerto() {
        System.out.println("Nao deu certo!");
    }
}

(EDITADO)
Exemplo Android:
public class UsuarioDAO {

    private SignupListener listener;

    public UsuarioDAO(){}

    public void cadastrarUsuario(Usuario usuario) {

        ParseUser parseUser = new ParseUser();
        parseUser.setUsername(usuario.getNome());
        parseUser.setEmail(usuario.getEmail());
        parseUser.setPassword(usuario.getSenha());

        parseUser.signUpInBackground(new SignUpCallback() {
            @Override
            public void done(ParseException e) {
                if(e == null) {
                   if ( listener != null ) {
                       listener.deuCerto();
                   }
                }else{
                   e.printStackTrace();
                   if ( listener != null ) {
                       listener.naoDeuCerto();
                   }
                }

            }

        });
    }

    public void setSignupListener(SignupListener signupListener) {
        this.listener = signupListener;
    }

    public interface SignupListener {
        void deuCerto();
        void naoDeuCerto();
    }
}

// Exemplo da Activity chamando o UsuarioDAO
public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        Usuario usuario = new Usuario();
        usuario.setUserName("usuario");
        usuario.setEmail("firstname.lastname@example.com");
        usuario.setPassword("senha");

        UsuarioDAO dao = new UsuarioDAO();
        dao.setSignupListener(signupListener);
        dao.cadastrarUsuario(usuario);

    }

    private UsuarioDAO.SignupListener signupListener = new UsuarioDAO.SignupListener {
        @Override
        public void deuCerto() {
           //DO SOMETHING
        }

        @Override
        public void naoDeuCerto() {
           //DO SOMETHING
        }
    }
}

Comment: Eu precisava de um retorno no metodo, pq o metodo que recebe esse retorno avisa o usuario
Comment: O problema é que você está usando uma classe DAO para fazer algo que não devia, que é o signup. Mas não vou entrar nesse mérito já que a pergunta não foi essa. Mas isso é facilmente contornável criando o seu próprio listener. Vou editar a resposta do exemplo com android para você ver como poderia ficar.
Comment: Mas o DAO nao faz os acessos ao banco? Inclusive o cadastro do usuario no.banco? Ou estou fazendo errado?
Comment: Da forma como está o exemplo, parece que você está fazendo algo a mais nesse signUpInBackground(), esperando a resposta de alguma api, etc. De qualquer forma eu atualizei a resposta. Essa é uma das milhares de respostas possíveis para o seu problema.
Comment: Achei que seria interessante esperar essa thread terminar, dai sim conseguir retornar. So que nao estou conseguindo entender como posso usar o join() para que o thread main espere ate que o outro termine
Comment: Você não pode fazer isso na main thread do Android, isso só vai fazer com que sua aplicação pare de responder e consequentemente poderá travar seu app.
Comment: Mas entao esperar a thread do signup terminar para ai sim ele poder retornar, tem como?


Azure API Management WSDL Import Failing on SOAP Encoding's Array Type

Question: I'm trying to create an API from a WSDL and currently getting this error back from Azure APIM during the import step:
Error: Parsing error : Line 17, position 22: Unable to import API from WSDL: Undefined
complexType 'http://schemas.xmlsoap.org/soap/encoding/:Array' is used as a base for
complex type restriction.

I'm gathering that the Array type is not WSI-compliant, but would love insight as to how I can tinker with the WSDL to make it work? I don't own the service which generated the WSDL, but the WSDL hasn't changed since it was incepted and the provider has said it's okay for us to mess with it to get the Azure APIM import step to work. Just meaning, since Azure APIM's a passthrough what can I slice out of the WSDL which would still (a) let Azure APIM import it, and (b) allow the calls to successfully flow through Azure APIM at runtime?
I slimmed down the WSDL to this, but let me know if anything looks off as the original WSDL is ~5,500 lines:
<?xml version="1.0"?>

<definitions
    xmlns:s="http://www.w3.org/2001/XMLSchema"
    xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
    xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:s0="urn:ChestersCopperpotsServiceSoap"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:atls="http://tempuri.org/vc/atl/server/"
    targetNamespace="urn:ChestersCopperpotsServiceSoap"
    xmlns="http://schemas.xmlsoap.org/wsdl/"
>
    <types>
        <s:schema targetNamespace="urn:ChestersCopperpotsServiceSoap" attributeFormDefault="qualified" elementFormDefault="qualified">
            <s:import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
            <s:complexType name="CMessage">
                <s:sequence>
                    <s:element name="Code" type="s:int"/>
                    <s:element name="Text" type="s:string"/>
                </s:sequence>
            </s:complexType>
            <s:complexType name="GetMessages_return_Array">
                <s:complexContent>
                    <s:restriction base="soapenc:Array">
                        <s:attribute ref="soapenc:arrayType" wsdl:arrayType="s0:CMessage[]"/>
                    </s:restriction>
                </s:complexContent>
            </s:complexType>
            <s:complexType name="MyHeader">
                <s:sequence>
                    <s:element name="m_SessionID" type="s:string"/>
                </s:sequence>
            </s:complexType>
        </s:schema>
    </types>

    <message name="GetMessagesIn">
    </message>
    <message name="GetMessagesOut">
        <part name="return" type="s0:GetMessages_return_Array"/>
    </message>
    <message name="m_Header">
        <part name="m_Header" type="s0:MyHeader"/>
    </message>

    <portType name="ChestersCopperpotsServiceSoap">
        <operation name="GetMessages">
            <input message="s0:GetMessagesIn"/>
            <output message="s0:GetMessagesOut"/>
        </operation>
    </portType>

    <binding name="ChestersCopperpotsServiceSoap" type="s0:ChestersCopperpotsServiceSoap">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"/>
        <operation name="GetMessages">
            <soap:operation soapAction="#GetMessages" style="rpc"/>
            <input>
                <soap:body use="encoded" namespace="urn:ChestersCopperpotsService" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
                <soap:header message="s0:m_Header" part="m_Header" use="encoded" namespace="urn:ChestersCopperpotsService" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </input>
            <output>
                <soap:body use="encoded" namespace="urn:ChestersCopperpotsService" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
                <soap:header message="s0:m_Header" part="m_Header"  use="encoded" namespace="urn:ChestersCopperpotsService" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
            </output>
        </operation>
    </binding>

    <service name="ChestersCopperpotsService">
        <port name="ChestersCopperpotsServiceSoap" binding="s0:ChestersCopperpotsServiceSoap">
            <soap:address location="http://localhost:80/ChestersCopperpots/ccSOAP.dll?Handler=Default"/>
        </port>
    </service>

</definitions>

Full message stack from Azure APIM is:
Informational: ParsingXMLStarted : Started parsing XML
Informational: ParsingXMLComplete : Completed parsing XML
Verbose: WsdlImportRuleVerifyWadl11Schema : WSDL validated against XML Schema
Informational: WsdlPrecheckComplete : Completed WSDL verification. WSDL is considered valid.
Informational: WsdlParsingStarted : Service : Endpoint :
Informational: WsdlIdentification : WsdlVersion: 'Wsdl11' TargetNamespace: 'urn:ChestersCopperpotsServiceSoap'.
Informational: LoadedSchema : Target Namespace: 'urn:ChestersCopperpotsServiceSoap'.
Informational: LoadedSchemas : Loaded '1' schemas.
Informational: LoadedTypes : Loaded '0' types.
Informational: LoadedMessages : Loaded '3' messages.
Informational: LoadedInterfaces : Loaded '1' interfaces.
Informational: LoadedBindings : Loaded '1' bindings.
Informational: LoadedServices : Loaded '1' services.
Informational: WsdlParsingComplete : Parsed 1 operations and 3 messages
Informational: ApiType : Creating SOAP Passthrough API
Informational: APICreated : Name : chesterscopperpotsservice Service Url: http://localhost:80/ChestersCopperpots/ccSOAP.dll?Handler=Default
Informational: XsdParsing : Starting to parse urn:ChestersCopperpotsServiceSoap
Error: Parsing error : Line 17, position 22: Unable to import API from WSDL: Undefined complexType 'http://schemas.xmlsoap.org/soap/encoding/:Array' is used as a base for complex type restriction.

Comment: That is not an api management issue, if you open your wsdl file with VS, you will get the same error.
Comment: @MohamadHaidar ... i think i made it clear in the post that the issue is with the XML since i've stated that i'm looking for a way to tweak the XML to get APIM to ingest it.
Answer: my money is on this part (which in lack of row #, I suspect this is where the error get's triggered). The SOAP-to-REST transformation in APIM only supports "embedded" arrays, whereas yours is referring to another definition ("s0.CMessage" above). Try replacing that bit with
<s:complexType name="GetMessages_return_Array">
                <sequence>
                    <element name="ArrayOfCMessages" type="CMessage" minOccurs="1" maxOccurs="1"/>
            </sequence>
</s:complexType>

Comment: hi @Marius, your change worked and allowed Azure APIM to import the WSDL. unfortunately it'll take me a while to see if that change is a non-breaking one as far as how things go at runtime, but i'm a step closer and i appreciate that.

i'm trying to figure out how to award you the bounty, but not sure (i've only offered one once before i think).

and for the `element` i used this (a slight tweak):
``
Comment: thanks @Marius i'll give it a try. i'm traveling at the moment, but it's definitely on my list for tomorrow.
Comment: Please mark the answer as accepted, if this has helped so it might help others. Thank you.
Comment: hi @Marius ... unfortunately a bunch of other stuff broke after i edited the XSD. while your answer helped, it didn't fully solve my problem, unfortunately. seems that there may not have been a solution as we went through hoops to remove APIM from the workflow all together. sorry, i should have come back and provided some additional notes at the time.


$U \times V$ is open in the product metric

Question: I'm trying to prove the following statement:
"Suppose that $X$ and $Y$ are metric spaces and that $U \subseteq X$ and $V \subseteq Y$ are open. Show that $U \times V \subseteq X \times Y$ is open in the product metric on $X \times Y$."
This is what I have so far:
"Let $U \subseteq X$ and $V \subseteq Y$ be open in $(X,d_X)$ and $(Y,d_Y)$, respectively.
Then by definition, for all $u \in U$, there exists some $\epsilon_1>0$ such that $B_{d_X}(u,\epsilon_1) \subseteq U$ and for all $v \in V$, there exists some $\epsilon_2>0$ such that $B_{d_Y}(v,\epsilon_2) \subseteq V$.
Let $\epsilon=\max{\{\epsilon_1,\epsilon_2\}}$.
Additionally, let $(u_o,v_o) \in U \times V$."
I'm confused as to where to go from here. Any tips?
Comment: What is the product metric?
Comment: We're defining the product metric to be $d_{X \times Y}((x_1,y_1),(x_2,y_2))=\max{\{d_X(x_1,x_2),d_Y(y_1,y_2)\}}$.
Answer: If $u\in U$ and $v\in V$, take $\varepsilon>0$ such that $B_{d_X}(u,\varepsilon)\subset U$ and that $B_{d_Y}(u,\varepsilon)\subset V$. Then$$B_{d_{X\times Y}}\bigl((u,v),\varepsilon\bigr)\subset U\times V.$$That's so because, if $(x,t)\in X\times Y$,\begin{align}(x,y)\in B_{d_{X\times Y}}\bigl((u,v),\varepsilon\bigr)&\iff\max\{d_X(x,u),d_Y(y,v)\}<\varepsilon\\&\iff d_X(x,u),d_Y(y,v)<\varepsilon\\&\implies x\in U\wedge y\in V.\end{align}
Comment: @bzoll213 I've edited my answer, adding a few lines. Yes, it is all you need to do.
Comment: Would that be all that I need to add?
Comment: Thank you so much!
Comment: Should I keep what I have and just add this to it or revise my proof completely to something akin to what you wrote?
Comment: If you start like that, then the $\varepsilon$ that you should take is $\min\{\varepsilon_1,\varepsilon_2\}$.
Answer: You should start the prof by taking an arbitrary element $(u_0,v_0)$ of $U \times V$. We then get $u_o \in U$ and $v_0 \in V$. So there exist $\epsilon_1,\epsilon_2 >0$ such that $B_{d_X}(u_0,\epsilon_1) \subseteq U$ and $B_{d_Y}(v_0,\epsilon_2) \subseteq V$. Let $\epsilon=\min\{\epsilon_1,\epsilon_2\}$. Can you check now that this $\epsilon$ works?


Custom UIButton for Facebook Login

Question: I have been working on a little project, and I need people to sign in/log in using Facebook/Google. It has been working perfectly so far with Google's Firebase Auth.
I basically works with Facebook, so all the functionality is okay.
Now I would like to "style" it a bit, and give it a customised look. I can't seem to make that happen.
I have made a UIButton that I can move around, change shape of and basically control everything. I would like to make my UIButton do the exact same as the native Facebook LoginButton.
I went to Facebook's own documentation. I tried everything. I copy/pasted the code they have written, it gives multiple errors. I tried every tutorial I could find, nothing helped. One tutorial got me a bit of the way, but did not quite make it.
Facebook's code that I copied: https://developers.facebook.com/docs/swift/login
Thanks a lot in advance, I hope someone can help me out.

Here is my code, if that helps:
import UIKit
import FacebookLogin
import FacebookCore
import FBSDKLoginKit
import FBSDKCoreKit
import FirebaseAuth

class ViewController: UIViewController, FBSDKLoginButtonDelegate {

let loginButton: FBSDKLoginButton = FBSDKLoginButton()

@IBOutlet weak var SpinnerLogin: UIActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad()

    loginButton.isHidden = true

    FIRAuth.auth()?.addStateDidChangeListener { auth, user in
        if let user = user {
            // User is signed in.

            let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let homeViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "HomeView")

            self.present(homeViewController, animated: true, completion: nil)

        } else {
            // No user is signed in.

            self.loginButton.readPermissions = ["public_profile", "email", "user_friends" ]
            self.loginButton.center = self.view.center
            self.loginButton.delegate = self
            self.view.addSubview(self.loginButton)

            self.loginButton.isHidden = false

        }
    }

}

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

//Tells us if person is logged in
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {

    self.loginButton.isHidden = true

    if (error != nil) {
        //Handle error
        self.loginButton.isHidden = false
    }

    else if (result.isCancelled) {
        //Handle cancel event
        self.loginButton.isHidden = false

    }

    else {

    SpinnerLogin.startAnimating()

    let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)

    FIRAuth.auth()?.signIn(with: credential) { (user, error) in

        print("User Logged in to Facebook")
        print("You are now signed in to Firebase")
    }
    }
}

//Tells us if person logged out
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {

    print("User did log out")
}

}

Answer: I found a way to do it. I don't now if its recommended, but it works perfectly.

Add a UIView to your storyboard, and give it the shape and size that
you want.
Give the UIView a FBSDKLoginButton subclass - like this: UIView with FBSDKLoginButton Class

Now in your swift file, do like this:
@IBOutlet weak var viewFBLogin: FBSDKLoginButton! = FBSDKLoginButton()

In your viewDidLoad do this:
viewFBLogin.delegate = self

And then you can decide which permission you want and all that, I followed the Firebase Documentation so here is how it looks for me:
    override func viewDidLoad() {
    super.viewDidLoad()

    //THIS LINE IS SUPER IMPORTANT, OTHERWISE THE REST OF THE CODE WONT KNOW IF USER IS LOGGED IN OR OUT
    viewFBLogin.delegate = self

    viewFBLogin.layer.cornerRadius = 20

    FIRAuth.auth()?.addStateDidChangeListener { auth, user in
        if let user = user {
            // User is signed in.

            let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
            let homeViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "HomeView")

            self.present(homeViewController, animated: true, completion: nil)

        } else {
            // No user is signed in.

            self.viewFBLogin.readPermissions = ["public_profile", "email", "user_friends" ]
            self.viewFBLogin.isHidden = false

        }
    }

}

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

//Tells us if person is logged in - DOES NOT WORK WITHOUT DELEGATE UP TOP
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {

    self.viewFBLogin.isHidden = true

    if (error != nil) {
        //Handle error
        self.viewFBLogin.isHidden = false
    }

    else if (result.isCancelled) {
        //Handle cancel event
        self.viewFBLogin.isHidden = false

    }

    else {

    SpinnerLogin.startAnimating()

    let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)

    FIRAuth.auth()?.signIn(with: credential) { (user, error) in

        print("User Logged in to Facebook")
        print("You are now signed in to Firebase")
    }
    }
}

//Tells us if person logged out - DOES NOT WORK WITHOUT DELEGATE UP TOP
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {

    print("User did log out")
}

Hope that helps, if anybody was in the same situation as I was.

Custom UIButton for Facebook Login


How to run an app in Tomcat?

Question: I have put my project in tomcat_home/webapps/ directory. The structure is : project_name/WEB-INF/classes. in WEB-INF i have put my web.xml descriptor. The problem is that when i try to run the application, it doesn't find the files. The error is:
The requested resource () is not available.

My web.xml content is:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"

    version="2.4">
<servlet>
   <servlet-name>Chapter1 Servlet</servlet-name>
   <servlet-class>Ch1Servlet</servlet-class>
</servlet>

<servlet-mapping>
   <servlet-name>Chapter1 Servlet</servlet-name>
   <servlet-url>/Serv1</servlet-url>
</servlet-mapping>
</web-app>

I have also restarted the server, but it doesn't want to work.
Any suggestions?
Comment: Have you checked if application is deployed successfully from tomcat logs?. Can you remove the whitespace from servlet name and then recheck?
Answer: Does your servlet have a namespace. In the  tag you need to fully qualify the Ch1Servlet class, i.e. my.code.Ch1Servlet
--- Additional after reading comments -----
Ok, try this. Create a context for your webapp. Create a file named project_name.xml and put the following in it:
<Context path="/Serv1" docBase="webapps/project_name"
         reloadable="true" debug="0" privileged="true">
</Context>

Now put the xml file in the webapps directory.
If you are deploying a WAR then replace the docBase as "webapps/project_name.war"
Comment: It is in the default namspace
Comment: This is not enough - does the servlet have a package? If it does, the full path to the package should precede the servlet name, just as Adrian has said.
Comment: This does not matter, if you do not put your servlet into a package, tomcat will look for it on what it considers to be it's current directory. Put it in a package and reference the package from the servlet-class tag.
Comment: no matter what i do, it doesn't work. I packaged it, recompiled... Unsuccessfully
Comment: Are you trying to access resources in the constructor or init of your servlet. If so, are they referenced by the package they reside in?
Comment: the mistake was at  tag in . It must to be . Uuuuf... I beg your pardon:)
Comment: Whoa, should have spotted that myself.
Answer: You need to throw what you have away, start again and go through this very carefully:
http://tomcat.apache.org/tomcat-6.0-doc/appdev/index.html
What have you learned so far?

Your servlet .class needs to be in a package.  You should see WEB-INF/classes/com.foo.Bar.class if your class is Bar.jar with a package com.foo; at the top
Package your app into a WAR named MyApp and put it in /webapps to deploy it.
The URL needs to be http://localhost:8080/MyApp/Bar if you map com.foo.Bar to /Bar

Forcing people to make suggestions, and repeating that "it doesn't work", isn't going to get you where you need to be.
Answer: If you are using the default server.xml that comes with Tomcat, you should not have to alter it to just get your Web app running. Have you tried accessing it from the following URL: http://localhost:8080/project_name/
Answer: It looks like you need to put your servlet in a package, e.g.
com.me.Ch1Servlet.  Then change the servlet-class declaration to
<servlet-class>com.me.Ch1Servlet</servlet-class>
Comment: i have also done this after Adrian's post, but also doesn't work
Answer: How about http://localhost:8080/Serv1 without the webapp name in the URL?

How to run an app in Tomcat?


How to adapt Twitter Bootstrap´s css classes to drupal menus?

Question: I´m traying to adapt the Twitter´s Bootstrap top menu to Drupal menu system. Up until now, unsuccessfully. I´m using Drupal module nicemenus to show them in dropdowns.
This is the hand made menu list using Bootstrap´s css:

                Dropdown 1

 Item 1

 Item 2

Normal Menu Link without dropdown

And this is the Menu output with nicemenus, as you can see Bootstrap is so much easier to understand.

Link without Dropdowns

Dropdown Link 1

Item 1

Item 2

Item 3

Dropdown Link 2

Item 1

Item 2

I´ve installed menu_attributes module, but when I add to it some classes they are added to the  tag only. How could I transform those css classes programatically?
Doing a print_r(), I´ve found this:
                            [sidebar_second] => Array
                                (
                                    [nice_menus_1] => Array
                                        (
                                            [#markup] =>

Link 1 without Dropdown
Dropdown 1
Dropdown 2
Dropdown 3

                                            [#contextual_links] => Array
                                                (
                                                    [block] => Array
                                                        (
                                                            [0] => admin/structure/block/manage
                                                            [1] => Array
                                                                (
                                                                    [0] => nice_menus
                                                                    [1] => 1
                                                                )

                                                        )

                                                )

                                            [#block] => stdClass Object
                                                (
                                                    [module] => nice_menus
                                                    [delta] => 1
                                                    [theme] => liganet
                                                    [status] => 1
                                                    [weight] => -62
                                                    [region] => sidebar_second
                                                    [custom] => 0
                                                    [visibility] => 0
                                                    [pages] =>
                                                    [title] =>
                                                    [bid] => 744
                                                    [cache] => -1
                                                    [subject] =>
                                                )

I thought that it could be done with the parent menu variable printed in the page template and then printing the children vars inside the classes? How may I do that with php?
Thanks for your help!
Answer: How to add/remove classes from menu output
Add the three functions below to the file template.php in your theme folder. Make sure the function names start with the name of your theme. The suffix __main_menu indicates the machine name of the menu you want to alter. Once the functions are added to your file, clear all caches.
1 ) theme_menu_tree(). This adds the "nav" class to the
 element. If we left things here it would be applied to the parent and all child menus. Since we only want this applied to the parent, let's keep going.
function mytheme_menu_tree__main_menu($variables) {
  return '
' . $variables['tree'] . '
';
}

2 ) theme_menu_link(). We have added only two lines to the original function which are commented below. The first adds the "dropdown" class to any
 element that contains a child menu. The second declares a new theme wrapper specifically for the child menus.
You can optionally strip away existing classes with $element['#attributes']['class'] = 'dropdown'; (remove the empty square brackets).
function mytheme_menu_link__main_menu($variables){
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {

    // Add class to this list element.
    $element['#attributes']['class'][] = 'dropdown';

    // Declare a new theme wrapper for this list item's child menu.
    $element['#below']['#theme_wrappers'][0] = 'menu_tree__main_menu_children';

    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $sub_menu . "
\n";
}

3 ) Custom theme function. This is our custom implementation of theme_menu_tree that we just declared above. It adds the class "dropdown-menu" to all child menus.
function mytheme_menu_tree__main_menu_children($variables) {
  return '
' . $variables['tree']    . '
';
}

Notes:

Be warned that removing classes could alter the functionality of the menu!

This technique will only affect menu output; that is, everything between
..
 in the example pasted above. To remove the wrapper elements you should override block.tpl.php as described on this handbook page.

More helpful links:

About overriding themable output (Drupal.org Handbook)
Create a Foundation 5 'Top bar' menu in Drupal 7.x (a blog post of mine that uses the same technique, but for a Foundation menu)
Answer: Install Bootsrap theme and set this theme as base theme of your own theme. All menus will output as you need in this case, because Bootsrap theme has all rewrite functions


How to find correlation between two functions?

Question: Let's say I have two functions, $f$ and $g$.  Both take the same normally distributed random variable ($X$) as an input.
\begin{align}
f(X) &= X \\
g(X) &= X^2
\end{align}
How does one find the correlation between these two functions, or any two functions in general?
I'd like to do so closed form.  No simulation, no interpolation.
Edit:  Specified normal distribution.
Comment: What kind of correlation? Pearson? Pearson assumes normal distributions, and X^2 is not normally distributed, so I'm not sure what the value would be. Pearson would also make no sense if X has both positive and negative values, as the relationship of X and X^2 will be a non-monotonic curve. Also to note, any rank correlations will be perfect if all numbers of X are positive (or negative).
Comment: Pearson correlation, and not necessarily monotonic.  The "base" function is definitely normally distributed here, and therein is the basis for comparison.
Comment: Think of it this way...   Let's assume X is from the standard normal.  I can simulate f(X) and g(X) and find a Pearson's correlation of 0.  If I have a third function h(X)=X + .5X^2, I can find around an 80% correlation.  This value *is* meaningful in the sense that I would want to hedge an asset h(X) with the asset f(X).
Answer: For the given functions $X$ and $X^2$ with $X \sim(\mu,\sigma^2)$ being a normal
random variable, finding
$\operatorname{cov}(X,X^2)$ is relatively
easy, and then the (Pearson) correlation coefficient can be found as
$$\rho = \frac{\operatorname{cov}(X,X^2)}{\sqrt{\operatorname{var}(X)
\operatorname{var}(X^2)}}.$$
Note that
$\operatorname{cov}(X,X^2) = E[X\cdot X^2]-E[X]E[X^2]
= E[X^3]-E[X]E[X^2]$ where the values of all three expectations
can be found in numerous texts and tables as well as on
Wikipedia.
For example, $E[X^3] = \mu^3 + 3\mu\sigma^2$.
Similarly, $\operatorname{var}(X^2) = E[X^4]-\left(E[X^2]\right)^2$
also can be calculated using the known formulas for the
moments of a normal random variable.
Answer: If you apply a function to a random variable you get a new random variable (the function should be measurable for this to hold). Then you can proceed to calculate correlation in the usual manner. So if you take any $f$ and $g$ and normal variable $X$, the desired correlation is
$$cor(f(X),g(X))=\frac{cov(f(X),g(X))}{\sqrt{Var(f(X))}\sqrt{Var(g(X))}}$$
Now
\begin{align}
cov(f(X),g(X))&=E[f(X)g(X)]-E[f(X)]E[g(X)]\\
Var(f(X))&= E[f^2(X)]-E[f(X)]^2\\
Var(g(X))& = E[g^2(X)]-E[g(X)]^2
\end{align}
so you need to calculate 5 integrals: $E[(f\cdot g)(X)]$, $E[f(X)]$, $E[f^2(X)]$, $E[g(X)]$, $E[g^2(X)]$ to get the correlation. Even if the $X$ distribution is known and normal, there is no closed form solution for general $f$ and $g$. The particular case of $f(x)=x$ and $g(x)=x^2$ is covered by the answer of Dilip Sarwate. Since you can find closed formulas for moments of normal variables, it would be possible to derive the closed formula in the case of polynomial $f$ and $g$.
Comment: Both mpiktas and dilip sarwate had the answer I was looking for.  I found mpiktas to have just a little bit more information, so I marked their answer as the correct one.


Need to add a JS file into  using a custom module with custom twig template

Question: I have created a custom module and created a config page which we need to input the url on that page.
Created a twig template within my custom module:

In my .module file
<?php

/**
 * @file
 * Add the url to the header section.
 */

/**
 * Implments hook_page_attachments_alter().
 */
function custom_module_page_attachments_alter(array &$attachments) {

  $js_file_url = \Drupal::config(' custom_module.settings')->get('url');

  $renderable = [
    '#theme' => 'my_template',
    '#test_var' => 'test variable',
  ];

$attachments['#attached']['html_head'][] = [
    [
      '#theme'  => 'my_template',
      '#js_file_url'   => $js_file_url,
    ],
  ];

}

function  custom_module_theme($existing, $type, $theme, $path) {
  return [
    'my_template' => [
      'variables' => ['js_file_url' => NULL],
    ],
  ];
}

My output:
<></>

Expected Output is

How to get rid of empty tags =>  <>,
By default $attachments['#attached']['html_head'][] is adding the '#tag' even if i dont declare it.
Can someone help me, please.
Comment: This seems somewhat dangerous (user defined JS url), but https://www.drupal.org/project/drupal/issues/2752283
Comment: can we use #theme inside $attachments['#attached']['html_head'][] ..?
Comment: I'm wondering if the Twig template makes any sense here at all.
Answer: You can attach custom tags to any render array from where it bubbles up into the HTML head. In the following sample I'm adding structured data when a certain block is viewed. $value then contains what's being printed between the opening and closing script tag.
/**
 * Implements hook_block_view_BASE_BLOCK_ID_alter().
 */
function MYMODULE_block_view_system_breadcrumb_block_alter(array &$build, BlockPluginInterface $block) {

  // Get JSON-LD.
  if ($json_ld = \Drupal::service('easy_breadcrumb.structured_data_json_ld')
    ->value()) {

    // Prepare script tag.
    $structured_data = [
      '#tag' => 'script',
      '#attributes' => ['type' => 'application/ld+json'],
      '#value' => $json_ld,
    ];

    // Add script tag.
    $build['#attached']['html_head'][] = [
      $structured_data,
      'easy_breadcrumb_structured_data_json_ld',
    ];
  }
}

I hope you get the idea how this can easily be adjusted to get your custom snippet into the head. You can keep your logic in hook_page_attachments_alter but then let it look more like in the following snippet. Maybe you don't even need any #value at all.
/**
 * Implements hook_page_attachments_alter().
 */
function MYMODULE_page_attachments_alter(array &$attachments) {

  if ($js_file_url = \Drupal::config('MYMODULE.settings')->get('url')) {

    // Prepare script tag.
    $my_script = [
      '#tag' => 'script',
      '#attributes' => ['src' => $js_file_url],
      '#value' => 'test',
    ];

    // Add script tag.
    $attachments['#attached']['html_head'][] = [
      $my_script,
      'MYMODULE_my_script',
    ];
  }
}


Do I Need to Buy Multiple Windows Licenses When Virtualizing?

Question:
Possible Duplicate:
Can you help me with my software licensing question?

I am considering setting up VirtualBox or VMWare Workstation to run multiple instances of Windows XP. Do I need to have a unique XP license for each instance?
Answer: Yes, you do, a license is required regardless of whether you run on bare metal or in a VM.
Answer: Unless it's Windows Server. I believe Standard Edition allows one virtualized guest included. Enterprise Edition allows for four also.
Comment: To go with that Data Center allows you an unlimited number of Server OS Guests.
Answer: Careful.  Windows XP requires a full license for each instance unless you use VECD which is only applicable for employees or contractors working directly for you.
Windows Server licensing provides extra licenses but ONLY for Server editions.  Downlevel editions are included so that a Windows Server 2008 license includes Server 2003 and 2008, but client operating system are NOT included.  It's a bummer, I know.

Standard = 1 extra virtual server license on the same server
Enterprise = 4
Datacenter = unlimited

But not client OSes.


How to scope user selection

Question: I'm currently developing a Web Application that consists of different panels and areas.
One panel contains a huge table, another panel contains a description box, etc.
Usually, users can drag their mouse and select any range of text inside an html page.
I want the user to only be able to select text inside of one panel or up to a barrier.
For example, when the table is in focus, selecting text by mouse or hitting Ctrl-A should only select text inside of it. Not every selectable text on the page.

Not this text

Nor that

       Hitting Ctrl-A here should only select THIS text

I need to somehow define a barrier on a parent element (like the table panel) that prevents expanding the selection further up the DOM tree.

I consulted https://developer.mozilla.org/en-US/docs/Web/API/Selection and
https://w3c.github.io/selection-api/
I tried to use stopPropagation() on dragstart-events, but this doesn't seem to have any effect.
Answer: You can prevent the default selection with e.preventDefault() and create your own selection instead.
If your table contains input elements that can get the focus you can build in an extra check for that. That is not included in my example.

document.addEventListener('keydown', (e) => {
  if(e.ctrlKey && e.key === 'a') {
    //Prevent the default select all
    e.preventDefault();

    //Select only the contents of div#special-panel-including-big-table
    var targetEl = document.getElementById('special-panel-including-big-table');
    var range;
    if (window.getSelection && document.createRange) {
        var selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(targetEl);
        selection.removeAllRanges();
        selection.addRange(range);
    }
  }
});

Not this text

Nor that

       Hitting Ctrl-A here should only select THIS text

How to scope user selection


Equivalent query of "Select All"

Question: I have this query:
SELECT * pg_type;

What is its equivalent query in Drupal 7?
My code throws an error.
$query = db_select('pg_type', 't1', array('target' => 'import'));
$result = $query->execute();

Answer: SELECT * pg_type

isn't a valid SQL query; presumably you meant:
SELECT * FROM pg_type;

which in Drupal-ese is:
$query = db_select('pg_type', 't')->fields('t');

Output of the above:
SELECT t.*
FROM {pg_type} t

Equivalent query of "Select All"


React Router V4 - Components not rendering under

Question: I'm trying to turn a block of hardcoded <Route />s into something that's dynamically generated from a config variable. Eg.
From
<Router>
    <Switch>
        <Route path="/" component={Home} exact />
        <Route path="/about" component={About} />
        <Route path="/documents" component={Documents} exact />
        <Route path="/documents/faq" component={DocFAQ} />
        <Route path="/documents/translations" component={Translations} />
    </Switch>
</Router>

To
const routes = [
    {
        path: '/',
        component: Home,
        exact: true
    },
    {
        path: '/about',
        component: About
    },
    {
        path: '/documents',
        component: Documents,
        children: [
            {
                path: '/faq',
                component: DocFAQ
            },
            {
                path: '/translations',
                component: Translations
            }
        ]
    }
];

const RecursiveRoute = ({ route, parentPath = '' }) => {
    const path = parentPath + route.path;
    return (
        <React.Fragment>
            <Route path={path} exact={route.exact || (route.children != null)} component={route.component} />
            {route.children && route.children.map((childRoute, i) => <RecursiveRoute key={i} route={childRoute} parentPath={path} />)}
        </React.Fragment>
    );
};

const Routes = () => (
    <Router>
        <Switch>
            {routes.map((route, i) => <RecursiveRoute key={i} route={route} />)}
        </Switch>
    </Router>
);

This code generates exactly what I want when I take the mapping call outside of <Router>; eg. I can verify that it outputs the exact same code as the hardcoded block from before. When it's inside the <Switch> however, only the first route in the routes array is getting mapped--nothing else is generated. Putting logging statements inside <RecursiveRoute> confirms this.
Why is this and how do I fix it?
Another weird thing is that if I paste <RecursiveRoute>'s JSX right into the map statement, it works (except I can't make it recursive in this case):
<Switch>
    {routes.map((route, i) => <Route key={i} path={route.path} exact={route.exact || (route.children != null)} component={route.component} />)}
</Switch>

But if I keep it outsourced to another component, the mapping fails again.

[Edit] Solution:
Based on mehamasum's answer, changing <RecursiveRoute> from a component to a function solved this problem:
function generateRecursiveRoute(route, parentPath = '') {
    const path = parentPath + route.path;
    const routeHasChildren = (route.children != null);
    const baseHtml = <Route path={path} exact={route.exact || routeHasChildren} component={route.component} key={path} />;
    return !routeHasChildren ?
        baseHtml :
        <React.Fragment key={path}>
            {baseHtml}
            {route.children.map((childRoute) => generateRecursiveRoute(childRoute, path))}
        </React.Fragment>;
}

const Routes = () => (
    <Router>
        <Switch>
            {routes.map((route) => generateRecursiveRoute(route))}
        </Switch>
    </Router>
);

Comment: What do you mean by the 'mapping fails'? Some kind of error thrown?
Comment: As in "only the first route in the routes array is getting mapped--nothing else is generated". So in this example, only the Home route is generated.
Answer: Switch is implemented in such a way that you provide multiple Components as children and it will render the first Component's component with matching path. So if you provide something other than a Route as child (something that doesn't have those path and component props) you need to make sure you write your rendering logic in there. Because Switch doesn't know what to do here, as it sees no component or render prop associated with that child.
So when you were mapping to Routes directly they were working, but when you were mapping to RecursiveRoute it was failing. It had no path nor component on it, right?
I have updated your code a little bit so that the routes are directly rendered as children of Switch:
// refactor of RecursiveRoute to
// use it as an utility function, not as component

const getRecursiveRoute = route => {
  if (route.children) {
    const RootComponent = route.component;
    return (
      <Route
        key={route.path}
        path={route.path}
        render={props => {
          return (
            <React.Fragment>
              {/* render the root matching component*/}
              <RootComponent {...props} />

              {/* render the subroutes */}
              {/* TODO: consider having a Switch here too */}

              {route.children.map(route =>
                getRecursiveRoute({
                  ...route,
                  path: props.match.url + route.path
                })
              )}
            </React.Fragment>
          );
        }}
      />
    );
  }
  return (
    <Route
      key={route.path}
      path={route.path}
      exact={route.exact || route.children != null}
      component={route.component}
    />
  );
};

const Routes = () => {
  return (
    <Router>
      <Switch>{routes.map(route => getRecursiveRoute(route))}</Switch>
    </Router>
  );
};

You might have to fix some edge cases about exact routing. Hope it helps.
Comment: This makes sense now, thanks! I found that simply changing `` into a function (eg. without using render) worked just fine as well.


Getting rid of a huge categorical factor in multiple regression

Question: I have a large regression problem with a lot of cases, but relatively few independent variables. One of them is a categorical factor with thousands of levels. Robust regression runs forever. In some cases the large number of dummy variables becomes too sparse to calculate with even "normal" lm.
What would usually make sense is to somehow calculate the average for each level of the factor, then adjust the dependent variable accordingly, and do the regression without the big factor. A colleague of mine could remember there is a two-letter R function that does that automatically, but he cannot remember the two letter combination.
Any help would be greatly appreciated.
Comment: Maybe you're thinking of `plm`?
Comment: How would plm help?
Comment: It sweeps the categorical fixed effects out of your model.
Comment: That seems like a good idea!
Comment: The package 'lfe' will also handle this problem. It implements a method for projecting out factors from OLS-regressions, the method is described in this forthcoming article: http://dx.doi.org/10.1016/j.csda.2013.03.024
Answer: I would think lme4 would be highly appropriate for this.  Treat your huge categorical factor as a practical random effect.  I won't go into the theoretical definitions.  Alternatively, use sparse.model.matrix() from Matrix to build the design frame and then pass that into glmnet() from glmnet package.  (lme4 naturally builds the sparse design matrix so you don't need to use the sparse.model.matrix() before you go into it.)
If you really want to do the 'average for each level' trick, then be sure to calculate each observation's average excluding itself and include a few extra observations with each factor level at the population mean.  Then use this derived variable as a feature in your models instead of the categorical variable.  If the factor was the only feature, then this result would be identical to lme4 or glmnet (assuming you solved for how many average observations to add).
There are a few blog entries out there that call the 'average for each level' trick impact coding.  Also from my experience, if there is a strong dense feature, you might want to fit a simple model on that feature and impact code the residuals by level of the huge categorical factor instead of the pure response.
As mentioned above, this is more practical advice.  Other people will probably come along with some stronger theoretical advice.
Comment: I try to calculate each observation's category average excluding itself and use it in the model. It does not work so well, as out-of-sample prediction is poor (compared to simply using the big factor). Did I get your technique right?
Comment: Did you do the second part and add a handful of fake observations at each level with the mean population response?  This is analogous to ridging / L2-Penalties.  You might have to tune how many pop-mean dummies to add.  Having said that, I also highly recommend lme4.  It's formula interface is very simple: `y~x.other+(1|x.huge.factor)`.
Comment: Clarification: I do use sparse matrices currently with MatrixModels / lm.fit.sparse. The estimates I get from lme4 are very similar. However, my eventual goal is to get rid of the big factors to (also) be able to do more effective outlier detection or robust regression. So in such case, would you recommend on the "ridging" strategy?
Comment: Well, in high enough dimensions, every point is an outlier.  But in simple terms, if you want to do more complex analysis suited to dense design matrices, then yea, ridging the level averages would probably work out okay.
Comment: I just re-read this and saw reference to `lm.fit.sparse()`.  I think I could safely say that `glmnet` would almost always be a better option than pure least-squares.  Especially when you have such a sparse design matrix.


How to swap views using a swipe gesture XCode

Question: I am using XCode to develop a Cocoa touch application for the iOS platform but have had trouble finding out how to get a swipe gesture implemented that would allow the user to swipe their finger left or right to change to a new ViewController (nib/xib file). I have done a swapView IBAction using a button and modal transitioning and I have read about Apple's TouchGestureRecognizer but I don't know how to implement a swipe action that would allow a view change.
I do NOT want to use a scroll view, as I have several dozen view controllers, that I want the user to be able to swipe through.
Here is an example:
First View Controller.xib:
SwipeRight- Go to second View Controller.xib
Second View Controller.xib:
SwipeLeft- Go to first View Controller.xib
SwipeRight- Go to third View Controller.xib
etc, etc
I have not used UISwipe/Touch Gestures before but I have used an IBAction method to switch views using a button with Modal Transitioning (see below):
-(IBAction)swapViews; {
    SecondViewController *second2 =[[SecondViewController alloc initWithNibName:@"SecondViewController" bundle:nil];
    second2.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:second2 animated:YES];
    [second2 release];
}

Is using a swipe to do a similar method formatted differently? If so, how do I sort this out and format it.
Thank You
Edit - Answer as Per Comment on Question
Place this in your viewDidLoad
UISwipeGestureRecognizer *swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeLeftDetected:)];
swipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeRecognizer];
[swipeRecognizer release];

Then add a selector as by pasting the following code into your main...
- (IBAction)swipeLeftDetected:(UIGestureRecognizer *)sender {
    NC2ViewController *second2 =[[NC2ViewController alloc] initWithNibName:@"NC2ViewController" bundle:nil];
    second2.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:second2 animated:YES];
    [second2 release];
}

Then just make sure you import the otherViewController you are swapping to using
#import "SecondViewController"

at the top of your main file. Hope this helps.
End Edit
Comment: Hi AppleFanBoy, Were you able to implement UIGesture to swap views? I have tried the same approach but have been unsuccessful. The previous NIB does not release. Can you please post code if it is working. Thanks.
Comment: I was successful and could get it to work
Comment: Place this in your viewDidLoad;  {UISwipeGestureRecognizer *swipeRecognizer =
  [[UISwipeGestureRecognizer alloc]  initWithTarget:self
               action:@selector(swipeLeftDetected:)];
  swipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
  [self.view addGestureRecognizer:swipeRecognizer];
  [swipeRecognizer release];

 }
Comment: Then add a selector as by pasting the following code into your main...

- (IBAction)swipeLeftDetected:(UIGestureRecognizer *)sender {

 NC2ViewController *second2 =[[NC2ViewController alloc] initWithNibName:@"NC2ViewController" bundle:nil];
 second2.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
 [self presentModalViewController:second2 animated:YES];
 [second2 release];

}
Comment: Then just make sure you import the otherViewController you are swapping to using #import "SecondViewController" at the top of your main file. Hope this helps.
Comment: Sorry for not replying to this in a long time.
Comment: Thanks AppleFanBoy for these tips.  Exactly what I was looking for aswell !
Comment: @AppleFanBoy you can update your question adding the solution. Thank you anyways, it is working.
Answer: This sounds like a perfect time to use UIGestureRecognizer or, more specifically, UISwipeGestureRecognizer.
For more info on how to use them, read up in the Gesture Recognizers section of the Event Handling Guide.
Answer: Lets assume you want to swipe left to bring up another view from the right.
In the storyboard, drag and drop a swipe gesture recognizer. It will make an icon below the view controller; drag this icon and drop onto the ViewController you want to navigate to. This will add a segue, select custom segue. Then create a UIStoryboardSegue class. Add the following code:
- (void)perform {
    UIViewController* source = (UIViewController *)self.sourceViewController;
    UIViewController* destination = (UIViewController *)self.destinationViewController;

    CGRect sourceFrame = source.view.frame;
    sourceFrame.origin.x = -sourceFrame.size.width;

    CGRect destFrame = destination.view.frame;
    destFrame.origin.x = destination.view.frame.size.width;
    destination.view.frame = destFrame;

    destFrame.origin.x = 0;

    [source.view.superview addSubview:destination.view];

    [UIView animateWithDuration:0.5
                     animations:^{
                         source.view.frame = sourceFrame;
                         destination.view.frame = destFrame;
                     }
                     completion:^(BOOL finished) {
                         UIWindow *window = source.view.window;
                         [window setRootViewController:destination];
                     }];
}


Pandas ValueError when attempting to select data using a boolean operator

Question: I'm trying to use this code to create a new Pandas DataFrame consisting of rows where both of my columns of interest have values.
sve2_hz = sve2_all[[(sve2_all[' Q l/s'].notnull()) & (sve2_all['Flow_mm/day'].notnull())]]

I've also tried changing removing the inner brackets:
sve2_hz = sve2_all[[sve2_all[' Q l/s'].notnull() & sve2_all['Flow_mm/day'].notnull()]]

However, Pandas throws up the following error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-110-0f3ba1c28b18> in <module>()
----> 1 sve2_hz = sve2_all[[(sve2_all[' Q l/s'].notnull()) & (sve2_all['Flow_mm/day'].notnull())]]
      2 print sve2_hz.head()

C:\Users\AppData\Local\Enthought\Canopy32\User\lib\site-packages\pandas\core\frame.pyc in __getitem__(self, key)
   1650         if isinstance(key, (Series, np.ndarray, list)):
   1651             # either boolean or fancy integer index
-> 1652             return self._getitem_array(key)
   1653         elif isinstance(key, DataFrame):
   1654             return self._getitem_frame(key)

C:\Users\AppData\Local\Enthought\Canopy32\User\lib\site-packages\pandas\core\frame.pyc in _getitem_array(self, key)
   1687             elif len(key) != len(self.index):
   1688                 raise ValueError('Item wrong length %d instead of %d.' %
-> 1689                                  (len(key), len(self.index)))
   1690             # _check_bool_indexer will throw exception if Series key cannot
   1691             # be reindexed to match DataFrame rows

ValueError: Item wrong length 1 instead of 16636.

Could somebody explain what the error message means? In particular the comment "Series key cannot be reindexed to match DataFrame rows".
Comment: could you try removing the inner square braces:`sve2_all[(sve2_all[' Q l/s'].notnull()) & (sve2_all['Flow_mm/day'].notnull())]`
Comment: Thanks, your suggestion works. I'd tried that originally but it returned an empty `DataFrame` so I'd assumed I'd made a mistake. Further investigation reveal that the problem is with my index, it's non-unique and non-monotonic so there were no matches.
Comment: Glad I helped not worth an answer I feel
Answer: The solution as proposed by @EdChum was to remove the inner set of brackets:
sve2_all[(sve2_all[' Q l/s'].notnull()) & (sve2_all['Flow_mm/day'].notnull())]


Compute the sum $\sum_{k=0}^{n} (-1)^k \binom{n}{k}^3$

Question: I have to calculate $\sum_{k=0}^{n} (-1)^k \binom{n}{k}^3$. I proved that for odd $n$ this sum equals to $0$ ($\binom{n}{k}$ and $\binom{n}{n-k}$ cancel each other out), but I have no idea how to approach an even $n$ case. Thanks!
Comment: The value is given by Dixon's identity (https://en.wikipedia.org/wiki/Dixon%27s_identity), a corollary of the MacMahon Master Theorem (https://en.wikipedia.org/wiki/MacMahon_Master_theorem). The value for even integers is
$$\sum_{k=0}^{2n} (-1)^k\binom{2n}{k}^3=(-1)^n\frac{(3n)!}{(n!)^3}$$
I figure you may also be able to prove this result via induction.
Comment: I typed the sequence into [OEIS](http://oeis.org/A245086) and something called Chebyshev Polynomials popped up
Comment: Thanks, Jacob. That works
Answer: If you already know about hypergoemetric functions
$$\sum_{k=0}^{n} (-1)^k \binom{n}{k}^3 x^k=\, _3F_2(-n,-n,-n;1,1;x)$$ Making $x=1$ and using Pochhamer symbols
$$\, _3F_2(-n,-n,-n;1,1;1)=\frac{(1-n)_n \left(\frac{n}{2}+1\right)_n}{(1)_n \left(1-\frac{n}{2}\right)_n}=\frac{\sqrt{\pi }\, 2^n\,\Gamma \left(\frac{3 n+2}{2}\right)}{\Gamma
   \left(\frac{1-n}{2}\right) \Gamma \left(\frac{n+1}{2}\right)^2 \Gamma (n+1)}$$ which is zero if $n$ is odd. If $n=2m$
$$\frac{\sqrt{\pi }\ 4^m \,\Gamma (3 m+1)}{\Gamma \left(\frac{1-2m}{2}\right) \Gamma (m+1)^2 \Gamma (2m+1)}=(-1)^m\frac{(3m)!}{(m!)^3}$$ which is Dixon's identity


Is spacing between strings and fret board rounding important for humbucker pickups?

Question: Is spacing between strings at the bridge and fret board radius important for humbucker pickups proper sound?
I made a simple guitar with narrow (10 mm between strings) and flat fretboard. (I originally wanted to build pickups myself, but I still have to wait to get my coil delivered and I'm not sure about results).
I think I made a mistake not taking available pickups in local stores into account when I started my build. As I see on pictures EMG or SD pickups (most popular as I can tell from my research) have about 12 mm spacing between magnets so that each magnet is placed exactly below corresponding string. Also magnets aligned vertically to match radius fret boards.
Right now I want to purchase EMG 85 for bridge or EMG 60/81 for neck (nothing else available in local stores). But I'm confused because my fret board is completely flat and spacing doesn't match. I've seen people put EMGs on 3-string guitars and they sound somehow (can't tell if it's good). But I want to get something close to real sound of an electric guitar (I understand how immature my construction is), not some noise of a wooden stick with strings amplified and scaled up.
So again is spacing between strings at the bridge and fret board radius important for humbucker pickups proper sound? In other words can I buy EMG and enjoy it on my narrow build? Or different spacing and flat bridge is a showstopper?
P.S. I have never had guitar so don't judge me too hard :-)
Comment: those little round things are not always "the magnets," but rather something touching the magnetic core. They might be made of magnetic material, but they are often just screws. My old Yamaha SC had single coil pickups with a single bar across the face, called a "blade style" pickup. The blade was steel and it touched a magnet at the bottom of the pickup assembly.
Comment: Vertical space between the strings and the pickups is what matters so far as electrical signal strength goes.  Spacing off the fingerboard mostly affects the force needed to finger notes and the risk of buzzing if a vibrating string hits the fingerboard.  But keep in mind that all electric guitars are basically oscillator sources for synthesizers (e.g. stomp-board switches).
Comment: @Yorik I agree, I've seen different builds on youtube, usually it's simply steel with magnet bar beneath (seems it's cheaper than round magnet bars). I called them magnets for clarity.
Comment: Can commenters please not leave answers in the comments. Yorik, Carl please incorporate some of that knowledge in an answer.
Answer: In re-reading your post, I am uncertain which distance you mean, so I'll leave my previous answer (which was about distance between strings and pickups) and I'll add a new one below on string spacing:
While the distance between the strings and the pole pieces does have an effect on the tone, you can use them quite happily across an extremely wide range and it will still sound good. And by wide range, I mean anything from 1 or 2mm to even as far as 10mm.
At really short distances, you run the risk of hitting the pole pieces, which sounds bad, and of losing sustain, as the magnetic drag from the pickup drains energy from the string quickly.
At the other extreme, you don't get as high a signal, so you will have to boost the gain more, and will experience more noise as a result.
The tone does vary with different distances, and we have some posts here on the exact distances that are recommended for a professional for each pole piece (down to fractions of a millimetre in order to get phases correct etc) but that requires your guitar to be extremely well built to tight tolerances, so I wouldn't worry about that if I were you.
If you do have adjustable pole pieces, you can use them, but if not - don't be concerned. See what it sounds like.
If your string spacing doesn't match your pickups this is really not a problem at all. What guitar manufacturers do, and what I learnt very early on when I made my first electric guitar, is that you can angle your pickups so they match the string spacing if you have a non-standard spacing.
(I have just checked 9 of my guitars and they all have 10mm string spacing except one, which is 11mm and one which is 8mm. And that goes for 6 and 7 string guitars. So you really shouldn't have a problem)
Comment: Thank you for extended reply. I actually meant both X and Y axis spacing. I didn't know that adjustable pole pieces exist. So you're right I was wondering about Y spacing between poles and strings first and then about X spacing between each string. Angled pickup idea seems to be a good solution to me.
Comment: I want to make it clear for myself: is it necessary to angle pickup to match horizontal (X axis) spacing between individual strings?
Comment: No, it isn't absolutely necessary, as you can see by the way you can still hear the note even if you bend it away from the pole piece. It just helps with getting the maximum output signal from your strings


How do I implement the param startYear and endYear?

Question: I have a hard time understanding of how to implement the startYear and the endYear params. I open the file name then it reads the data. Then it will read the user's inputs for state, gender, startYear, and endYear. As what I have it looks at the gender and if it matches the input then it goes on the startYear and if it matches then it will append to the list.
Get the top names.
:param state (str): The state, e.g. 'NY'
:param gender (str): The gender, e.g. 'F'
:param startYear (int): The starting year, e.g. 1969
:param endYear (int): The ending year, e.g. 2010
:return: The list of top Name objects
:rtype: list

def getTopNames(state, gender, startYear, endYear):

    fileName = 'data/' + state + '.TXT'

    topName = []

    with open(fileName) as f:
        for line in f:
            loon = line.split()
            if loon[1] == gender:
                 if line[2] == startYear:
                    Name += line[3]

            topName.append(createName(loon[0], loon[1], int(loon[2]), int(loon[3])))
    return topName

Comment: What exactly is your question?
Comment: Please clarify your question and format your post properly.
Answer: If startYear is an integer (as suggested by your parameter list), then you need to convert it to a string before you can meaningfully compare it with one:
>>> startYear = 1999
>>> startYear == "1999"
False
>>> startYear = str(startYear)
>>> startYear == "1999"
True

Furthermore, I suspect that you meant
if loon[2] == startYear: # instead of line[2] which would be a single character

Lastly, no need to nest the ifs:
if loon[1] == gender and loon[2] == startYear:
    Name += loon[3]


Normalizing to zero mean and unit variance before regression

Question: I'm new to regression (vector autoregression), and recently encountered the following issue:

If I use raw dependent and independent variables to do the regression, the $R^2$, DW-d test and standard error of estimate for each dependent variable are quite good. The $R^2$ is above $95\%$.
However, When the dependent and independent variables are normalized to zero mean and unit variables (column normalized), these measures got worse. The $R^2$ ranges from $60\%-90\%$.

So what happened after I normalized the data?
Comment: I don't think it is possible for the $R^2$ to change.  You didn't state the reason for normalization.  I can't think of any.
Answer: Frank Harrell is right, it's not possible for the R2 to change, unless you've done something unusual like ... removed the intercept from your regression.  See for yourself with this R-fiddle.
My suggestion?  Put the intercept back in.  See, for example, "Regression through the Origin and Its Pitfalls".


onBeforeUnload and node.js

Question: I am new to node.js. Is it possible to use onbeforeunload in node.js? If yes, can "no script" plugin for firefox will not block script created by node.js? I always want to notify my visitors using onbeforeunload before leaving the page with forms not yet filled up w/ necessary information.
Answer: Node is backend code. Think of it like PHP but JavaScript.
The frontend is not aware of what language the backend is running. If a user is blocking scripts from running then all scripts, hard-coded on a page or placed there when Node renders it, will be blocked.

onBeforeUnload and node.js


How to set i/o priority for nfs client processes?

Question: The configuration is: A linux server and a nas box (netgear) acting as nfs server.
It is easy for a single process on the linux server to use all i/o bandwidth by simply copying a file from the nfs share to the nfs share. The i/o channel is jammed and all other processes on the server will nearly halt waiting for i/o. Load grows up to 10-20 (four cores), more and more pdflush processes appear... until someone stopps the file copy.
How can I limit the i/o bandwidth the cp process uses? nice will not help of course, but also ionice -c3 has no effect. Does ionice affect nfs mounts at all? Is there something like nfsnice ?
Answer: What are your "rsize" and "wsize" values set to?
Normally, modern linux NFS clients negotiate the maximum values with the server, but sometimes, they can end up way off base. For example, we had rsize=1m,wsize=1m in /proc/mounts, not knowing the NAS being unable to support more than 32768. Same slowliness, same effect of load skyrocketing as you describe.
Setting both values down to 32k immediately solved the slowliness and the rising load for us, desktop remained perfectly responsive even while copying gigabytes per NFS. And we have our home directories on NFS...
Perhaps your NAS's NFS server implementation does a little "show off" by offering more size than it can chew...?
Cheers
Answer: This seems like the Netgear NAS is not keeping up and is causing blocked I/O. What does the NAS look like? How many drives? What does the RAID config look like? This appears to be a server-side issue.
Comment: The configuraton ist "RAID X", a proprietary netgear level, with 3 1tb disks resulting in 2tb capacity (similar to raid5). The whole disk space is dedicated to the nfs share.
Comment: It may be a server-side issue, but still with only one process accessing the nfs share, things work quite well, but as soon as we have more processes, some tend to hang. A `nfsnice` command / api might still help...
Comment: Do you have any way to see the CPU utilization of the Netgear or its disk activity during the period of blocked I/O on the NFS client?


Removing outliers and calculating a "lowest" attainable price from a pre-determined/fixed time series of prices

Question: Just a foreword, I'm not a mathematician or otherwise statistically skilled. I know my way around calculating standard deviations, but it's all self taught. I'm a programmer with limited stats knowledge.

Now, Assume that you run a "Widget Rental" website, and on your application you allow owners of "Widgets" to rent them out. You let the widget owners create seasons, (such as May - June, and August - September ), and then pick a price that it would cost to rent out the Widget during that time period.
With the prices that are entered, I want to be able to :

Sort all widgets by "lowest price" available, so low-to-high in a result list of all widgets.
Provide a "From price" for a widget. That is to say, "You can rent this widget for $XXX per day".

Each widget can have a different price based on the time of year. Some widgets will have dozens of different prices depending on the season as you get "high" seasons and "low" seasons.
However, the sellers of the "Widgets" are especially mischievous, and have realised that if they set their widget to be really expensive for one day of the year, and also really cheap one day of the year, then they can easily appear at the low and high sort ranges. And they are also using this to manipulate their "from Price".
Currently, I took a very naive solution in order to calculate the "lowest price" for a Widget, which is to just take the lowest( N ) value from a dataset.
What I would like to is to get a "lowest from price" for a widget, which accurately portrays the price which it could be rented from.. and remove the lower/higher-band outliers.
Take a look at this chart... with values...

X Axis - Time (each significant interval is a day)
Y Axis - Price

The X axis is time, and the Y axis is the price. Now, this contains a normal distribution, and there aren't any real statistical outliers in that dataset. It's common to see the price between the lowest value and the upper value to fluctuate as much as 200% or a few standard deviations.
However, take a look at this second chart... It contains a single day tariff, which is only 20 ēuros...

I've played around with using Grubbs test and it seems to work quite well if you have a small dataset and don't take into account the duration of a date range. However, once you start trying to throw in a 3 days for a widget which is $1, it doesn't work well for removing the 3 clear outliers...
The important thing is that I want to get a "from price". That is to say, I want to be able to say, "You can rent this widget from XXXX". So it should be reflect the overall pricing taken as a whole and ignore clear outliers.
I'm going to implement this in PHP, so I don't have any amazing statistical tools at my disposal other than the core math libraries.
Answer: Since this value will not be used for statistical testing or any further analysis, I am not sure that going through all the trouble of thinking about what is or is not an outlier is necessary. It is a much more complex question than you might suppose and, in fact, in many cases not a recommended approach. Note that any number you might come up with is not as easily interpretable as the minimum price and therefore not more legitimate than any other as the "right" summary, because it necessarily results from some assumptions about what is "normal" variation.
As a low tech alternative, why not take the median and be done with it? That way, you get a rough idea of the price that cannot be arbitrarily manipulated by changing the price on a single day. Some more exotic things like the "Winsorized mean" might also be relevant.
One scenario in which the median is less useful is a comparison between (A) a widget you can rent for 10\$ a day for 182 days of the year and 100\$/day for another 182 days and 50\$/day for the last remaining day and (B) a widget available for 50\$/day all year round. The median price per day is the same but the actual price will differ depending on the period you want to rent the widget. Of course, you could create similar scenarios for the mean or the Winsorized mean. Fundamentally a single number cannot always capture the whole price distribution or correctly reflect each potential renter's situation.
Yet another solution would be to order widgets using the highest end of their price range (i.e. starting with the widget with the lowest highest daily price – hope that makes sense) or display the whole range ("Rent it between x and y\$/day") or a little graph so that "cheaters" can be spotted immediately by the users. Basically, deal with this as a design problem rather than a purely statistical one.
Comment: Thanks for your input. I like the winsorized mean idea. This would definitely work better than a median value. I have thought about using rent between `$X` - `$Y`.. will give more thought.
Answer: To add to Gael's response, you could calculate the standard deviation for each widget price and then say that the price is usually between one standard deviation below and above the mean, which would be 67% of the cases. Obviously, you would use the actual values rather than the term standard deviation.  Alternately, you could use a range of two SDs above and below if preferred, or some other range such as 80% of the time.
Comment: 67% here is presumably an echo of the 68.3% or so of cases being within 1 SD of the mean for a normal distribution; but that's not a universal result. The key point is that means and SDs are themselves typically inflated by outliers, so do not provide resistant criteria, which are needed here.


Como extrair o número da semana do mês no R?

Question: Estou com dificuldades em extrair o número da semana do mês de uma data específica.
Exemplo:
hoje = Sys.Date()
print(hoje)

[1] "2019-02-11"

No exemplo da data acima, hoje seria a 2ª semana do mês.
Eu sei que:
wday() #extrai o dia da semana.
mday() #extrai o dia do mês.
month() #extrai o mês.

Mas como posso usar o R para extrair de hoje a semana do mês?
Answer: Você pode usar a função lubridate::day em conjunto com a função ceiling:
library(lubridate)

hoje<-Sys.Date() # Sys.Date retorna a data de hoje
[1] "2019-02-11"

day(hoje) # day retorna o dia do mês
[1] 11

day(hoje)/7 # dividir o dia pelo número de dias de uma semana (7)
[1] 1.571429

ceiling(day(hoje)/7) # retorna a semana do mês a qual a data está
[1] 2

Comment: Funcionou perfeitamente. Eu havia confundido a quantidade de semanas no mês, mas já corrigi a pergunta.