What are the differences between tests for overidentification in 2SLS

Question: I am using 2SLS for my research and I want to test for overidentification. I started out with the Hausman test of which I have a reasonable grasp.
The problem I have is that from the Hausman and the Sargan Test I am getting very different results.
The Sargan test is done by ivmodel from library(ivmodel). I copied the Hausman test from "Using R for Introductory Econometrics" page 226, by Florian Heiss.
[1] "############################################################"
[1] "***Hausman Test for Overidentification***"
[1] "############################################################"
[1] "***R2***"
[1] 0.0031
[1] "***Number of observations (nobs)***"
[1] 8937
[1] "***nobs*R2***"
[1] 28
[1] "***p-value***"
[1] 0.00000015

Sargan Test Result:

Sargan Test Statistics=0.31, df=1, p-value is 0.6

On top of this I am also using ivtobit from Stata, which provides a Wald test of exogeneity.
Lastly I read about a fourth which is the Hansen J statistic.
What is the difference between all of these tests?
Comment: OK. But that would help spell out possible differences, such as dealing with heteroskedasticity in the weighting matrix of the Sargan statistic etc.
Comment: Regarding the [tag:two-step-estimation] tag: if I remember correctly, algebraically 2SLS is actually a single-stage procedure.
Comment: Can you post a MWE example of what you did exactly in the two tests, preferably using publicly available data, like in Heiss' book?
Comment: Hey Christoph, thank you for your comment. I am not really worried about the code. I am more interested in the conceptual differences.
Answer: There are a lot of questions here, so I'll first give an overview, and then explain a bit more. You have 4 tests you're asking about: Hausman test, Sargan test, a Wald test of exogeneity, and a Hansen J Test. To fix some notation, let $Z$ be a vector of instruments, and consider $Y = \beta_1 X_1 + \beta_2 X_2 + e$, where $X_1$ are exogenous variables you include in the model, and $X_2$ are endogenous, and you wish to use $Z$ instruments for $X_2$. Sometimes I will use $X = (X_1,X_2)$ as well. In what follows, I will describe each test, and then provide intuition and an approach. I may stray from my notation during the intuition parts, but tried to stick to it during the approach parts.
Before beginning, the TL;DR is that Wald and Hausmann test for exogeneity of $X$ (assuming exogeneity of $Z$), and Hansen's J and Sargan test for exogeneity of $Z$ (assuming you have more instruments than endogenous variables). Wald and Hausmann are very similar, but Wald is often better than Hausmann, and Sargan is a simpler version of Hansen's J used with TSLS (Hansen's J is used with IV-GMM). Since Hausman and the Sargan test different things, it makes sense you get different results.
Here's an explanation of what each test basically does:
Wald test of exogeneity: You assume that the instruments $Z$ satisfy exogeneity, and you test if $X_2$ may actually be exogenous.
Intuition: You have a valid instrument $Z$ (this assumption is key) for some variable $X$, and the first stage basically fits $X = \hat{\alpha} Z + \hat{e}$, and intuitively, in TSLS, we replace $X$ with $\hat{\alpha}Z$ in the second stage, which is the part of $X$ that is predicted by $Z$. Now what's $\hat{e}$? Well it's the part of $X$ that is unexplained by $Z$. If we ran a regression of $Y$ on $\hat{e}$. and find $\hat{e}$ has no effect on $Y$, then the part of $X$ that explains $Y$ is basically accounted for by $\hat{\alpha}Z$, but since $Z$ is exogenous by assumption, then $X$'s effect on $Y$ is a combination of the $Z$ fitted part and the $Z$ unfitted part, but we just found out that the unfitted part does not matter, and so $X$ is actually exogenous for all intents and purposes: the only part of it that matters is the part explained by $Z$, and $Z$ itself is exogenous, so $X$ must be exogenous. In such a case, you don't have to use IV and can just run OLS, which is more efficient.
Approach: we run the regression $Y = \delta_1 X + \delta_2\text{resid}(X_2) + \epsilon$, where $\text{resid}(X_2)$ are the residuals from the first stage regression of $X_2$ on $Z$. Then the exogeneity test is a Wald test that $\delta_2 = 0$ (ie jointly testing that all coefficients in the vector $\delta_2$ are $0$). Rejecting the test means that $X_2$ is not exogenous.
Hausman's test for endogeneity: This test is very similar to the above Wald test, and should be quite similar (I think exactly the same) under homoscedasticity. It is not used because we don't want to necessarily impose such an assumption, and because it involves a generalized inversion of a matrix that is often hard to calculate numerically. So we instead use a Wald test as above.
Intuition: Same as Wald test above.
Approach: First get first stage of TSLS and get the residuals $r$. Then run a regression $Y = \beta X + \delta r$ and test if $\delta = 0$. If significantly different, $(X_1,X_2)$ is not exogenous, and you should use TSLS, otherwise you can use the more efficient OLS. Note that unlike Wald test, the first stage and residuals are for all $(X_1,X_2)$ using $(X_1,Z)$, not just $X_2$.
Hansen's J: If we have more instruments than endogenous variables, i.e. $dim(Z) > dim(X_2)$, then we can test if all instruments are exogenous assuming that at least one of them is exogenous.
Intuition: If $dim(Z) > dim(X_2)$, we have more instruments than we need, and so we can actually use some of them for testing purposes instead of using them for estimation. I'm not super sure how to give an intuitive explanation here, but basically if we have more instruments then needed, TSLS will use all these instruments to build a set of instruments of $dim(X_2)$, and so I can take the residuals of TSLS from using this 'reduced' set of instruments, and then run a regression of these residuals (denoted $r_{TSLS}$) on $Z$. If $dim(Z) = dim(X_2)$, then by construction the coefficient of such a regression will be $0$, i.e. $r_{TSLS} = \hat{\alpha}Z$ will always result in $\hat{\alpha} = 0$, and so we don't learn anything. In contrast, if $dim(Z) > dim(X_2)$, then this need not be the case, but if the instruments truly were exogenous, then it should still be $0$. This is what we are testing here.
Approach: This is really used with IV-GMM, which is not what you are doing, so I don't know how much you want to know about this. As I'll next explain, the Sargan test is basically the simplified version of this test used with TSLS (the analogy is typically as follows: IV is to GMM  as Sargan's test is to Hansen's J test).
Sargan: Very similar to Hansen's J. We use it to test exogeneity of instruments assuming one is at least exogenous, when we have more instruments than $X_2$ endogenous variables. It is popular when performing TSLS. Following on comment below, it seems that Hausmann's test for overidentification, as defined by OP as in Section 15.5 of Wooldridge's Introductory Econometrics, is also defined as this test.
Intuition: Same as Hansen's J.
Approach: If we assume homoskedasticity, the Sargan's test is a special case of Hansen's J test. We first run TSLS with all instruments, and get the residuals, and then regress these on the instruments. The sample size times $R^2$ of this regression is approximately $\chi^2$ with number of excess instruments as degrees of freedom.
Comment: So the calculation for Hausman can be found here http://www.urfie.net/read/index.html#page/254 (left page). I will run the Sagran on that example tomorrow to see if I can reproduce a difference. Thanks!
Comment: Once again, thank you for a great answer. You have no idea how much I appreciate it! One question, it seems that in your answer you are referring to the Hausman test for endogeneity right? The test results I provided are actually for the test Hausman test for  overidentification (Wooldridge Introductory Economics 15.5, in which you regress the 2nd stage residuals on the 2nd stage). It seems that this test is much more like the Hansen J test as you describe it right? If you want to check, the book I referred to in the orig. post is freely accessible online. http://www.urfie.net/read/index.html
Comment: If the Hausman test is literally as described in 15.5 of your link, then yes, that's exactly Sargan's test, which as I wrote, can be basically thought of as the 'J Test' equivalent for TSLS.
Comment: I lightly edited the post to reflect that the hausman test for overidentification as defined in 15.5 is indeed the same as Sargan
Comment: Thank you very much! But this means that I have a problem with my data or the code then right? Because I am getting very different results for both tests..
Comment: @TomKisters I see that you have the R^2 and nobs, but idk how you calculated it.. if you're sure that you ran the same TSLS and then took the residuals and then ran a regression of residuals on instruments + exogenous variables, and then have the correct degrees of freedom, it should be the same... Id recommend simulating a simpler example (maybe 2 instruments, 1 endogenous variable), and make sure the tests agree there. If not, really study the code, and if still can't figure it out, make a post with your neat code and the approach you took and ask why it's not working.
Comment: If that is indeed the problem and you post it, comment here and i'll take a look. Otherwise, I don't really know what the problem may be, but a first step regardless will be to make sure youre getting the same result on a simple simulated dataset.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/109541/discussion-between-doubled-and-tom-kisters).


DOMContentLoaded not working like $(document).ready() in a simple scenario

Question: On the main file of my webpack assets bundle for an Angular2 app, I'm not being able to listen for the DOMContentLoaded event.
The file just has the following lines:
// styles
const bootstrapLoader = require('bootstrap-loader');
const styleScss       = require('./main.scss');
// scripts
const $               = require('jquery');
const jQueryUjs       = require('jquery-ujs');
const coreJS          = require('core-js');
const zoneJS          = require('zone.js');
const reflectMetadata = require('reflect-metadata');
const myAngularApp    = require('./main.ts');

document.addEventListener('DOMContentLoaded', function () {
  console.log('Hola!');
});

On the other hand, if I use jQuery, it works perfectly, id est, changing the last three lines with the following ones:
$(document).ready(function() {
  console.log('Hola!');
});

This looks so basic, but I don't understand why the plain javascript version of the document ready is not working here...
Many thanks!
Answer: It's not the same
https://api.jquery.com/ready/

Most browsers provide similar functionality in the form of a DOMContentLoaded event. However, jQuery's .ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded before the code calls .ready( handler ), the function handler will still be executed. In contrast, a DOMContentLoaded event listener added after the event fires is never executed.


Tratamento de exceções em C++

Question: Estou com uma dúvida referente ao tratamento de exceções em C++, a classe Fracao abaixo está propositalmente incompleta não possui nem mesmo setters ou getters e varias coisas foram "deixadas de lado", possui apenas dois atributos e um construtor, sendo que caso o denominador receba zero, será lançada uma exceção dentro do construtor.
O código funciona perfeitamente, o que gostaria de saber é se é possível fazer, não apenas o lançamento da exceção dentro do construtor/método da classe, mas também o tratamento da mesma, ou seja tirar os blocos try e catch da int main, e tratá-lo em outro lugar evitando que toda vez que eu precise criar um objeto qualquer (do tipo Fracao nesse caso) tenha que criá-lo dentro de um bloco try, seguido de um catch.
#include <iostream>
#include <exception>

using namespace std;

class Fracao
{
private:
    int numerador;
    int denominador;

public:
    Fracao(int numerador, int denominador);
};

Fracao::Fracao(int numerador, int denominador)
{
    this->numerador = numerador;

    if(denominador != 0)
        this->denominador = denominador;
    else
        throw "Impossivel dividir por zero";
}

int main()
{

    try
    {
        Fracao f1(1, 0);
    }
    catch(const char* msg)
    {
        cerr << "Erro: " << msg << endl;
    }
    catch(...)
    {
        cerr << "Erro desconhecido\n";
    }

    return 0;
}

Comment: Tratar em que lugar?
Comment: @bigown Onde seria normalmente feito o tratamento em um programa em C++? Meu objetivo seria não precisar utilizar try catch para todo objeto criado na main.
Comment: E aí seria tratado onde? Normalmente é feito onde precisa ser feito. Se quer fazer algo diferente, tem que justificar.
Comment: "não possui nem mesmo setters ou getters": javismo ? Em C++, pelo meno em minha experiência, as classes possuem os membros que precisam ter, não existe muito essa preocupação com "setters" e "getters"
Comment: @JoséX. Foi apenas uma forma de dizer que a classe é simples, e para nos atermos somente ao problema, inclusive agradeço seu comentário e concordo com você.
Answer: Tem algumas soluções possíveis, até mesmo não usar exceção. Se a construção do objeto tem um contrato que gera uma exceção quando a criação falha você tem que capturar a exceção e decidir o que fazer.
Note que se isso é considerado um erro de programação e nada deve ser feito você pode deixar sem tratar a exceção ou tratar de forma genérica em apenas um lugar. E esse lugar provavelmente seria a função main(). É o caso que parece estar sendo feito. Eu não faria diferente. Em uma aplicação mais complexa que chama outras funções há uma grande chance que eu não faria diferente. Só daria uma mensagem de erro um pouco melhor, registraria em log ou algo assim. OU seja, capture a exceção o mais longe possível de onde ocorreu. No caso não dá para ir muito longe que tudo ocorre na main().
Se quer fazer algo específico e tentar resolver a situação (só deve capturar exceções que pode resolver a situação) aí tem que capturar a exceção no local que ela pode ser gerada. Aí é para capturar o mais perto possível que faça sentido.
O que pode fazer para facilitar é criar uma função para manipular o erro e chamá-las ao invés de tratar para todo lado. Isso só é válido se o tratamento é sempre o mesmo.
Claro que aí talvez a classe deveria melhor e não precisa disso tudo, mas isso é apenas uma suposição, depende muito do caso. Também tem motivos para não fazer isso.
Se quiser fazer a função seria algo assim:
#include <iostream>
#include <exception>
using namespace std;

class Fracao {
private:
    int numerador;
    int denominador;
 public:
    Fracao(int numerador, int denominador);
};

Fracao::Fracao(int numerador, int denominador) {
    this->numerador = numerador;
    if (denominador != 0) this->denominador = denominador;
    elsethrow "Impossivel dividir por zero";
}

Fracao HandleExceptionFracao(int numerador, int denominador) {
    try {
        Fracao f(numerador, denominador);
        return f;
    } catch (const char* msg) {
        cerr << "Erro: " << msg << endl;
    } catch(...) {
        cerr << "Erro desconhecido\n";
    }
}

int main() {
    Fracao f1 = HandleExceptionFracao(1, 0);
}

Veja "funcionando" no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Dá até para fazer uma função genérica que sirva para criar qualquer objeto e cuidar da exceção sempre da mesma maneira. Mas ainda acho que de acordo com o exemplo da pergunta o erro é de programação e o tratamento deveria ser generalizado.
Seria interessante ler sobre exceções no site. A maioria não é para o C++, mas a maioria dos conceitos são universais. Bem poucos programadores sabem usar ou entendem para que serve uma exceção e como (não) se deve tratá-la.
Comment: Achei muito interessante sua resposta, e o link que você passou tem umas discussões interessantes, sobre por quê/quando usar ou não exceções, vou conferir. Muito obrigado novamente
Answer: Você pode imitar o que outras linguagens de programação fazem, como por exemplo Java, onde existe uma interface Trowable, todas as exeções lançadas no Java devem implementar essa interface, então a máquina virtual se encarrega capturar todas as exceptions, então em C++ você faria o seguinte:
Declarar sua classe de Exception que vai servir de base para que seja sempre capturada;
class RunnableException {
private:

public:
    virtual std::string getMessage() =0;
};

Criar uma classe específica para lançar a exceção do denominador inválido;
class ValorInvalidoException : public RunnableException {
private:
    std::string message;

public:
    ValorInvalidoException(std::string message) {
        this->message = message;
    }

    std::string getMessage() {
        return this->message;
    };
};

Ao invés de lançar um const char*, você deverá lançar um objeto;
Fracao::Fracao(int numerador, int denominador)
{
    this->numerador = numerador;

    if(denominador != 0)
        this->denominador = denominador;
    else
        throw ValorInvalidoException("Impossivel dividir por zero");
};

Use um único try-catch envolvendo toda sua função main;
int main() {
    try {
        //faca seu codigo do main normalmente
        Fracao f1(1, 0);
        try {

        } catch (ExcecaoEspecifica e) {
            //coloquei esse try catch aqui só para exemplicar o uso de um outro try
            //ele não tem nada haver com a captura do denominador errado
        }
        Fracao f2(2, 0);
    } catch(RunnableException re) {
        //esse catch vai pegar o denominador errado
        std::cout << t.getMessage() << std::endl;
    }
}

Tratamento de exceções em C++


Qual relacionamento entre o MVC e os Padrões de Projetos?

Question: Sabemos que o Padrão MVC (Model View Controller) não é um Design Pattern, mas sim padrão de arquitetura. Ele também não é um padrão em camadas, pois este diz como agrupar componentes enquanto o MVC diz como os componentes interagem.
O MVC utiliza alguns padrões.
Quais Padrões de Projetos usa o MVC?
Answer: No livro Design Patterns: Elements of Reusable Object-Oriented Software, considerado a bíblia dos Desing Patterns, é citado o padrão MVC na linguagem Smalltalk.
Segundo o livro, o padrão MVC usa os seguintes design patterns:
Observer
Usado no desacoplamento de View das Models de forma que mudanças na Model reflitam em todas as Views.
Composite
Usado para utilização de Views aninhadas e criação de componentes complexos como controles.
Strategy
Usado na relação View - Controller. Ao mudar a instância de controller que a view responde, você muda a estratégia de manipulação da View.

O livro ainda cita os seguintes design patterns que podem ser usados no MVC, mas são um pouco específicos a implementação Smalltalk ao qual o livro se refere.
Factory Method - Pode ser usado para definir a instância padrão de um Controller para uma View.
Decorator - Para adicionar rolagem a uma View
Pode ler aqui o trecho que fala especificamente disso.
Porém cada implementação específica do MVC vai utilizar um ou outro Design Pattern a mais ou a menos. O ASP.NET MVC por exemplo, utiliza algo bem próximo do pattern Command quando se utiliza o ActionResult no retorno. Diferentes retornos como JsonResult, ViewResult ou PartiaViewResult reprentam comandos diferentes que serão executados pelo framework no retorno do controle.


What would the World Series schedule be in this case?

Question: If the Yankees played the Mets in the World Series, it would be the two teams with the shortest distance between ballparks.
As it is now, and for every other case in memory, there is a travel day where games are not played as the series shifts from city to city.
In this example, since the Series is being held in the home city for both teams, would there be a travel day between switches in home stadiums, or would the series play out in 7 days?
Comment: As late as 1979, no travel day was scheduled even for the move from Baltimore to Pittsburgh between Games 2 and 3, though there was a travel day for the move back to Baltimore before Game 6. The 1971 series between the same teams did have the expected travel days, though Game 2 was delayed by rain until the travel day without postponing Games 3, 4, or 5.
Comment: The last intracity series prior to 2000 appears to have been 1956 between the Yankees and then Brooklyn Dodgers. There don't appear to have been any scheduled off-days, though Games 2 through 6 were played on consecutive days after Game 2 was originally postponed due to rain.
Comment: Lots of other interesting close pairs, but I stopped when I realized I was going off on quite a tangent. For example, 1985 KC/STL, 1983 PHI/BAL, 1989 OAK/SF (which appeared to have a single "travel" day after Game 2 replaced by an earthquake week, and then the series ended in a 4-game sweep anyway).
Comment: @chepner  Excellent finds
Answer: This already happened. https://en.wikipedia.org/wiki/2000_World_Series
You can see from the link that they had the usual travel day between games 2 and 3. Note that MLB schedules these things way in advance so the TV networks can plan around them, so they won't change just because two teams are in the same city.


Question about a determinant property I encountered in a question.

Question: Here's the question:
let $A,B\in \mathbb{R}^{3\times 3}$ such that $AB=|A|I$ and $|(2A)^2(A^t)^{-1}B|=16$ then $|A|=?$
I wanted to ask about how to deal with the information that $AB=|A|I$, can I just $|AB|=||A|I|=|A|$? am I allowed to do that?
From the other information I got that $4^3|A||B|=16$ so $|AB|=\frac {1}{4}$.
So what I said was $|A|=\frac {1}{4}$, but the answer was $|A|=(\frac{1}{4})^{\frac {1}{3}}$, so I think I have a miss understanding about how to calculate $||A|I|$.
Thanks in advance for all the help.
Comment: $\det(A)$ is a number here ! So if you want to put it out from the $\det$, you have to put it out with the good power. Apply the formula I gave with $M=I$ and $\lambda=\det(A)$.
Comment: Be careful, the good formula is $\det(\lambda M)=\lambda^n \det(M)$, where $n$ is the dimension of the matrix... So $\det(\det(A)I)= ...$ ?
Comment: @TheSilverDoe Thanks for the comment, Yes I know that formula, but how can I apply it in $||A|I|$, what I did was : $||A|I|$=$||A||*|I|=|A|$, that seems wrong but I can't see why.
Comment: @TheSilverDoe Thanks alot, all clear now, I appreciate the help :).
Answer: From $AB=|A|\operatorname{Id}$ and from the fact that $A$ is a $3\times3$ matrix, you get that$$|A||B|=\bigl||A|\operatorname{Id}\bigr|=|A|^3.$$And from the fact that $\left|(2A)^2\left(A^T\right)^{-1}B\right|=16$, you get that$$64|A|^2\frac1{|A|}|B|=16\left(\iff|A||B|=\frac14\right).$$So, $|A|^3=\frac14$, and therefore $|A|=\frac1{\sqrt[3]4}$.
Answer: Hint:
$|kA|=k^3|A|$, if $A$ is $3 \times 3$.similarly $||A|I|=|A|^3$.
Comment: @Z Ahmed Thanks alot, this clears it, wonderful trick to know :). Appreciate the answer.


Lilypond changing staves with tremolo on single notes

Question: I'm on Lilypond 2.20 and trying to write a passage where I have several 8th notes tremolo'd to 16ths, and I'm trying to get them to change staves—but whenever I do, the beams glitch out and can't be placed correctly.
As an example, try running the following code:
<code>\autochange { c8:16 c'':16 c:16 c'':16 }</code>
Any idea what I can do about this?  Thank you!
Comment: The tremolo is happening at the same time that the beaming is happening.
The solution is to create a custom stem with the tremolo symbol (I don't know how to do that.) But it would happen same time stem created. Maybe someone on here maybe able to help, or try User mailing list: email@example.com see http://lilypond.org/contact.html
Answer: Best I can come up with is creating two voices in top staff. First voice has 8th notes, second voice has 1/4 notes in space of 8th notes and they "hold the tremolo sign"
Created variables for up and down staff. Two functions for: beam adjustment, and tremolo height. Might need. Very hacky but works.
<code>\version "2.20.0"
beamPos =
#(define-music-function
     (parser location beg-end)
     (pair?)
   #{
     \once \override Beam.positions = #beg-end
   #})

tremPosition =
#(define-music-function
     (parser location y-offset)
     (number?)
   #{
     \once \override StemTremolo.Y-offset = #y-offset
   #})

csu = { \change Staff = "up" \stemDown }
csd = { \change Staff = "down" \stemUp }

up = \relative c {
  %\csd c8 \csu c'' \csd c \csu c''
  <<
    \relative c {
      \csd \beamPos #'(4 . 4) c8 \csu c'' \csd c,, \csu c''
      \csd \beamPos #'(4 . 4) c,,8 \csu c'' \csd c,, \csu c''
    }
    \\
     \relative c {
       \csd  c4 * 1/2:8 \csu c'':8 \csd c,,:8 \csu c'':8
       \csd \tremPosition #3 c,,4 * 1/2:8 \csu \tremPosition #-2 c'':8 \csd \tremPosition #1 c,,:8 \csu \tremPosition #-1 c'':8
     }
  >>
}

down = \relative c' {
  s1 | s1 |
}

\score {
   <<
    \new Staff = "up" \with {
      midiInstrument = "acoustic grand"
    } \up
    \new Staff = "down" \with {
      midiInstrument = "acoustic grand"
    } { \clef bass \down }
  >>
  \layout { }
  \midi { }
}
</code>
First shows default output. Second shows altering tremolo signs. Both have beam adjusted. Don't forget spacer rests in down staff to:

keep the staff alive!
Comment: This definitely looks like it works (if it looks like a duck, then it is a duck), but I have like 24 measures of this stuff to work through.  Any ideas on how to make it scale faster?
Comment: If it's all the same then it's the `\repeat unfold 24 { stuff to repeat }`. Or if some things are the same put in variables `mymusicA = { c d e f g}` place `\mymusicA` in main body and `mymusicB = { g f e d c}` place `\mymusicB`. Might not be helpful! The code I provide is not ideal from a scalability point of view. Just thought give **some** solution. May you might find putting variables in as above. Otherwise copy and paste line by line and change as you go. That's what I often do with structures the same and only change by the notes
Comment: Also if using frescobaldi (most do), use the snippets, where you create custom lines of code and double-click or assign to a keyboard shortcut. Can even run python scripts in it (though think it's python 2.x not 3.x)


Setting the media type when using @RequestLine

Question: I am using @RequestLine annotatin in my Feign Client interface. It only takes the Request Method and Path, is there a way to set the media type it produces and consumes?
This is what I have, any suggestions what ways I can add the media type it produces and consumes to this?
<code>@RequestLine("POST /metrics-service/rest/addMetric")
    MyEntity sendEntity(@RequestBody MyEntity toSend);
</code>
Answer: Yes, very simple, you can add
<code>@Headers("Content-Type: application/json")
</code>
check out the reference: https://github.com/Netflix/feign


How to to fix nginx listening externally on port 8080 and internally on port 80?

Question: Nginx started and listening on port 80 but it can only be accesed externally on port 8080.
curl 0:80 works fine with a 200 response and curl 0:80 reponds with connection refused but externally, curl example.com:80 is stuck and never responds
while curl example.com:8080 responds with 200
Port 80 is allowed on ufw
Initially I forwarded port 80 to 8080 before the issue started, then I removed the port forwarding configuration setting from /etc/ufw/before.rules yet the issue still persisted.
I stopped my nginx server and it stopped, then I started the server again and the issue started.
My nginx is configured to run on port 80, netstat -lpn confirms that nginx is running on port 80.
But it is not responding externally on port 80 but port 8080
I also tried nc -z 0 80 ; echo $? and it returned 0.
But nc -z 8080 ; echo $? is returning 1 but I can't find the processes listening on port 8080.
I've tried ps aux too.
Comment: Is there a router or firewall between the server with Nginx running on port 80, and the server you are running `curl` from?
Comment: No just ufw on which 80/tcp is allowed and I explained how I went about it there
Comment: What do you get when you run the command `ss -an  '( sport = 8000 )'` (`ss` is a tool similar to `netstat`, with slightly different options)
Comment: Just:
`Netid          State          Recv-Q          Send-Q                   Local Address:Port                   Peer Address:Port         Process `
Comment: Nothing for 8000 and 8080 but :80 is displaying
`Netid         State           Recv-Q          Send-Q                   Local Address:Port                   Peer Address:Port         Process
tcp           LISTEN          0               511                            0.0.0.0:80                          0.0.0.0:*
tcp           LISTEN          0               511                               [::]:80                             [::]:*    `
Comment: One thing I found out is this, nginx is responding internally on port 80 and externally on port 8080.
My ufw confiiguration is okay, and port 8080 is not even allowed on my ufw
`sudo ufw status` has this:
`22/tcp              ALLOW       Anywhere
443/tcp                ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere
22/tcp (v6)                ALLOW       Anywhere (v6)
443/tcp (v6)               ALLOW       Anywhere (v6)
80/tcp (v6)                ALLOW       Anywhere (v6)`
Comment: Please review what is on topic in the [help/on-topic]. Stack Overflow is only for _programming_ questions. Systems administration questions are better directed to [sf] or perhaps [unix.se] or [ubuntu.se].
Answer: I fixed it by flushing the chains in the NAT table and removing sub chains
sudo ufw disable
sudo iptables --table nat --flush
sudo iptables --table nat --delete-chain
sudo ufw enable

Comment: This has been causing me issues for ages! Every port except 80 would work lol.


Meaning of "you can tap in the delay time" (manual of Behringer DR 400)?

Question: What is the meaning of the next text in manual of Behringer DR 400?

When pressing the foot switch for 2 seconds or longer, you can tap in the delay time

Link to manual
There are three general groups of pedal functions:

delay
delay + reverb
reverb

There are two knobs that change their functionality according to the mode, but not according to the "tap in the delay time".
Does anyone know what long pressing actually does?
Comment: Are you asking what the "tap" function does? Or do you know what that is and you're saying it doesn't seem to work the way the manual suggests? In case you meant the first, many delay effects have a "tap tempo" feature where you can tap a button at a particular tempo to set the delay time. You could press it a bunch of times as if you're tapping along with the beat, but you only really need to press it twice. The time between the last two taps is how long the delay will be. This is especially useful when playing live if you need differing delay times set on the fly and hands-free.
Comment: @user37496 , I don't know how it works. I'll receive pedal in the middle of may, and I'd like to know how to deal with it. Everything else is clear for exception of "tapping in the delay time". Thanks for comment I'll try this
Answer: Sounds to me that holding for two seconds will activate another mode were you get to select the amount of delay by taping the button with your foot.
Hold the pedal for 2 seconds and the ON/BATT LED flashes, then tap the pedal a few more times in rhythm to set the delay time.
That is my guess based on the manual which is not very good.


Rest at the beginning of a score in musicxml

Question: I've been studying diverse musicXML files with MuseScore and I've found that usually rest notes are easily represented and visible in its musicXML file.
Yet, I found this 'repeated rest' at the start of a song which has particularly intrigued me since I'm using the xml file to build an object for a different software, resulting into a repeated rest which is obviously not desired.
It has a backup value which I couldn't find much information about. I'm obviously not a musician.
The duplicated rest
<measure number="1" width="148.52">
      <print>
        ....
        </print>
      <attributes>
        ...
        <staff-details number="1">
          ...
        </attributes>
      <note>
        <rest measure="yes"/>
        <duration>8</duration>
        <voice>1</voice>
        <staff>1</staff>
        </note>
      <backup>
        <duration>8</duration>
        </backup>
      <note>
        <rest measure="yes"/>
        <duration>8</duration>
        <voice>5</voice>
        <staff>2</staff>
        </note>
      </measure>
<measure number="2" width="121.94">
  <note>
    <rest/>
    <duration>2</duration>
    <voice>1</voice>
    <type>quarter</type>
    <staff>1</staff>
    </note>
  <note default-x="42.79" default-y="-30.00">
    <pitch>
      <step>E</step>
      <octave>4</octave>

The partiture:

What also calls my attention is that the rest note does not have any type value which according to the museScore partiture it should be a half.
Next rest, which is also a rest, has its proper value of a quarter and it's not repeated.
It's important to understand this, otherwise I will not be able to generate the proper algorithm for the time stamps of each note.
The complete start of the musicxml file if case you find it useful
<part id="P2">
    <measure number="1" width="148.52">
      <print>
        <staff-layout number="1">
          <staff-distance>0.00</staff-distance>
          </staff-layout>
        <staff-layout number="2">
          <staff-distance>76.96</staff-distance>
          </staff-layout>
        </print>
      <attributes>
        <divisions>2</divisions>
        <key>
          <fifths>1</fifths>
          </key>
        <time>
          <beats>4</beats>
          <beat-type>4</beat-type>
          </time>
        <staves>2</staves>
        <clef number="1">
          <sign>TAB</sign>
          <line>5</line>
          </clef>
        <clef number="2">
          <sign>G</sign>
          <line>2</line>
          </clef>
        <staff-details number="1">
          <staff-lines>4</staff-lines>
          <staff-tuning line="1">
            <tuning-step>G</tuning-step>
            <tuning-octave>3</tuning-octave>
            </staff-tuning>
          <staff-tuning line="2">
            <tuning-step>D</tuning-step>
            <tuning-octave>4</tuning-octave>
            </staff-tuning>
          <staff-tuning line="3">
            <tuning-step>A</tuning-step>
            <tuning-octave>4</tuning-octave>
            </staff-tuning>
          <staff-tuning line="4">
            <tuning-step>E</tuning-step>
            <tuning-octave>5</tuning-octave>
            </staff-tuning>
          </staff-details>
        </attributes>
      <note>
        <rest measure="yes"/>
        <duration>8</duration>
        <voice>1</voice>
        <staff>1</staff>
        </note>
      <backup>
        <duration>8</duration>
        </backup>
      <note>
        <rest measure="yes"/>
        <duration>8</duration>
        <voice>5</voice>
        <staff>2</staff>
        </note>
      </measure>
    <measure number="2" width="121.94">
      <note>
        <rest/>
        <duration>2</duration>
        <voice>1</voice>
        <type>quarter</type>
        <staff>1</staff>
        </note>
      <note default-x="42.79" default-y="-30.00">
        <pitch>
          <step>E</step>
          <octave>4</octave>
          </pitch>
        <duration>2</duration>
        <voice>1</voice>
        <type>quarter</type>
        <stem>down</stem>
        <staff>1</staff>
        <notations>
          <technical>
            <down-bow/>
            <string>3</string>
            <fret>2</fret>
            </technical>
          </notations>
        </note>
      <note default-x="69.64" default-y="-30.00">
        <pitch>
          <step>E</step>
          <octave>4</octave>
          </pitch>
        <duration>2</duration>
        <voice>1</voice>
        <type>quarter</type>
        <stem>down</stem>
        <staff>1</staff>
        <notations>
          <technical>
            <down-bow/>
            <string>3</string>
            <fret>2</fret>
            </technical>
          </notations>
        </note>
      <note default-x="96.49" default-y="-15.00">
        <pitch>
          <step>B</step>
          <octave>4</octave>
          </pitch>
        <duration>2</duration>
        <voice>1</voice>
        <type>quarter</type>
        <stem>down</stem>
        <staff>1</staff>
        <notations>
          <technical>
            <down-bow/>
            <string>2</string>
            <fret>2</fret>
            </technical>
          </notations>
        </note>
      <backup>
        <duration>8</duration>
        </backup>
      <note>
        <rest/>
        <duration>2</duration>
        <voice>5</voice>
        <type>quarter</type>
        <staff>2</staff>
        </note>
      <note default-x="39.79" default-y="-161.96">
        <pitch>
          <step>E</step>
          <octave>4</octave>
          </pitch>
        <duration>2</duration>
        <voice>5</voice>
        <type>quarter</type>
        <stem>up</stem>
        <staff>2</staff>
        <notations>
          <technical>
            <down-bow/>
            </technical>
          </notations>
        </note>
      <note default-x="66.64" default-y="-161.96">
        <pitch>
          <step>E</step>
          <octave>4</octave>
          </pitch>
        <duration>2</duration>
        <voice>5</voice>
        <type>quarter</type>
        <stem>up</stem>
        <staff>2</staff>
        <notations>
          <technical>
            <down-bow/>
            </technical>
          </notations>
        </note>
      <note default-x="93.49" default-y="-141.96">
        <pitch>
          <step>B</step>
          <octave>4</octave>
          </pitch>
        <duration>2</duration>
        <voice>5</voice>
        <type>quarter</type>
        <stem>down</stem>
        <staff>2</staff>
        <notations>
          <technical>
            <down-bow/>
            </technical>
          </notations>
        </note>
      </measure>

Answer: I'm not quite sure what was that backup about, despite finding some shallow information (here), however found nothing that could help me that much.
In the end, and after visiting several other songs, I just ignored any rest note that didn't have a staff value of 1, thus I was able to map perfectly the song.


Find the Least Prime Divisor of $2^{17}-1$

Question:
Show that the least prime divisor of $2^{17}-1$ is $2^{17}-1$ itself.

This question is really anoying. Let $N=2^{17}-1$. What I know is that if $q\mid N$, then $q=34k+1$ for some $k \in \Bbb{N}$ and $q \equiv \pm1 \pmod 8$. Therefore,
$$q \equiv 2k+1 \equiv \pm1 \pmod 8$$
We get $k \equiv -1, 0 \pmod 4$. So $q=136x+1$ or $q=136x-33$ for some $x \in \Bbb{N}$.
This is all I know about finding the prime divisor of the form ${2^{p}-1}$, which might be the Mersenne number. But do I have to just substitute each possible value of $q$ into $N$ in order to show that it ultimately doesn't have any prime divisors other than $N$ itself? It takes so much time and effort. And I don't think the problem is just to make students tediously substitute each case one by one(if it is, then I'm so frustrated).
So the question: is there any more time-saving way to distinguish certain types of Mersenne number without goint too far from my basic understading of Number Theory? Or should I just subsitute one by one and that's the best choice I can take?
Thanks!
Edited This was a question that baffled me about few months ago, and after studying the case for perfect numbers, now I do know that $2^{17}-1$ is a Mersenne number(related to the perfect number $8589869056$). But I still think just memorizing the case doesn't give me full insight into this area.
Comment: If you are dealing with large Mersenne numbers, there is the [Lucas-Lehmer test](http://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test) which is the process used to establish many of the prime number records in recent decades.
Comment: GIMPS has a screen saver you can install that will use your computer's spare processing power to look for Mersenne primes.  For over a decade, the record for largest known prime has been held by someone running this software.  See [here](http://primes.utm.edu/mersenne/index.html).
Comment: There is always lots to learn :-)! See: http://mathworld.wolfram.com/PrattCertificate.html. Here is the example they use on that web site and I posted the certificate for your particular problem, so you can follow: {True, {7919,
  7, {2, {37, 2, {2, {3, 2, {2}}}}, {107,
    2, {2, {53, 2, {2, {13, 2, {2, {3, 2, {2}}}}}}}}}}}. Regards
Comment: Testing that $2^n-1$ is prime is hard, that's why [GIMPS](http://mersenne.org/) exists.
Comment: @vadim123 Wow, what is that site exactly for? An association for sharing knowledge to find Mersenne number?
Comment: @OldJohn Thanks for the new method to distinguish Mersenne numbers. I didn't know it. It would be much better to use the technique rather than substituting the case one by one for sure.
Comment: @TaxxiDriver: Can you just prove that $2^{17}-1 = 131071$ is a prime number using something like a Pratt Certificate? {True, {131071,
  3, {2, {3, 2, {2}}, {5, 2, {2}}, {17, 3, {2}}, {257, 3, {2}}}}}. Also, http://primes.utm.edu/notes/proofs/Theorem2.html
Comment: @Amzoti I do know about the proof you just had linked. But I haven't heard of Pratt Certificate. Still so long way to go for me...
Comment: @vadim123 Oh thanks. The site has so many fruitful results that I have to check out.
Comment: @Amzoti Yes, indeed. So many things to learn, always! Thanks for the link. I think I have to make some of the methods recommended to be accustomed to me.
Comment: This is a really fun area as the problems can be easily stated, but are usually very complex, it allows for fun numerical experiments and there are projects for primes, factoring, and Mersenne's, et. al.
Answer: Let $p|2^{17} - 1$, then we have $2^{17} \equiv 1 \pmod p$, but we also have from Fermat's Little Theorem $2^{p-1} \equiv 1 \pmod p$.
From Lagrange Theorem for group order we get that $2^{\gcd(p-1,17)} \equiv 1 \pmod p$.
Obivously the greatest common divisor is $17$, because otherwise (if the gcd were $1$) then $2 \equiv 1 \pmod p$, which is impossible.
Then we have $17 \mid p-1$ and because $p-1$ is even we have $34\mid p-1$. So we need to check all prime numbers of the form $p=34k + 1 \quad \forall k \in \mathbb{N}$ such that $p \in (1,\sqrt{2^{17} - 1}]$. Which reduces the number of divisors to check. Actually there are just $4$ primes in this inteval, those are $103, 137, 239, 307$. You can check that none of them divides $2^{17} - 1$, implying that $2^{17} - 1$ is prime.
Also you can check how Euler proved that $2^{31} - 1$ is prime, and apply the same method on $2^{17} - 1$.
Actualy $2^{17} - 1 = 131071$ isn't that big number, even without knowledge in number theory it isn't so much hord work to do.
And at last as other users have suggested use Lucas-Lehmer Test.
Comment: @Sky If p has a divisor greater than $\sqrt{2^{17} - 1}$ then it also must have one smaller than $\sqrt{2^{17} - 1}$. So if there exist such a divisor, then we must find it's "partner(s)" in the given interval. But since $2^{17} - 1$ doesn't have a divisor in the interval, it implies it also doesn't have one in $(\sqrt{2^{17} - 1}, 2^{17}-1)$. Obviously this greatly reduces the numbers we need to check.
Comment: Yeah, I got confused, and though we were dealing with $2^{19}-1$. @Stefan4024
Comment: Oh, I forgot about the Sieve of Erastosthenes... Thanks for the link, too.
Comment: @TaxxiDriver Hope it helps ;) As I said the first method can be useful and quite fast for small numbers, but for big numbers the Lucas-Lehmer Test will do the job much better
Comment: According to most lists of Mersenne numbers, the number $2^{17}-1$ was first proven prime by [Cataldi](http://en.wikipedia.org/wiki/Pietro_Cataldi) in 1588. This illustrates that this can be done by "brute force", without knowing that factors of Mersenne numbers must have a special form. Just like you said.
Comment: Why does the interval end at $\sqrt{2^{17} - 1}$?
Comment: You also have that $2$ is a square modulo $p$, so $p\equiv \pm 1\pmod{8}$. So $p\equiv 1, 103\pmod{136}$.
Comment: @ThomasAndrews But I've already proven that $p\le \sqrt{2^{17}-1} < 363$, so you can eliminate the last two primes.
Comment: @ThomasAndrews It happens. Also nice observation to notice that $p \equiv \pm 1 \pmod 8$


A bag of scrabble tile contains 5 Es, 4 As, 3 Ns and 2 Bs.

Question: I draw 4 tiles one by one from the bag as an ordered sample without replacement. Assume equally likely outcomes. Let C be the event that I get 2 Es, 1 A and 1 N. Compute P(c).
So I started by taking P(14,4) which gave me 24,024. Then, to account for repeated elements in the sample space (5 Es, 4 As, 3 Ns, 2 Bs), I figured I'd have to divide by $5!\cdot4!\cdot3!\cdot2!$. The problem is that this gave me a value less than 1. Where am I going wrong?
Comment: The question is to find probability so that may not necessary. In any case even if you did that, why are you dividing by $5!$ etc.? You have to consider the order in the $4$ tiles that you take out, not in $14$.
Comment: I will come to your working but are you not finding probability of the event $C$? So it should be less than $1$, why is that wrong?
Comment: @MathLover Because I wasn't at that step yet, I was still in the process of cancelling out repeated combinations to get my total number of ways to draw the ordered samples of tiles.
Comment: $14 \choose 4$ is the total number of ways to draw $4$ tiles if the order does not matter.
Comment: @MathLover I would use that if I was looking for unordered samples, but that is not the case.
Comment: [Welcome to Math.SE!](//math.meta.stackexchange.com/a/4928/290189) Please use MathJax.  For some basic information about writing math at this site see e.g. [basic help on MathJax notation](/help/notation), [MathJax tutorial and quick reference](//math.meta.stackexchange.com/q/5020/290189), [main meta site math tutorial](//meta.stackexchange.com/a/70559/259305) and [equation editing how-to](//math.meta.stackexchange.com/q/1773/290189).
Answer: This is a question on probability so here is how you should go about it -
Sample space: $5 E, 4 A, 3 N, 2 B$
Event C of $4$ tiles:  $2 E, 1 A, 1 N$
So $P(C) = \displaystyle \frac{{5 \choose 2}{4 \choose 1}{3 \choose 1}}{14 \choose 4} = \frac{120}{1001}$
If you consider the order in your calculation, you will get to the same answer. In that case in total, you have $14$ choices for the first, $13$ for the next and so on ($ ^{14}P_4 $). For favorable cases, multiply your selection by $4!$ for possible arrangements of them.
$P(C) = \displaystyle \frac{{5 \choose 2}{4 \choose 1}{3 \choose 1} \ 4!}{14 \times 13 \times 12 \times 11} = \frac{120}{1001}$


Does Thread.Sleep deactivates a TCPListener?

Question: I have a thread like this:
        Public Sub StartWork()
        Try
            myTCPListener.Start()
            While StopRequest = False
                Dim requestspending As Boolean = m_TCPListener.Pending()
                If myTCPListener.Pending = False Then
                    Threading.Thread.Sleep(100)
                Else
                   DoSomething()
                End If

            End While
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

Now my question is: I send the Thread via Thread.Sleep to sleep mode when nothing happens here. Does this affect the TCPListener in his work somehow and what happens to an incomming connection while the Thread is in sleep-mode?
Comment: Pretty unclear how you can burn 17% core with Thread.Sleep(100) calls.  Anyhoo, you should definitely prefer the 0% you get from AcceptSocket.
Comment: Yes.  The code is strange, you only DoSomething when somebody is trying to connect.  So don't bother, just call AcceptSocket instead so you don't have to sleep to avoid burning core.
Comment: the thing is that when i run it without thread.sleep the program takes 33% of my cpu (amd x6 phenom), with thread.sleep it just takes 17%. so when the thread sleeps connections still can pend, but can't be accepted, did i get that right?
Answer: While your thread is asleep it can't do anything. In particular it won't be able to accept a connection. So clients connecting to you will have to wait for 100ms until the connection gets established (the connection gets established when you call Accept and Accept returns).
Answer: Dim connection As Socket
Dim reader As BinaryReader
Dim writer As BinaryWriter
Dim socketStream As NetworkStream
Dim listener As TcpListener

Dim ip As IPAddress = IPAddress.Parse(ipstring)
listener = New TcpListener(ip, portnumber)
listener.Start()

connection = listener.AcceptSocket()
socketStream = New NetworkStream(connection)
writer = New BinaryWriter(socketStream)
reader = New BinaryReader(socketStream)

this is the efficient way to handle incomming connections :-), you dont have to put anything to sleep. If performance is an issure, decrease the priority of the thread. ex:
serverthread.Priority = ThreadPriority.BelowNormal

Answer: Listening for TCP connections and serving them is a standard design pattern. There is a better way to do it than you have in your code. Use TcpListener.AcceptTcpClient() which blocks until there is a connection request and when that happens it returns TcpClient you can work with to serve the client. Even though AcceptTcpClinet() is a blocking call (won't return until there is a request) it will not use CPU time. Since this is exactly what you do in your code (do nothing until there is a request) it will do the job you want.
Generally you should avoid Thread.Sleep() as it is not the best way of giving up CPU time. You should rather use specialized listening methods like AcceptTcpClinet(), timers, asynchronous calls, WaitHandle, Thread.Join() and so on. It is much harder to do and sometimes not worth it but that should be your aim.


Derivative $d/dx$ of an integral will be $0$?

Question: If we want to take the derivative $d/dx$ of, say, $\int_{0}^{1} x^2dx$, what will the answer be? does that mean to take $g(x) = \int_{0}^{1}x^2dx$ and find $g'(x)$? If so, we have $g(t) = \int_{0}^{1}t^2dx = t^2$ and therefore the derivative $d/dx$ of $\int_{0}^{1} x^2dx$ is $2x?$  What needs to be done first, calculate the integral to get $g(x) = 1/3$ or do what I did and why? thanks
Comment: That integral is a numerical constant, not a function of $x$, so yes.  It's derivative is $0$.  This is true for any definite integral.
Answer: $$\int_{0}^{1} x^2dx
$$
is just a number - it happens to be $1/3$. It does not depend on $x$ and its derivative (should you think of it as a constant function) is $0$.
I think you are confusing this definite integral with the indefinite integral
$$
f(x) = \int_{0}^{x} t^2dt .
$$
The derivative of that function is $x^2$, which you know from the fundamental theorem of calculus even without guessing the antiderivative $x^3/3$.
Edit in response to a comment: see this answer about "dummy variables"
What exactly is a 'dummy variable'? .
Comment: The $x$ in the integral is just a **dummy variable** of integration (i.e. you could replace the integration variable with any symbol and it would be the same, e.g. $\int_0^1 x^2\, dx = \int_0^1 u^2\, du = \int_0^1 y^2\, dy = \int_0^1 \Upsilon^2\, d\Upsilon = \int_0^1 \ddot{\smile}^2\, d\ddot{\smile}=\cdots$). It is separate and different in meaning to the $x$ in your $g$ function (and it's nicer really here to use a different symbol for the $g$ input and the integration variable).
Comment: I know, If I wrote $g(t) = \int_{0}^{1} x^2dx$ it was OK for me, but what annoys me is when I write $g(x) = \int_{0}^{1}x^2dx$ why doesn't it make it $g(1) = \int_{0}^{1}1^2dx$?
Answer:
A definite integral like $\int_a^bf(x)\,dx$ is a number; the dummy variable one uses does not affect the value of the definite integral:
$$
\int_0^1x^2\,dx=\int_0^1y^2\,dy=\int_0^1t^2\,dt=\cdots.
$$
Given any real constant $C$, one can define a constant function
$$
g(x)=C\quad  \textrm{for all the real number $x$}.
$$
The derivative of a constant function (at any point) is $0$.
Writing $g(x)=\int_0^1x^2\,dx$ is bad; you are using the symbol $x$ for two different kinds of purposes: on the right hand side, it is a dummy variable; on the left, it is used as a variable of the function $g$. If such expression makes sense at all, it means the same thing as $g(x)=\int_0^1u^2\,du$, which defines a constant function, the derivative (at any point) of which is $0$.
The definite integral $\int_0^1x^2\,dx$ and $\int_0^1t^2\,dx$ are two different things: the value of the later depends on the value of $t$. In fact,
$$
\int_0^1x^2\,dx=\frac13,\quad\int_0^1t^2\,dx=t^2.
$$
"Taking the derivative" and applying the differential operator $d/dx$ to a function are not quite the same. One can take the derivative of any differentiable function but one cannot applying the differential operator $d/dx$ to a function that does not have $x$ as its variable. For instance, it does not make sense to, say, take $d/dx$ to $g(t)=t^2$. But it make sense to write $g'(t)=2t$.
Answer: There appears to be a major point of confusion here. The integral
$$ \frac{1}{3} = \int_0^1 x^2 dx$$
is a number. It's exactly equal to $1/3$. Taking the derivative of a constant is zero (since the constant function does not change).
Writing notation like
$$ g(x) = \int_0^1 x^2 dx$$
is very poor notation, since the $x$ appearing in the integral is not the same variable as appears in $g(x)$.


Cannot get dompdf to work

Question: I have extracted the dompdf libraries folder to /sites/all/libraries
Re: 2. Edit dompdf_config.inc.php to fit your installation.
What exact changes do I need to make to this file???
Also, I am getting this warning in the drupal admin:

Warning: in_array() expects parameter 2 to be array, integer given in print_pdf_settings() (line 22 of /home/mysite/public_html/sites/all/modules/print/print_pdf/print_pdf.admin.inc).
Comment: Which module are you trying to use?  This should probably be reported to that module's issue queue, not here.
Comment: @PatrickKenny OP is referring to the [Print](http://drupal.org/project/print) module, as shown in the error.
Answer: Print module works best when you copy the library dompdf (or tcpdf) to the module folder directly. In this was you don't need to edit the file, and the print module will detect the library automatically.

Extract the dompdf directory into sites/all/modules/print so that you have dompdf_config.inc at sites/all/modules/print/dompdf/dompdf_config.inc.
Ensure that you have write access to PUBLIC/print_pdf/dompdf/fonts directory.
Your print module should now show the detection of the library at admin/config/user-interface/print/pdf.

You should now be able to export the nodes to PDF :)

Cannot get dompdf to work


Show that $\sum(-1)^{k}f_{k}(x)$ converges uniformly over $[0, \infty)$

Question:
Let $f_n: [0, \infty) \rightarrow \mathbb{R}$ be a sequence of real functions.
Suppose for each $n$ and $x \in [0,\infty)$ we have that $0 \leq f_{n+1}(x) \leq f_n(x)$.
Show that if $(M_n)_{n=1}^{\infty}$ is a sequence of reals with $\lim_{n\to\infty} M_n = 0$ and $\forall x \in [0, \infty) \space \space \forall n \in \mathbb{N}:\space 0 \leq f_{n}(x) \leq M_n$then $\sum(-1)^{k}f_{k}(x)$ converges uniformly over $[0, \infty)$.

I know, by Leibniz's test, that the sequence convergence pointwisely.
However it's left unclear to me why the existence of $(M_n)$ would ensure that the convergence is uniformly. I will be glad to have a hint\an observation which I possibly haven't considered yet.
Thanks
Answer: Let $S_{n}(x)=\sum_{k=1}^{n}(-1)^{k}f_{k}(x)$ be the partial sum.
We go to show that $(S_{n}(x))_{n}$ is uniformly Cauchy and hence
it converges uniformly. Let $\varepsilon>0$ be given. Choose $N$
such that $M_{n}<\varepsilon$ whenever $n\geq N$. Let $p\in\mathbb{N}$,
$n\geq N$, $x\in[0,\infty)$ be arbitrary, then
\begin{eqnarray*}
 &  & \left|S_{n+p}(x)-S_{n}(x)\right|\\
 & \leq & \left|(-1)^{n+1}f_{n+1}(x)\right|\\
 & \leq & M_{n+1}\\
 & < & \varepsilon
\end{eqnarray*}
This shows that $(S_{n}(x))_{n}$ is uniformly Cauchy on $[0,\infty)$.
In the above, we have used the fact that $f_{1}(x)\geq f_{2}(x)\geq\ldots\geq0$
to infer that $\left|S_{n+p}(x)-S_{n}(x)\right|\leq\left|(-1)^{n+1}f_{n+1}(x)\right|$.


Show a block only on the frontpage of the sub-domains

Question: I am using Drupal 7 for a site and I installed the Domain access module for maintaining the sub-domains. The slideshow block (created using the Views module) should be displayed on the sub-domains front page, but not on the main domain.
I tried the Domain block module, but it would require to manually set the block for each domain.
How can I make the block appear only on the front page of the sub-domains?
Answer: I recommend you to use context module for block displays with the domaincontext module extension.

Domain Context module is an integration module for the Domain Access module and the Context module.
The Domain Access module allows administrators to set specific
  settings for each of their domains that are using the same code base.
  The Context module allows you to assign blocks to regions (and more)
  given certain conditions that can be set in the Context admin.
  Currently when both modules are installed you have no interface that
  will allow you to trigger a context on a specific domain. This module
  adds a domain condition to the context administration so that you can
  trigger a context on a specific domain.
Comment: The Domaincontext module didn't help me. Even, it gave Domain condition while creating new contexts. Any help other than that.
Comment: I am planning to write code to disable the slideshow for the main site.
Answer: I added a view filter based on the domain ID (unique key ID).
These key IDs are nothing but the domain IDs you get while creating new domains. By default,the main domain ID is 1.
In the view, I added the Domain: Key ID filter and made a filter for  Domain Key ID ~ 1.
It worked.


Network teaming Windows Server 2008 R2

Question: I have two Windows Server 2008 R2 servers that need to share files on SAS attached logical drives over a 10G network connection.
The servers have two 10G ports so I'm wondering if I can use both of them to increase file I/O performance and how it would be done.
Currently I am getting 300Mb/sec file transfer and would like to see 500 to 600Mb/sec.
Comment: How do you know that the network is the bottleneck?
Comment: File transfer from one logical drive to another directly attached to a server is twice as fast as file transfer over the network.
Comment: Well, you aren't saturating the 10G port, so that's the problem you should work on.
Comment: Maybe it's SMB. I need to do some testing. I have not changed any settings yet.
Comment: Update to Windows 2012 R2 (SMBv3), make sure you have Jumbo Frames enabled.
Answer: Your best bet is to upgrade.  You'll get the best performance from SMB 3 cluster and clients (ver. 8 and up) but on SMB 2 clients you can at least maximize their nice thruput by enabling jumbo frames on the server.  Note that a CAFS requires an 8 or better client

Network teaming Windows Server 2008 R2


Posso nomear pastas no GtiHub com caracteres especiais?

Question: Tenho dúvidas se é uma boa pratica nomear pastas utilizando caracteres com acento ou "ç" no github, (ainda estou no inicio da jornada como Developer, quero seguir as boas praticas).
Comment: Na dúvida nunca use caractere especial enquanto estiver trabalhando com programação.
Answer: Github tem superte a caracteres unicode.
Mas para evitar problemas é recomendado evitar caracteres especiais.
Answer: não só para o Github, mas para qualquer projeto ou OS. Você deve seguir alguns parâmetros do que não utilizar para não ter problemas futuros em outras plataformas.
Vamos lá:
Não utilize esses caracteres:
<code>\
/
|
?
<
>
*
:
"
</code>
assim como, não utilize acentos (agudo, crase, circunflexo, tio). Não inicie o diretório com letras maiúsculas também.


Integrate $\int_{0}^{2\pi}\frac{1}{\sqrt{(1+a-\cos\theta)(3+a-\cos\theta)}}\mathrm{d}\theta$

Question: Consider the following integral with $a>0$:
\begin{equation}
I=\int_{0}^{2\pi}\frac{1}{\sqrt{(1+a-\cos\theta)(3+a-\cos\theta)}}\mathrm{d}\theta
\end{equation}
How does one deal with this integral?
I tried various substitutions such as $u=\cos\theta$ but nothing seems to work. I expect the integral to diverge at $a=0$, but for $a>0$ I should have a smooth behaviour.
Here is a list plot for $I$ in function of $a$:
Comment: Elliptic integrals ?
Comment: $$\int_0^{2\pi}\frac {1}{((k-(1+\cos x))(k+(1-\cos x)))^{\frac 12}}dx$$ Now try using half angle formula Not sure but seems if it's of third kind
Comment: I am not sure how I can use the half angle formula while there is this $k$?
Answer: $$
I=2\int_{0}^{\pi}\frac{d\theta}{\sqrt{(1+a-\cos(\theta))(3+a-\cos(\theta))}}$$
As @Darshan P. commented, use the tangent half-angle substitution to make
$$I=4\int_0^\infty\frac {dt} {\sqrt{\left(a^2+6 a+8\right) x^4+2\left( a^2+4a+2\right) x^2+a(a+2) }}$$ which is an elliptic integral.
We have for the antiderivative (forget the $4$ for time being)
$$-\frac{i F\left(i \sinh ^{-1}\left(x\sqrt{\frac{a+4}{a+2}}
   \right)|\frac{(a+2)^2}{a (a+4)}\right)}{\sqrt{a (a+4)}}$$where $F(.)$ is the elliptic integral of the first kind.
All of that makes
$$I=\frac{4}{\sqrt{a (a+4)}}K\left(-\frac{4}{a(a+4)}\right)=\frac{4 }{a+2}K\left(\frac{4}{(a+2)^2}\right)$$ where $K(.)$ is the complete elliptic integral of the first kind.
This is confirmed by Wolfram Alpha.
However, it seems that we do not agree. In order you check  your calculations, for $a=2$, the numerical value is $1.68575$. Also checked using Wolfram Alpha.
I also computed the original integral (see here). Notice that Wolfram Alpha returns just a number.
In terms of infinite series
$$I=\sum_{n=0}^\infty \left(\frac{\Gamma \left(n+\frac{1}{2}\right)}{\Gamma (n+1)}\right)^2 \left(\frac{2}{a+2}\right)^{2n+1}$$


Dúvida com recursividade

Question: Fiz teste de mesa mas o resultado nunca dará 0 porque subtrai 1 de n mas depois soma o resultado com n.
O resultado dessa questão foi 36 e não entendi porquê.
public class Recursivo{

    public static void main(String[] args) {

        int result = sum(8);

        System.out.println(result);
    }

    public static int sum(int n){
        if( n == 0){
            return 0;
        }
        else
        {
            return n + sum( n - 1);
        }
    }
}

O que realmente faz isso?
return n + sum( n - 1);

Comment: Porque haja que deve dar `0`?
Comment: Ele chega em 0 sim. A linha que vc está em dúvida que é a mais importante, ali que chama a função recursiva.
O 0 é o ponto de parada, ele subtrai o número informado de 1 em 1 até chegar a 0.
Comment: @GeorgeWurthmann O AP se refere ao resultado de `n + sum( n - 1);`
Answer:
O que realmente faz isso?
return n + sum( n - 1);

O método sum() fica se chamando sempre passando como parâmetro o próprio número que recebeu como argumento menos um, até que esse número chegue a zero que será quando ele retornará zero. Ou seja, se você passar o número 8, ele vai retornar 8 mais o retorno do método sum(7), que vai retornar 7 mais o retorno do método sum(6), que vai retornar 6 mais o retorno do método sum(5), que vai retornar 5 mais.... até chegar a 0, ou seja, cada vez que você chama o método sum(), ele soma esse valor com todos os seus valores inferiores até chegar a zero.
Para o caso em questão o retorno ficaria: 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0, ou seja: 36.
Para tentar debugar, coloquei uns prints para mostrar o que acontece em cada iteração:
public class Recursivo{

    public static void main(String[] args) {

        int result = sum(8);

        System.out.println("Resultado final: " + result);
    }

    public static int sum(int n){
        if( n == 0){
            System.out.println("Fim da recursividade");
            return 0;
        }
        else
        {
            System.out.println("O valor de n nessa iteração é: " + n);
            int ret =  n + sum( n - 1);
            System.out.println("O valor a ser retornado nessa iteração é: " + ret);
            return ret;
        }
    }
}

Resultado:

O valor de n nessa iteração é: 8
O valor de n nessa iteração é: 7
O valor de n nessa iteração é: 6
O valor de n nessa iteração é: 5
O valor de n nessa iteração é: 4
O valor de n nessa iteração é: 3
O valor de n nessa iteração é: 2
O valor de n nessa iteração é: 1
Fim da recursividade
O valor a ser retornado nessa iteração é: 1
O valor a ser retornado nessa iteração é: 3
O valor a ser retornado nessa iteração é: 6
O valor a ser retornado nessa iteração é: 10
O valor a ser retornado nessa iteração é: 15
O valor a ser retornado nessa iteração é: 21
O valor a ser retornado nessa iteração é: 28
O valor a ser retornado nessa iteração é: 36
Resultado final: 36

Perceba que existem dois prints dentro do else no método sum(), mas somente o primeiro é mostrado até que seja atingido o ponto final da recursividade, que é quando n chega a 0, e ao invés de chamar o próprio método novamente ele simplesmente retorna um valor.
Comment: Sim, ele soma `n`,  que no caso é `8`, com o valor que retornar uma nova chamada ao método `sum()`, que no caso vai ser `sum(7)`, que por sua vez vai fazendo novas chamadas, até que vai somar com `0` e vai para de chamar o método `sum()`. Vou tentar explicar melhor na resposta.
Comment: Sim, mas ele está somando n + sum( n - 1); Não entendi porque ele soma...
Answer: return n + sum( n - 1):

Nesta linha é somado o valor de n com o valor resultante do método sum(n-1).
No exemplo:
sum(8) = 8 + sum(7)
sum(7) = 7 + sum(6)
sum(6) = 6 + sum(5)
sum(5) = 5 + sum(4)
sum(4) = 4 + sum(3)
sum(3) = 3 + sum(2)
sum(2) = 2 + sum(1)
sum(1) = 1 + sum(0)
sum(0) = 0.

Repare que sum(0) não chama o método sum novamente. Este é o ponto de parada do método recursivo. Quando a recursividade encontra o ponto de parada, é só voltar toda a cadeia para ir somando os valores e obter o retorno.
Com isso substitui-se os valores:
sum(0) = 0.
sum(1) = 1 + sum(0) = 1 + 0  = 1
sum(2) = 2 + sum(1) = 2 + 1  = 3
sum(3) = 3 + sum(2) = 3 + 3  = 6
sum(4) = 4 + sum(3) = 4 + 6 = 10
sum(5) = 5 + sum(4) = 5 + 10 = 15
sum(6) = 6 + sum(5) = 6 + 15 = 21
sum(7) = 7 + sum(6) = 7 + 21 = 28
sum(8) = 8 + sum(7) = 8 + 28 = 36

Analisando o método sum mais de perto, ele faz a soma de todos os números de 1 até n, no exemplo dado: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
Comment: Ótima resposta, em especial o primeiro exemplo que deixou bem claro que as chamadas dos métodos vão se empilhando até que ele retorne algo e interrompa a recurssão, +1
Comment: Ahnnnnn ENTENDI

Dúvida com recursividade


How to deal with "non-integer" warning from negative binomial GLM?

Question: I am trying to model the mean intensities of parasites affecting a host in R using a negative binomial model. I keep getting 50 or more warnings that say:

In dpois(y, mu, log = TRUE) : non-integer x = 251.529000

How can I deal with this? My code looks like this:
mst.nb = glm.nb(Larvae+Nymphs+Adults~B.type+Month+Season, data=MI.df)

Comment: A negative binomial GLiM is a kind of count model. The response is supposed to be counts. A [count](https://en.wikipedia.org/wiki/Count_data), by definition, cannot be a fractional value. Do you have such values?
Comment: @Natasha, don't do it.  It is overwhelmingly likely that the right way to handle this problem is according to Gung's answer, with an offset.  If you want to be sure, edit your question to explain a little bit more about where the differential sampling intensities come from.  Are these different numbers of hosts?  Different lengths of time sampled, or number of collectors?
Comment: Please add a [reproducible example](http://stackoverflow.com/q/5963269/1217536) for people to work with.
Comment: I have count data, however I had to calculate the intensities to account for different sampling efforts. I do understand that I need count data there, however I was just wondering if there was another way to work with non-integer numbers using the same model.
For intensities I divided count of parasites with number of infected host.
Comment: @Natasha: Measuring intensity that way doesn't distinguish between counting 2 parasites across 10 hosts & 20 parasites across 100 hosts: Ben & gung are right.
Comment: Can you clarify what you mean by "intensities"? Are you dividing a count of a parasite by, say, an amount of surface area for a host?
Comment: Thanks for the link, I can use a quasi-Poisson without any errors. Maybe I'll stick to that. :)
Comment: See [How is it possible that Poisson GLM accepts non-integer numbers?](http://stats.stackexchange.com/q/70054/17230). You could perhaps come up with a quasi-negative-binomial regression approach, but in practice quasi-Poisson regression is considered an alternative to NB regression. Or use a model appropriate for a continuous response.
Comment: Test it to make sure it is really including the decimal part and if it isn't, write your own.
Comment: This doesn't make a lot of sense. A negative binomial GLiM is a count model. There shouldn't be fractional values. If there are fractional values, we need to figure out what's going on, not write a new function that will somehow shoehorn the fractional values into the model fit.
Comment: Actually the negative binomial really is defined for non-integer parameters. You are right to point out that only integers make sense for some problems because you can't have "half a failure" etc. See "extension to real-valued r" in the Wikipedia article. This became an issue for me when I was trying to use the method of moments and also when trying to use maximum likelihood estimation.
Comment: Non-integer parameters are fine, but it's still a distribution for discrete random variables.
Comment: That is true. So Gung was right to begin with.
Comment: there *are* cases where I can imagine non-integer response values making sense -- e.g. in cases of uncertainty ("I wasn't sure whether I counted 12 or 13 parasites in that host, so I'll score it as 12.5") -- but the default should be "if you're not *really, really sure* that you know what you're doing, pay attention to the warning.  Don't try to work around it -- figure out (as @Gung said initially) what's going on and modify your model accordingly."
Answer: The negative binomial is a distribution for count data, so you really want your response variable to be counts (that is, non-negative whole numbers).  That said, it is appropriate to account for "different sampling efforts" (I don't know exactly what you are referring to, but I get the gist of it).  However, you should not try to do that by dividing your counts by another number.  Instead, you need to use that other number as an offset.  There is a nice discussion on CV of what an offset is here: When to use an offset in a Poisson regression?  My guess is that your model should be something like:
mst.nb = glm.nb(Larvae+Nymphs+Adults ~ B.type+Month+Season + offset(log(num.hosts)),
                data=MI.df)

Comment: @Bakaburg, this is about how R works. Addition is elementwise. Adding 3 vectors gives you a single vector where each element is the sum of the 3 corresponding elements. To have multiple response variables on the LHS of an R formula, you need to use `cbind()`.
Comment: Thank you. I'll try this and get back to tell you'll what I did.
Comment: OT: i'm missing something, what does it mean to have many outcomes in a regression??
Comment: @Bakaburg, I can't tell what you are referring to.
Comment: The "Larvae+Nymphs+Adults~" part in the code.
Answer: It's a warning, not a fatal error. glm.nb() is expecting counts as your outcome variable, which are integers. Your data are not integers: 251.529.
R is saying "Hmmm... you might want to check this out and make sure it's OK, because it might not look right to be." If my memory is correct, SPSS doesn't give such a warning.
If you're sure that you're using the right model, even though you don't have integers, ignore it and keep going.
Comment: I know it is a warning, I was just wondering if there is a way around it. I do have integers though so I was trying to see if there is a way of working with integers but using the same model with a different code.
Comment: How to suppress warnings explained here:  https://stackoverflow.com/questions/16194212/how-to-suppress-warnings-globally-in-an-r-script
Answer: I'm an ecological parasitologist. The way you should handle this is by cbind-ing the hosts that were parasitised and the ones that were not, and then using a binomial distribution.
Let's say you want to look at parasitised larvae:
you would have n. of larvae that were healthy, and n. that were parasitised.
For example, given Lh and Lp:
parasitizedL=cbind(Lp, Lh)
hist(parasitized)

I'm guessing you can just use a regular binomial distribution with glm(), and might not need neg.binomial model.
PLarvae1=glm(parasitizedL~B.type+Month+Season, family=binomial,data=MI.df)

Then do stepwise model reduction to see which of your factors significantly effect parasitism: see this link.
However it looks like you need to have random effects to account for repetitive sampling, so likely your random effect will be (1|Season/Month), but it's hard to tell without knowing your data.


Relationship between "Erwäge" aria of St John Passion and final Chorus of St Matthew Passion

Question: The  "Erwäge" aria of Bach's St John Passion is harmonically extremely similar to the final Chorus of Bach's St Matthew Passion (to the extent that when listening to the former, I keep waiting for the chorus to break out in the latter). Is there any discussion somewhere of why Bach may have done this? Thematically they occur at different points of the passion. Possibly the answer is as simple as "he liked how it sounded" but perhaps there is a different answer.
Comment: I'm voting to close this question because its quite vague and appears more to attract comments than a definite answer.
Comment: I do think we in modern & post-modern musicians are apt to overthink the compositional processes of our forebears. Which is to say that your prosaic hunch is probably correct. That said, JS Bach was JS Bach: anything is possible.
Comment: This seems to fit better into Music Fans section, if not even into a chat.
Answer: One possibility is that he deliberately created musical connections between the two passions to emphasize that they were the same story. But Bach plagiarized himself multiple times, a common practice in the Baroque era.
The first movement of Brandenburg Concerto #1 is based on a violin sonata, and the second movement is a reworking of a harpsichord piece.  The second concerto incorporates themes from a harpsichord concerto, and the third movement is a reworking of a chorale melody. #5 features a harpsichord solo that is based on a piece from one of Bach's keyboard collections.
The Mass in B Minor is a large-scale work that incorporates material from several earlier compositions, including cantatas, motets, and chorales.


Connection Error with Laravel Passport and PostgreSQL

Question: I am installing a new API with Laravel Passport using POSTGRESQL databases. When installing Laravel and basic authentication, it works ok to the point of registering users and logging in perfectly. (take the database ok, this is important!) But when following the steps to install Passport and run the "php artisan migrate" command, Passport does not recognize that I am using POSTGRESQL and looks for the connection to MYSQL, which is non-existent. I will appreciate ideas, I don't know what else to do.
ERROR:
Illuminate\Database\QueryException

SQLSTATE[HY000] [1045] Access denied for user 'forge'@'localhost' (using password: NO) (SQL:
create table `oauth_auth_codes` (`id` varchar(100) not null, `user_id` bigint unsigned not
null, `client_id` bigint unsigned not null, `scopes` text null, `revoked` tinyint(1) not
null, `expires_at` datetime null) default character set utf8mb4 collate
'utf8mb4_unicode_ci')

at vendor/laravel/framework/src/Illuminate/Database/Connection.php:671
667|         // If an exception occurs when attempting to run a query, we'll format the
error
668|         // message to include the bindings with SQL, which will make this exception a
669|         // lot more helpful to the developer instead of just the database's errors.
670|         catch (Exception $e) {
671|             throw new QueryException(
672|                 $query, $this->prepareBindings($bindings), $e
673|             );
674|         }
675|

I try without result:
php artisan cache:clear
php artisan config:cache

My .ENV:
#DB_CONNECTION=mysql
#DB_HOST=127.0.0.1
#DB_PORT=3306
#DB_DATABASE=laravel
#DB_USERNAME=root
#DB_PASSWORD=

My CONFIG/DATABASE WITH POSTGRESQL:
'default' => env('DB_CONNECTION', 'pgsql'),

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => true,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],

    'pgsql' => [
        'driver' => 'pgsql',
        'url' => env('DATABASE_URL'),
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '5432'),
        'database' => env('DB_DATABASE', 'xxxx'),
        'username' => env('DB_USERNAME', 'xxxxxxxxxxx'),
        'password' => env('DB_PASSWORD', 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'),
        'charset' => 'utf8',
        'prefix' => '',
        'prefix_indexes' => true,
        'schema' => 'someschema',
        'sslmode' => 'prefer',
    ],

Answer: I finally found the solution in a Laravel Passport forum, it seems that in the latest versions the connection to the db is configured directly in passport (I don't know why it doesn't take the one from .env or config / databases), "publishing" (exporting) from the I sell the connection file that includes the Passport Storage Driver to the app, to be able to modify it and declare the connection exclusively for Passport. Needless to say, there are 3 different places in Laravel to declare a connection to the database, subject to chatting directly with Otwell.
Anyway, this is done with the following command:
php artisan vendor:publish --tag=passport-config

which adds a file in the config folder called passport.php, and where we find, ready to configure:
/*
|--------------------------------------------------------------------------
| Passport Storage Driver
|--------------------------------------------------------------------------
|
| This configuration options determines the storage driver that will
| be used to store Passport's data. In addition, you may set any
| custom options as needed by the particular driver you choose.
|
*/

'storage' => [
    'database' => [
        'connection' => env('DB_CONNECTION', 'mysql'),
    ],
],


Estimate on the first term in $(\ast)$

Question: Here, $\mathscr{S}(\mathbb{R})=\{f\in C^{\infty}(\mathbb{R}):\lVert f\rVert_{(N,\alpha)}<\infty\text{ for all non-negative integers }N\text{ and }\alpha\}$ is the Schwartz space ; where $$ \lVert f\rVert_{(N,\alpha)}=\sup_{x\in\mathbb{R}}\left\lbrack (1+|x|)^N \cdot\left\lvert f^{(\alpha)}(x)\right\rvert \right\rbrack. $$
Let $W_0:\mathscr{S}(\mathbb{R})\to\mathbb{C}$ be a map defined as :
$$ \langle W_0,\phi\rangle=\frac{1}{\pi}\lim_{\epsilon\to 0}\int_{\epsilon\leq |x|\leq 1}\frac{\phi(x)}{x}dx+\frac{1}{\pi}\int_{|x|>1}\frac{\phi(x)}{x}dx, $$for $\phi\in\mathscr{S}(\mathbb{R})$.
Our goal is to prove that $W_0$ is a tempered distribution.
For any $0<\epsilon<1$, we notice that $$ \int_{\epsilon\leq |x|\leq 1}\frac{1}{x}dx=\int_{\epsilon\leq x\leq 1}\frac{1}{x}dx+\int_{-1\leq x\leq -\epsilon}\frac{1}{x}dx=\int_{\epsilon\leq x\leq 1}\frac{1}{x}dx+\int_{1\leq x\leq \epsilon}\frac{1}{x}dx=0 .$$
Thus, we can write, for $\phi\in\mathscr{S}(\mathbb{R})$, $$ \langle W_0,\phi\rangle=\frac{1}{\pi}\lim_{\epsilon\to 0}\int_{\epsilon\leq |x|\leq 1}\frac{\phi(x)-\phi(0)}{x}dx+\frac{1}{\pi}\int_{|x|>1}\frac{\phi(x)}{x}dx. \hspace{2cm}(\ast)$$
We note that $$ \left\lvert\int_{|x|>1}\frac{\phi(x)}{x}dx\right\rvert\leq\int_{|x|>1}|\phi(x)|dx=\int_{|x|>1}\frac{|\phi(x)|\cdot(1+|x|)^2}{(1+|x|)^2}dx\leq\lVert \phi\rVert_{(2,0)}\cdot\left(\int_{\mathbb{R}}\frac{dx}{(1+|x|)^2} \right)=2\lVert \phi\rVert_{(2,0)}. $$
So, the second term in the right side of the equality in $(\ast)$ is bounded by $\frac{2}{\pi}\cdot\lVert\phi\rVert_{(2,0)}$.
Prof. Grafakos has directly written in his book $\textbf{Classical Fourier Analysis}$ that the fraction $\frac{\phi(x)-\phi(0)}{x}$ is controlled by $\lVert\phi'\rVert_{\infty}$ so we have the estimate $$ |\langle W_0,\phi\rangle|\leq\frac{2}{\pi}\cdot\lVert\phi'\rVert_{\infty}+\frac{2}{\pi}\cdot\lVert\phi\rVert_{(2,0)}. $$
I am not able to prove that the fraction $\frac{\phi(x)-\phi(0)}{x}$ is controlled by $\lVert\phi'\rVert_{\infty}$. It seems very easy and trivial but I am unable to prove this rigorously. Please give me some hints or solution. Thanks.
Comment: Note that $\int_1^\infty \frac2{1+x^2}\,dx=\frac\pi2$ and $\int_0^\infty \frac2{1+x^2}\,dx=\pi$, neither of which is equal to $2$.  The former is certainly less than $2$ and this inequality leads to the reported result.
Answer: Since $\phi\in \mathbb{S}$, we can write $\phi(x)-\phi(0)=\phi'(\xi(x))x$ for $\xi(x)$ between $0$ and $x$.
Then, we have
$$\begin{align}
\left|\int_{\varepsilon\le |x|\le 1}\frac{\phi(x)-\phi(0)}{x}\,dx\right
|&=\left|\int_{\varepsilon\le|x|\le1} \phi'(\xi(x))\,dx\right|\\\\
&\le\int_{\varepsilon \le |x|\le 1}|\phi'(\xi(x))|\,dx\\\\
&\le ||\phi'||_{\infty}\int_{\varepsilon \le |x|\le 1}1\,dx\\\\
&\le 2 ||\phi'||_{\infty}
\end{align}$$
as was to be shown!

Estimate on the first term in $(\ast)$


What is the difference between $H^1_{loc}$ and $H^1$?

Question: I have started studying Sobolev spaces and I came across a space referred to as $H^1_{loc}$. I am not sure what the $loc$ subscript infers? What is it that makes this space different from $H^1$? Why would you every specify this space instead of $H^1$?
Comment: Usually loc means local. So I guess $H^1_{loc}$ would mean the set of functions that are locally $L^2$ and have weak derivatives that are locally $L^2$ too. Being locally $L^2$ means that $\int_K |f|^2 < \infty$ for compact sets $K$.
Comment: Where did you find such notation? Can you give us the source material?
Comment: @jooi What is the significance of the functions being integrable on compact sets?
Comment: @jooi: If you're working in a domain in $\Bbb R^n$, then it just means that around every point $x$ in the domain, there's a neighborhood on which the function is $H^1$. It's just about demanding sufficient integrability/differentiability hypotheses on your function locally without making such demands globally (so, eg, the integral of your function over the whole domain needn't be finite).
Comment: Sorry, that ping was supposed to be @Riggs.
Answer: For J.L. Lions and others, $H^m_{loc}(\Omega)$ spaces are made of functions of $H^m(\Theta)$ where $\Theta$ represents any open subset such that $\bar{\Theta}\subset \Omega$. This allows to define a family of seminorms, the norms in $H^m(\Theta)$, and in the end these spaces are Frechet spaces.


In organ scores sometimes it says positif or recitive - which keyboard do they mean for these? Swell or great?

Question: Which keyboard do they mean on organ when music says positif and recitive?
Answer: The answer depends whether you are asking about the physical arrangement of the manuals, or their musical function.
The "standard" 19th century French arrangement for a 3 manual console was Grand Orgue at the bottom, Positif in the middle, and Récit at the top. For instruments with more than 3 manuals, the additional ones were above the Récit.
On the other hand, in their musical function the Positif is closer to the English Choir and the Récit to the English Swell - i.e. a "standard" English 3 manual console has the "Positif" above the "Récit".
That's the theory, but in practice you may have to find the registrations that give the nearest equivalent registrations to the "French organ sound", and play them on whatever manual is most convenient. A typical small English Choir division is a very wimpy replacement for a French Positif with some "in your face" reed stops, and you might be better off using a reduced registration on the English Great, or coupling some stops from the Solo division of a large English instrument.
As a famous organist once said, "you never actually play 'composer X' or 'composer Y' on an organ. You always finish up playing 'composer X or Y, in an arrangement made by the organ-builder"!
(And as somebody else once said, "The only registrations you need to play any French organ toccata are a really loud noise on the manuals, a really really really loud noise on the pedals, and full swell with the box completely closed for the boring middle section that nobody listens to anyway.")


Django REST framework serializing model combinations

Question: I'm programming an online game with a JavaScript client and I use Django REST framework for the backend. I have written a quest system for it.
My quests objects are dynamically created from a django model QuestTemplate which stores information like the Quest desription and the titel (the part that is the same for every user); and another model QuestHistory  where I put the information about the state of quest for a certain user: so it has fields like user and completed. They also have some nested objects: Tasks and, Rewards which are created in a similar way to the the Quest objects.
I added a pure python class Quest that combines all the fields of those models, and then I wrote a Serializer for this class. The drawback is that I have to define all the fields again in the QuestSerializer
I have seen that for the ModelSerializer you can use a inner class Meta where you specifiy the model and . Is there also a way to do this with a normal python class instead of a model (with my Quest class).
http://www.django-rest-framework.org/api-guide/serializers#specifying-nested-serialization
Or:
Is it possible to specify more than one model in this inner class, so that it takes fields from my  model QuestTemplate and some other fields from my model QuestHistory?
(I'm also not sure about whether this structure makes sense and asked about it here: django models and OOP design )
Answer: In the class Meta of the ModelSerializer you can specify only one Model as far as I know. However there are possibilities to add custom fields to the serializer. In your case you could maybe try with:
custom_field = serializers.SerializerMethodField('some_method_in_your_serializer')

You should add the method to your serializer like this:
def some_method_in_your_serializer(self, obj):
    # here comes your logic to get fields from other models, probably some query
    return some_value # this is the value that comes into your custom_field

And add the custom_field to fields in the class Meta:
class Meta:
    fields = ('custom_field', 'all_other_fields_you_need')

Take a look in the documentation about SerializerMethodField for deeper understanding.


How to include a caption (a cck field) in lightbox?

Question: I'm working on a theme i bought and since i'm just learning php i'm having a hard time including a field as a description text in the lightbox once the thumbnail is clicked.
Here's the code (that's in the tpl.php file) that outputs the thumbnails (from a view)
<?php
if (isset($fields['field_image']->content) and strpos($fields['field_image']->content, '<img')) {
 print str_replace('<a ', 'content); ...
?>

Here's the html version of the lightbox script :
<img ...

How can in include the caption tag ?
Thanks !!
Comment: Relevant question that may be of help: http://drupal.stackexchange.com/questions/29252/get-the-title-attribute-into-a-lightbox-frame/141870#141870
Answer:

Both the caption and the description will be displayed on the image preview.
Comment: Hi,
Thank you for the reply but i don't really understand what you said.
The html version i used is just an example of how the script works.

What i want is a way to dynamically include the caption in the php script. (the one that's in the tpl.php file)

I can hardcode it and it would be something like this :

`print str_replace('<a ', '<a rel="prettyPhoto[gallery]" title="Hardcoded Caption" '...`
Comment: Ok, so do you ask how to access a CCK field or how to embody a string in the lightbox frame ?
Comment: Yes i want to access a cck field and include it in the lightbox script as a caption

Screenshot : [https://img.skitch.com/20120112-cihwefn7nq18ysu53uhruniui3.jpg]
Comment: Ok, there exist a basic approach to this problem. Type `` in node.tpl.php to see what's available in the node object (what fields, how formatted, etc.) and then take what you want and output it to the lightbox. I hope that's what you need..
Comment: I fail to understand how this answer is helpful to the question asked.


How to build same project with two different java version and target into two seperate folder?

Question: I have a maven project .whenever it pushes into gitlap, it will be deployed with single java version using CI option. I need to build with two different java version on same project when commit the project. So, How to create pom file to achive this using maven?
Comment: Just build with Java 8 and it can simply run on Java 12...?
Comment: Why do you need to build with two different java versions? Which versions?
Comment: Because of clients who is not ready to change to latest java .thats why i need two build .I need for java 8 and java 12
Comment: you are correct thanks
Answer: I got englightened by @khmarbaise comment and made me think this way as follows,
I have a java project which compile with java8 and can run on higher version than this, in my case java 12. So, creating two build with two different java version on same project is not necessory as i know.
In another case, even if i use "java12 feauture" on project,i could not compile with java8, So, i have to create two different project for java8(for clients needs) and java12. So,There is no complication in this scenerio to achieve my needs.
if any scenerio i miss here, please comment!!!
Comment: With Java 9 they introduced the multirelease jar and it is supported by Maven, see https://maven.apache.org/plugins/maven-compiler-plugin/multirelease.html . However, think twice before using it, because it is a lot harder to maintain.
Comment: The question is: What feature of Java 12 do you really need? And of course follow the guidelines of Robert...


Get node url alias/path when loading the node using node_load()

Question: Does the node_load() does not return the node url alias in the node object or am I missing something.
I know one way of getting the url alias/path is using the drupal_get_path_alias("node/NODE_ID"), however I was hoping the object return by node_load should contain node url alias as well.
Answer: No, the URL alias is not a field nor entity property, and it doesn't get added to the node object when it's loaded.
It would be trivial to add that data though, using hook_node_load()
function MYMODULE_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->url_alias = url("node/$node->nid");
  }
}


Converter Data para ano / mês

Question: Consegui converter a data para ano / mês, mas necessito que a data saia assim: 2019/04, mas está saindo assim: 2019/4
como posso resolver isso?
SELECT CONVERT(VARCHAR(4), DATEPART (year,'01/04/2019')) + '/' + CONVERT(VARCHAR(4),DATEPART(month,'01/04/2019')) as AnoMes

Comment: select (convert(varchar(200), year(convert(date, '01/04/2019'))) + '/' + convert(varchar(200), month(convert(date, '01/04/2019')))) as AnoMes
Answer: Tente dessa forma:
    select format(CAST('04/01/2019' AS DATE), 'yyyy/MM');

Esse teste que fiz tive que colocar a data como 'MM/dd/yyyy'.
Answer: Experimente
-- código #1
SELECT convert (char(7), nome_coluna, 111) as AnoMes
  from tabela;

onde nome_coluna está declarada como date, datetime ou algum outro tipo de dados específico para armazenamento de data.
O estilo 111 refere-se ao formato 'aaaa/mm/dd'.
Exemplo:
-- código #2
declare @data date;
set @data= convert (date, '1/4/2019', 103);  -- dd/mm/aaaa

SELECT convert (char(7), @data, 111);

Answer: O SQL fornece algumas conversões prontas de data e hora, aqui tem uma tabelinha:
https://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/
Conforme o link, poderia estar sendo feito assim:
SELECT CONVERT(CHAR(7), GETDATE(), 111) AS [ANO/MES]
FROM TABELA

O padrão de retorno quando você faz CONVERT(VARCHAR, DATA, 111) é 'YYYY/MM/dd', substituindo VARCHAR por CHAR(7) ele irá retornar os 7 primeiros caracteres: 'YYYY/MM'

Converter Data para ano / mês


Show content of custom content type in a block based on taxonomy term

Question: In D8 I have created two custom content types:

Store
Store products

It's not an e-commerce, I just need two custom types to show all the stores on one of the subpages and the products that each store has.
Because there are 24 stores, I would hate to create 24 custom types of a store products, so I also added a taxonomy term field to a Store product.
Now, I would want to show the Store products in a Block, depending on the taxonomy term.
For example:
I created Store A, which has products A1, A2, A3. If I go to the page of Store A, there should be a block that shows those products.
If I would go to Store B, the same block would show products of Store B.
I tried following this answer and added a contextual filter, but no luck so far:
Display content based on URL
What I did:

Created a View Block for Store Products
Added a contextual filter to the block (Has taxonomry term -> taxonomy term ID from URL)
Also added another contextual filter node:id
Added the block under blocks to render on the page Store
Comment: Its probably better if you describe what you also did try, some code or views setup description.
Answer: What you're trying to do already come out of the box in "Taxonomy term" content views.
If you have tagged your Store product nodes with taxonomy terms these nodes will appear on the related term pages. You don't need a separate Block, the term pages will show a list of nodes tagged with that term.
You don't even need the Store content type if its whole purpose is to provide categorization. The "Store" Taxonomy Vocabulary is all you need.
Can you try and see if that is enough for you?

In your Contextual configuration you should use the option "Load default filter from term page", and not "Load default filter from node page" because the information is taken from the taxonomy term page, you're not showing a block on a node page.
Why do you need the second Contextual for NID? This is usually used when you want to exclude the current node from the list (Under More > Exclude), but you're not on a node page so there is nothing to comare the NID to. Remove that second Contextual, you don't need it.
Comment: Those are all entities, you can add fields to Taxonomy terms just as you would to Content types! And you can show them in Views just like you would if the Store were nodes. Simply add the relevant fields to your Vocabulary, and inside Views add the Relationship for the field that connects your nodes to the Taxonomy terms. When you add that relationship you'll be able to show taxonomy term logo and description as fields, filters, what ever you need. The procedure would have been the same if Store were nodes, you'd still have to add the Relationship for that entity reference field.
Comment: Thanks for clarifying some things to me. I changed the filters as you proposed, but I still can't get the block to show.

The reason why I created content type for store also is because I need to have a different logo and some text content for each one. And then, based on the name of the store, the "store products blocks" should render items that belong to that store - based on the taxonomy term. Or at least that's what I thought should be the easiest way to do it.
Comment: As you said, I tried and am able to do it with taxonomy terms only. I added some fields to taxonomy term to describe the store, and the products are listed automatically.


Loop through nested array in Twig

Question: I have created a variable to use in my twig template. The variable consists of a nested array. If I dump the variable I get the following result:

dump(gallery_images)
array (size=2)
  'img' =>
    array (size=15)
      0 => 'path-to-file.jpeg'
      1 => 'path-to-file.jpeg'
      .....
   'alt' =>
    array (size=15)
      0 => 'img 1 alt text'
      1 => 'img 2 alt text'

I want to loop through gallery_images and map the alt text to the image. My loop was working fine before I added the nested array / alt text. This is how I expected it to work:
{% for gallery_image in gallery_images %}

{% endfor %}

That did not work, then I tried to call the src and alt with
{{ gallery_image.0 }}
{{ gallery_image.1 }}

Then I only got 1 file and 1 alt text. What is the correct way to loop through the nested array? Also bear in mind I may want to add title text next.
Answer: Do you have control over your array structure?
Why not just change it to this:
[
  0 => ['alt' => 'alt text', 'img' => 'image-path'],
  1 => ...?
]

Because then your logic would work, but right now you have the reversed structure. What you could do is loop over the image paths with {% for key, path in gallery_images.img %} and use the key toaccess gallery_iamges.alt[key]` (not 100% sure about the exact syntax). Certainly more complicated that way.
Comment: Yes I do have control because I am creating the array in the .theme file, so I will try that. Thanks.

Loop through nested array in Twig