Como inverter a posição de uma div(e seu conteudo e atributos) com outra div?

Question: Desejo fazer isso com jQuery, qual a forma mais elegante de se fazer isso?
Supondo o cenário a seguir, como ficaria se eu quisesse trocar de posição a div2 com a div3? (não postarei o meu código real que é muito grande)

 Conteúdo da Div

 Conteúdo da Div

 Conteúdo da Div

 Conteúdo da Div

Comment: Quem chegou agora, ignore os *downvotes* e dê uma olhada na minha [resposta](http://br.stackoverflow.com/questions/669/como-inverter-a-posicao-de-uma-dive-seu-conteudo-e-atributos-com-outra-div/675#675) para ver um método que troca elementos independentemente da estrutura.
Comment: Não acredito que ninguém ainda sugeriu a [solução clássica...](http://br.stackoverflow.com/questions/669/como-inverter-a-posicao-de-uma-dive-seu-conteudo-e-atributos-com-outra-div/690#690)
Answer: Método simplificado:
Uma forma de relizar a operação pretendida, com pouco código mas limitado a elementos que se encontram um ao lado do outro, é fazer uso do método de jQuery .before(), onde o que é feito é pegar no $ele2 e passar o mesmo para antes do $ele1:
function switchElements($ele1, $ele2) {
    $ele1.before($ele2);
}

switchElements($('#div2'), $('#div3'));

Ver exemplo no JSFiddle.
Também podemos utilizar o método de jQuery .after() que fará o inverso:
function switchElements($ele1, $ele2) {
    $ele2.after($ele1);
}

switchElements($('#div2'), $('#div3'));

Ver exemplo no JSFiddle.
Nota:
Isto são tudo métodos de jQuery muito semelhantes aos já sugeridos em outras respostas.
Por outro lado é limitado pelo facto de que a sensação de "trocar de posição" só é tida se os elementos estiverem lado a lado.

Método genérico:
Uma maneira para realizar o pretendido pode ser atingida fazendo uso do método de jQuery .clone() e do método .replaceWith():
// cache elements
var $div1 = $('#div1'),
    $div2 = $('#div2');

// clone elements and their contents
var $div1Clone = $div1.clone(),
    $div2Clone = $div2.clone();

// switch places
$div1.replaceWith($div2Clone);
$div2.replaceWith($div1Clone);

Ver exemplo no JSFiddle.

Passando este exemplo para uma função:
function switchElements($ele1, $ele2) {

    // clone elements and their contents
    var $ele1Clone = $ele1.clone(),
        $ele2Clone = $ele2.clone();

    // switch places
    $ele1.replaceWith($ele2Clone);
    $ele2.replaceWith($ele1Clone);
}

Utilização:
// cache elements
var $ele1 = $('#div2'),
    $ele2 = $('#div3');

switchElements($ele1, $ele2);

Ver exemplo no JSFiddle.
Comment: @GuilhermeBernal Não, não funciona dessa forma, por isso tive o cuidado de deixar a nota que esse método só faz "troca" quando os elementos estão lado a lado. Por isso é que não sugeri em primeiro lugar. Para trocar elementos "longe" uns dos outros, é preciso utilizar o "método genérico". :) ver [JSFiddle](http://jsfiddle.net/34Jcy/).
Comment: O "simplificado" não funciona. Experimente inverter a `#div2` com a `#div4`.
Answer: Vejo muitas abordagens diferentes, mas nenhuma usando o clássico algoritmo de se trocar duas variáveis de valor:
swap = a
a = b
b = swap

No caso de jQuery ficaria assim:
function trocar(a, b) {
    var swap = $("");
    a.after(swap).detach();
    b.after(a).detach();
    swap.after(b).detach();
}

Esclarecendo:

a.after(swap) coloca swap logo após a, retornando a si mesma;

a.detach() remove a si mesma do DOM - mas mantendo dados e ouvintes:

O método .detach() é o mesmo que .remove(), exceto que .detach() mantém todos os dados jQuery associados com os elementos removidos. Esse método é útil quando os elementos removidos serão reinseridos no DOM em um momento posterior.

Exemplo completo no jsFiddle.
Answer: Nota
Minha resposta inicial era simplista e não funcionava em 100% dos casos. Fiz então uma implementação um tanto complexa, mas ainda não fiquei satisfeito, assim como com as outras respostas.
Estou considerando apenas as soluções gerais, isto é, que se aplicam a troca de quaisquer elementos em níveis e posições diferentes.
Análise das soluções propostas
A mais simples e direta é a do @mbigsonbr, mas fiquei com um pé atrás por causa da criação e inserção de um elemento desnecessariamente.
A resposta do @Zuul de clonagem também é simples e interessante, mas também parece ainda mais pesada.
A minha resposta parece muito complexa. Será que é necessário tudo aquilo?
O teste de desempenho
Decidi então aplicar as diferentes técnicas e fazer um teste de desempenho. Os resultados confirmaram minhas suspeitas:

A clonagem é muito lenta
Minha solução foi discretamente mais rápida que as demais quando os elementos estão no mesmo nível, mas devido à complexidade e ao uso excessiva da API do jQuery, quando os estão em níveis diferentes do DOM, o desempenho foi equivalente.

Ainda não satisfeito, cheguei à conclusão de que a solução do @mgibsonbr poderia ser facilmente convertida para Javascript puro. Fiz novamente o teste e parece que finalmente achei algo interessante.
Vejamos o resultado no gráfico abaixo:

A legenda é a seguinte:

Azul escuro: o meu algoritmo com nós do mesmo nível
Vermelho: o meu algoritmo com nós de níveis diferentes
Amarelo: o algoritmo original do @mgibsonbr com nós do mesmo nível
Verde escuro: o algoritmo original do @mgibsonbr com nós de níveis diferentes
Roxo: o algoritmo modificado do @mgibsonbr com nós do mesmo nível
Azul claro: o algoritmo modificado do @mgibsonbr com nós de níveis diferentes
Pink: o algoritmo do @Zuul com nós do mesmo nível
Verde claro: o algoritmo do @Zuul com nós de níveis diferentes

Teste no jsperf
O meu algoritmo
(function ($) {

    $.fn.swap = function(anotherElement) {

        var sameParentStrategy = function(one, another) {
            var oneIndex = one.index();
            var anotherIndex = another.index();
            var swapFunction = function(first, second, firstIndex, secondIndex) {
                if (firstIndex == secondIndex - 1) {
                    first.insertAfter(second);
                } else {
                    var secondPrevious = second.prev();
                    second.insertAfter(first);
                    first.insertAfter(secondPrevious);
                }
            }
            if (oneIndex < anotherIndex) {
                swapFunction(one, another, oneIndex, anotherIndex);
            } else {
                swapFunction(another, one, anotherIndex, oneIndex);
            }
        };

        var differentParentsStrategy = function(one, another) {
            var positionStrategy = function(e) {
                var previous = e.prev();
                var next = e.next();
                var parent = e.parent();
                if (previous.length > 0) {
                    return function(e) {
                        e.insertAfter(previous);
                    };
                } else if (next.length > 0) {
                    return function(e) {
                        e.insertBefore(next);
                    };
                } else {
                    return function(e) {
                        parent.append(e);
                    };
                }
            }
            var oneStrategy = positionStrategy(one);
            var anotherStrategy = positionStrategy(another);
            oneStrategy(another);
            anotherStrategy(one);
            return this;
        };

        //check better strategy
        var one = $(this);
        var another = $(anotherElement);
        if (one.parent().get(0) == another.parent().get(0)) {
            console.log('sameParentStrategy');
            sameParentStrategy(one, another);
        } else {
            console.log('differentParentsStrategy');
            differentParentsStrategy(one, another);
        }

    };

}(jQuery));

Demo no jsfiddle.
O algoritmo modificado do @mgibsonbr
(function ($) {
    $.fn.swap = function(anotherElement) {
        var a = $(this).get(0);
        var b = $(anotherElement).get(0);
        var swap = document.createElement('span');
        a.parentNode.insertBefore(swap, a);
        b.parentNode.insertBefore(a, b);
        swap.parentNode.insertBefore(b, swap);
        swap.remove();
    }
}(jQuery));

Modo de Usar
$(elementSelector).swap(anotherElementSelector);

Comment: Bem, criei essa função de propósito geral que se acopla ao jQuery e troca dois elementos em qualquer tipo de estrutura. Por favor, avaliem e critiquem.
Answer: Eis uma função que dá conta de inverter quaisquer elementos que sejam irmãos no DOM, sem utilizar clonagem:
function inverterPosicoes(el1, el2) {
    el1 = $(el1);
    el2 = $(el2);
    var prev = el1.prev();
    var parent = el1.parent();

    // Move o primeiro elemento para a posição do segundo
    el2.after(el1);

    // Move o segundo elemento para onde o primeiro estava
    if (prev.length) {
        // Se o primeiro elemento não era o primeiro filho
        prev.after(el2);
    } else {
        // Se o primeiro elemento era o primeiro filho
        parent.prepend(el2);
    }
}

http://jsfiddle.net/342LP/
Comment: @Guilherme Sua edição me fez pensar... http://meta.br.stackoverflow.com/questions/249
Answer: Se os elementos forem vizinhos, use insertBefore:
$('#div3').insertBefore($('#div2'));

Exemplo
Exemplo executável: http://jsfiddle.net/rodrigorgs/uya47/
Explicação
A documentação do jQuery esclarece:

Pode-se selecionar um elemento da página e inseri-lo antes de outro:
$( "h2" ).insertBefore( $( ".container" ) );
Se um elemento selecionado dessa forma for inserido em um único local no DOM, ele será movido para o alvo (e não clonado).
Se houver mais de um elemento alvo, no entanto, serão inseridas cópias do elemento para cada alvo após o primeiro.

(tradução livre)
Conforme escreveu @utluiz, pode-se também usar o insertAfter; neste caso, inverte-se a ordem dos elementos.
Comment: Não funcionou. Experimente inverter a `#div1` com a `#div4`.
Comment: Você está certo, eu não tinha pensado no caso geral =/
Answer: Tente isto:
function alterPosition(idElement1, idElement2){
    var div = $(idElement1).clone();
    $(idElement1).remove();
    $(idElement2).before(div);
}

Comment: Eu posso estar a ler mal a tua função, mas parece-me que estás a remover o primeiro elemento, e depois vais ao segundo elemento e inseres antes dele o primeiro elemento... ou seja, fica tudo igual, não ocorreu troca de posições! :( ([JSFiddle](http://jsfiddle.net/rcpn4/))
Comment: Preppend não insere **antes** do elemento?
Comment: O correto é o .before(), .prepend() adiciona antes de todo o conteudo da tag selecionada...obrigado pela observação...
Comment: Acho que realmente você entendeu errado, eu excluo o atual, e insiro ele antes do elemento desejado, de acordo com o parametro....
Comment: @KennyRafael Sim, mas no Fiddle com o teu código, as `div` não trocam de posição, ve o link que deixei no comentário. _(posso ter algo errado no Fiddle, se assim for, diz!)_
Comment: Inverta os parâmetros! ;P
Comment: E ai, deu certo?
Comment: Seja pelo menos humilde a ponto de tirar o votedown...
Comment: @KennyRafael Fiz um teste rápido mas não funcionou. Agora em relação ao votoNegativo, lamento mas **não fui eu**... podes aceder ao meu perfil para confirmar que não dei votos negativos a ninguém!
Comment: @KennyRafael Para que garantas que determinado utilizador lê a resposta que colocaste num comentário, utiliza `@nomeDoUtilizador`, para que ele seja notificado que tem uma resposta por ler ;)
Comment: @Zuul Ok então, porém antes de questionar a resposta de outra pessoa, certifique-se de fazer os testes corretamente, pois meu código funciona, pode não ser o ideal, mas funciona e é como eu faria antes de conhecer outras opções, você não precisa falar mal do código dos outros para promover sua resposta.
Comment: @KennyRafael Isto é um pouco estranho, parece que pelo facto de alertar para um detalhe em relação ao teu código passei a ser um "inimigo" ? Só estava a querer ajudar, até me dei ao trabalho de fazer um Fiddle com o teu código para se verificar o que pode estar mal e retificar. Também tive o cuidado de dizer que podia estar a ver mal a questão, mas outras pessoas votaram no comentário o que diz que concordaram com o que foi dito. Honestamente não entendo porque está assim de "pé atrás" em relação a tudo isto.
Comment: Pensares que estou a "promover a minha resposta" através desta tentativa de ajudar, realmente deixa-me um pouco triste! Futuramente vou-me abster de comentar ou alertar para conteúdos das tuas perguntas ou respostas! A critica positiva/negativa não parece cair-te bem! :(


How do I tell Drupal 8 to use my custom module's theme template when rendering an image that is linked?

Question: I'm building a custom module to extend the default image field. It adds additional attributes that relate to the image field on a per content type basis. At this point it will take and store the attributes => values and when calling hook_preprocess_field() they can be returned (printed) so I can rest assured that they are indeed storing and relating correctly. The final part of the puzzle is to assign my twig template and insert my custom attributes. I thought that hook_theme() would do the job but so far I have failed and I can't find any suitable documentation on the subject when it comes to fields or image fields.
How do I tell Drupal to use my custom module's template when rendering an image that is linked?
Comment: @mradliffe, thanks for chiming in. I wasn't sure if this question would gain any traction. By extending, I mean that I don't want to change the field formatter on the display settings page for the content type. I just want to add options for a few attributes (rel, target, class). This is specific to image fields and specific to the image linking to "file". I have built custom field formatters for other projects but in this case, I am specifically interested in extending the default image field formatter rather than creating a new one. Thanks for any assistance/feedback you can provide.
Comment: A little more digging shows that the default image formatter is located at: 'core/themes/stable/templates/field/image-formatter.html.twig'. I need to override that and provide my own within my module. hook_theme() doesn't seem to do the job. I may be able to use hook_theme_registry_alter(), providing I can get it to use the path I give it to my module. It may be a little heavy handed though.
Comment: Thanks for that... I've now been looking at the `hook_field_info_alter()` and it might be useful to change the `$info['image'][default_formatter]` to my own in its place. I've been looking at a lot of approaches on this so I need to give it some more thought first.
Comment: What do you mean by "extend the default image field"? This could be creating a new field type, changing the plugin class to use your own class, making a template for image render types.
Comment: I understand now. If you want to override the class used by a field type, then `hook_field_info_alter` is the only way. Change the `$info['image']['class']` or what not to your new class. And then it needs a `drush cr && drush entup` I think you don't need to provide an annotation. I haven't tried that before.
Comment: @mradcliffe, thanks for the help. I couldn't find a solution with `hook_field_info_alter()` I ended up using `hook_theme_registry_alter()` and it did the trick.
Answer: Answering my own question. The solution was to use: hook_theme_registry_alter()
/**
 * Implements hook_theme_registry_alter
 */
function MY_MODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['image_formatter']['path'] = drupal_get_path('module', 'MY_MODULE') . '/templates/field';
}
In my module I have the templates/field directory with the template image-formatter.html.twig, so no other changes were necessary.


Show that $Z-\tilde{Z}_{\iota_{\nu}}$ and $\tilde{Z}$ are independent.

Question:

Let $Z\sim N(a\iota_{\nu},I_{\nu}), a\in\mathbb{R}$ whereat
    $$
\iota_{\nu}=\begin{pmatrix}1\\1\\\vdots\\1\end{pmatrix},~~~I_{\nu}=\text{diag}(1,\ldots,1).
$$
    Show that $Z^TZ=(Z-\tilde{Z}_{\iota_{\nu}})^T(Z-\tilde{Z}_{\iota_{\nu}})+\nu\tilde{Z}^2, \tilde{Z}:=\sum_{i=1}^{\nu}Z_i/\nu$. Furthermore, show that $Z-\tilde{Z}_{\iota_{\nu}}$ and $\tilde{Z}$ are stochastically independent and determine the distributions of $Z-\tilde{Z}_{\iota_{\nu}}$ and $\tilde{Z}$.

Hi, I think the first and the last task are not that difficult:
It is $Z^TZ=\sum_{i=1}^{\nu}Z_i^2$ and
$$
(Z-\tilde{Z}_{\iota_{\nu}})^T (Z-\tilde{Z}_{\iota_{\nu}})=\sum_{i=1}^{\nu}(Z_i-\tilde{Z})^2=\sum_{i=1}^{\nu}Z_i^2-2\tilde{Z}\sum_{i=1}^{\nu}Z_i+\nu\tilde{Z}^2\\=\sum_{i=1}^{\nu}Z_i^2-2\nu\tilde{Z}^2+\nu\tilde{Z}^2=\sum_{i=1}^{\nu}Z_i^2-\nu\tilde{Z}^2,
$$
so
$$
(Z-\tilde{Z}_{\iota_{\nu}})^T (Z-\tilde{Z}_{\iota_{\nu}})+\nu\tilde{Z}^2=\sum_{i=1}^{\nu}Z_i^2=Z^TZ.
$$
Moreover, the $Z_i, i=1,\ldots,\nu$ are independent (because the covariance matrix is diagonal), so it follows that
$$
\tilde{Z}\sim N(a,1/\nu).
$$
Write $Z-\tilde{Z}_{\iota_{\nu}}=c+I_{\nu}Z, c:=-\tilde{Z}_{\iota_{\nu}}$, then it follows that
$$
Z-\tilde{Z}_{\iota_{\nu}}\sim N(a\iota_{\nu}-\tilde{Z}_{\iota_{\nu}}, I_{\nu}).
$$
This should be ok. But how can I show that $Z-\tilde{Z}_{\iota_{\nu}}$ and $\tilde{Z}$ are independent?
Comment: Are $\tilde{Z}_{\iota_{\nu}}$ and $\tilde{Z}$ the same thing? If they are, you can't have $Z-\tilde{Z}_{\iota_{\nu}}\sim N(a\iota_{\nu}-\tilde{Z}_{\iota_{\nu}}, I_{\nu})$, because $\tilde{Z}$ is random.
Comment: It is $\tilde{Z}=\frac{1}{\nu}\sum_{i=1}^{\nu}Z_i$ and $\tilde{Z}\iota_{\nu}=\begin{pmatrix}\tilde{Z}\\\vdots\\\tilde{Z}\end{pmatrix}$. So its not the same. Nevertheless you are right...
Comment: How can I then determine the distribution of $Z-\tilde{Z}\iota_{\nu}$?
Answer: Well the mean of
$Z-\tilde{Z} {\iota_{\nu}}$ is 0, so the value of $a$ might as well be 0.
You can show independence of $Z-\tilde{Z} {\iota_{\nu}}$ and $\tilde{Z}$ by looking at their covariances, and using the property of Multivariate Normal (uncorrelated $\Rightarrow$ independent).
You can also find the covariance matrix of $Z-\tilde{Z} {\iota_{\nu}}$. I wouldn't call the resulting distribution Multivariate Normal though, because the resulting matrix will not be full rank. Try the 2-dimensional case to see more clearly what's going on.
Comment: You would rather use the identity $Cov(X+Y, W) = Cov(X,W) + Cov(Y,W)$
Comment: Whats the covariance of $Z-\tilde{Z}\iota_{\nu}$? Do not know how to calculate that? Isnt it $E((Z-\tilde{Z}\iota_{\nu})(Z-\tilde{Z}\iota_{\nu})^T)$?
Comment: Just look at each pair of components separately. Start with 2-dim case if you're stuck.
Comment: I am confused now... on the diagonals it is $Var(Z_i-\tilde{Z})=E((Z_i-\tilde{Z})^2)$. Otherwise it is $E((Z_i-\tilde{Z})(Z_j-\tilde{Z}))-E((Z_i-\tilde{Z})E(Z_j-\tilde{Z})$
Comment: Sorry do not understand what you mean. Do not know this identity.
Comment: Can you pls give me more help? :-)


Surface area of rotation of a circle around a tangent

Question: Self-studying integral calculus and I got this problem:

The circle $x^2+y^2=a^2$ is rotated around a line tangent to the circle. Find the area of the surface of rotation.

I made the construction:

There were a few hints given alongside this question, namely: "Set up coordinate axes and a convenient parametrization of the circle. What does the polar graph $r=2a\sin(\theta)$ look like?" I understood the first and last hints since under this new coordinate system, the circle's equation becomes:
$${x_n}^2+(y_n-a)^2=a^2$$
Which when converted to polar, gives you the last hint. However I was unable to describe this in terms of parameters, so I decided to take the upper semicircle's surface area of revolution going from $a$ to $-a$ and multiplying that by 2 to account for the lower semicircle. My integral:
$$2\int_{-a}^a 2\pi (\sqrt{a^2-x^2}+a)\sqrt{1+\frac{x^2}{a^2-x^2}} dx$$
Upon simplification:
$$4\pi\int_{-a}^a a+\frac{a^2}{\sqrt{a^2-x^2}}dx$$
Evaluation leads me to:
$$8\pi a^2 + 4\pi^2 a^2$$
However my book (Serge Lang's First Course in Calculus) gives only $4\pi^2 a^2$. Where has my logic gone wrong if I am getting an extraneous term $8\pi a^2$?
EDIT for clarity on integral setup:
I first rearranged for $y$ while taking positive square root as I want to take the upper semicircle into consideration for surface of revolution about x-axis. I'll double this to account for the lower semicircle. This gives:
$$y=\sqrt{a^2-x^2}+a$$
Using the surface of revolution formula with the derivative as
$$\frac{dy}{dx}=\frac{-x}{\sqrt{a^2-x^2}}$$
Using this into the surface of revolution integral nets me my first integral in this post (also applied $\times$2)
Comment: I do not understand what you are doing. Can you please explain your integral setup? If you are rotating about a tangent, you cannot take volume of rotation of a semicircle and multiply by $2$. Volume is a function of the distance from the axis of rotation.
Comment: Hint: [Theorem of Pappus](https://en.wikipedia.org/wiki/Pappus%27s_centroid_theorem)
Comment: Also the volume of rotation of a circle around any tangent is going to be the same so choose a tangent that is easy to work with
Comment: That is the formula for surface area of revolution around the x-axis. I'll add the setup but I figured out my issue now using the parameters.
Comment: ok so are you rotating $x^2 + (y-a)^2 = a^2$ around x-axis?
Comment: Can you detail more how you got the first integral in your question?
Comment: @MathLover Yes. I rearranged for y while taking positive square root, then doubled that surface of revolution to account for the negative square root part.
Comment: @AaryanPatil please see last part of my answer that uses polar coordinates and it is a much easier integral.
Answer: After changing the coordinates, in effect you are rotating $x^2 + (y-a)^2 = a^2$ around x-axis.
The circle is $x^2 + y^2 = 2 ay$
$ \displaystyle y' = \frac{x}{a-y}$
$ \displaystyle ds = \sqrt{1 + (y')^2} ~dx = \frac{a}{|y-a|} ~ dx$
For lower half -
$y = a - \sqrt{a^2-x^2}$
So, $ \displaystyle S_1 = 2 \pi a \int_{-a}^a \frac{a - \sqrt{a^2-x^2}}{\sqrt{a^2-x^2}} ~ dx$
$ = 2 \pi a^2 (\pi - 2)$
For upper half -
$y = a + \sqrt{a^2-x^2}$
So, $ \displaystyle S_2 = 2 \pi a \int_{-a}^a \frac{a + \sqrt{a^2-x^2}}{\sqrt{a^2-x^2}} ~ dx$
$ = 2 \pi a^2 (\pi + 2)$
Adding both, $S = 4 \pi^2 a^2$
But it is easier in polar coordinates as I mentioned in comments. The circle is,
$r = 2a \sin\theta, 0 \leq \theta \leq a$
$\dfrac{dr}{d\theta} = 2a \cos\theta$
$ \displaystyle ds = \sqrt{r^2 + \left(\frac{dr}{d\theta}\right)^2} ~ d\theta = 2a ~ d\theta$
$y = 2a\sin^2\theta$
So the integral is,
$ \displaystyle S = 8 \pi a^2 \int_0^{\pi} \sin^2\theta ~ d\theta = 4 \pi^2 a^2$
Answer: In spite of your obfuscating figure, you are asking for the surface area of a torus whose inner radius, $R$ (to the center of the cross-section) and outer radius, $r$ (that of the cross-section) are the same. This is well known to be $S=4\pi^2Rr$ (see, for example the CRC Mathematical Tables). So in your case, $S=4\pi^2a^2$
We can derive this result with Pappus's ($1^{st}$) Centroid Theorem, which states that the surface area $S$ of a surface of revolution generated by rotating a plane curve $C$ about an axis external to $C$ and on the same plane is equal to the product of the arc length $s$ of $C$ and the distance $d$ traveled by its geometric centroid. Simply put, $S=2πRL$, where $R$ is the normal distance of the centroid to the axis of revolution and $L$ is the curve length. In your case, $R=a$ and $L$ is the circumference of the circle, i.e., $=2\pi a$, so that $S=4\pi^2a^2.$
Answer: Comment on the Question
I believe that this is the standard setup for surface of revolution about the $x$-axis
$$
\int_{-a}^a\overbrace{\quad2\pi y\quad\vphantom{\frac{a}{\sqrt{a^2}}}}^{\substack{\text{account for}\\\text{revolution}}}\overbrace{\frac{a}{\sqrt{a^2-x^2}}}^{\mathrm{d}s/\mathrm{d}x}\,\mathrm{d}x
$$
However, the part for the upper arc of the circle does not give the same area as that for the lower arc of the circle, so we need to compute both separately:
$$
\begin{align}
&\int_{-a}^a2\pi\left(a+\sqrt{a^2-x^2}\right)\frac{a}{\sqrt{a^2-x^2}}\,\mathrm{d}x\tag{upper}\\
&+\int_{-a}^a2\pi\left(a-\sqrt{a^2-x^2}\right)\frac{a}{\sqrt{a^2-x^2}}\,\mathrm{d}x\tag{lower}\\
&=2\pi\int_{-a}^a2a\,\frac{a}{\sqrt{a^2-x^2}}\,\mathrm{d}x\\[6pt]
&=4\pi^2a^2
\end{align}
$$

Other Approaches
Revolution Around the $\boldsymbol{x}$-axis
As I had posted before I realized the question was revolving around the $y$-axis, if we revolve around the $x$-axis, the upper and lower parts of the surface have the same area, so we can just multiply the upper integral by $2$ in this case. Thus, the formula is
$$
\begin{align}
2\int_0^{2a}2\pi x\,\frac{a}{\sqrt{a^2-(x-a)^2}}\,\mathrm{d}x
&=2\int_{-a}^a2\pi(x+a)\,\frac{a}{\sqrt{a^2-x^2}}\,\mathrm{d}x\tag{1a}\\
&=4\pi a^2\int_{-1}^1(x+1)\frac1{\sqrt{1-x^2}}\,\mathrm{d}x\tag{1b}\\
&=4\pi a^2\int_{-\pi/2}^{\pi/2}(\sin(x)+1)\,\mathrm{d}x\tag{1c}\\[9pt]
&=4\pi^2a^2\tag{1d}
\end{align}
$$
Explanation:
$\text{(1a)}$: substitute $x\mapsto x+a$
$\text{(1b)}$: substitute $x\mapsto ax$
$\text{(1c)}$: substitute $x\mapsto\sin(x)$
$\text{(1d)}$: integrate
Parametrization
Parametrize the torus as follows: at each point of the circle around the $z$-axis, $a(\cos(\phi),\sin(\phi),0)$ put a circle perpendicular to this circle:
$$
\begin{align}
p(\phi,\theta)
&=\overbrace{a(\cos(\phi),\sin(\phi),0)}^\text{primary circle}+\overbrace{a(\cos(\phi)\cos(\theta),\sin(\phi)\cos(\theta),\sin(\theta))}^\text{secondary circle around the primary circle}\\
&=a(\cos(\phi)(1+\cos(\theta)),\sin(\phi)(1+\cos(\theta)),\sin(\theta))\tag{2a}]\\[6pt]
p_1(\phi,\theta)
&=a(-\sin(\phi)(1+\cos(\theta)),\cos(\phi)(1+\cos(\theta)),0)\\
&=a(1+\cos(\theta))(-\sin(\phi),\cos(\phi),0)\tag{2b}\\[6pt]
p_2(\phi,\theta)
&=a(-\cos(\phi)\sin(\theta),-\sin(\phi)\sin(\theta),\cos(\theta))\tag{2c}
\end{align}
$$
Thus, we get
$$
\begin{align}
|p_1(\phi,\theta)\times p_2(\phi,\theta)|
&=a^2(1+\cos(\theta))\,|(\cos(\theta)\cos(\phi),\cos(\theta)\sin(\phi),\sin(\theta))|\\
&=a^2(1+\cos(\theta))\tag3
\end{align}
$$
and we can compute
$$
\int_0^{2\pi}\int_0^{2\pi}a^2(1+\cos(\theta))\,\mathrm{d}\phi\,\mathrm{d}\theta=4\pi^2a^2\tag4
$$
Theorem of Pappus
As I mentioned in a comment, we can apply the Theorem of Pappus: the primary circle has circumference $2\pi a$ and the secondary circle has circumference $2\pi a$, so the area is
$$
(2\pi a)(2\pi a)=4\pi a^2\tag5
$$
Comment: Hmm... it was bothering me why symmetry consideration was not possible here. I didn't realize that the upper semicircle would indeed produce a greater surface area than the lower one until I read your comment. Thanks!
Comment: You're welcome. If you rotate around the $x$-axis, the upper and lower parts *are* the same, so there is a little less work. I've added, and expanded, the part I used to have in my answer when I thought you were rotating around the $x$-axis.
Comment: The author defined the surface area by this:
$$S=\int_a^b 2\pi y\sqrt{1+(\frac{dy}{dx})^2}dx$$
Comment: That would be for revolving about the $x$-axis. It would be useful to mention that. This would require two integrals, one for the part $y\le a$ and one for the part $y\ge a$, you can't simply double the one for the part $y\ge a$ (which has a larger surface area than the part $y\le a$). In my answer, I was revolving about the $y$-axis. With this new information, I will update the first part of my answer.


How do I get higher recording quality for my Nord Piano 3?

Question: this is the test recording I did

but when I compare to like these videos, they all sound way better

I'm using a UR22 interface with a TS patch cable I found lying around, I assume it is cheap and it's pretty short. this is a raw recording (OBS STUDIO) I haven't edited yet.
here is the recording that I did on audacity https://vocaroo.com/i/s0GgXoos4pSP
if there are any editing required like EQ, mastering stuff like that let me know and I'll send you the file so you can touch it up and send me how it should sound like after the editing
EDIT: this is another audacity recording but with 4.7 reverb hall https://vocaroo.com/i/s0Qi7I0yI5o1
Comment: Regarding your last sentence, it's not on-topic here to ask for someone else to edit or mix any of your content. We can tell you what we think will improve it, but this isn't the place to ask for services to be rendered. Also, vocaroo is probably not a good service for sending music files, since voice quality audio is often less than music quality, and vocaroo is meant for voice recordings.
Answer: First off, everyone else recorded in stereo. The Nord piano library definitely sounds much better in stereo. You'll want two TS cables instead of just one. Also make sure you have all the effects on the Nord turned off since some of them convert the stereo piano samples to mono.
Anderton's has access to all the top-quality gear, so they might have run the two TS outputs into a stereo Radial JDI and then from there to some nice preamps and then from there to a high-quality interface.
Finally, it sounds like Anderton's compressed the audio a bit, which makes it overall much louder sounding without clipping. Since the piano is a very dynamic instrument, it is very common to compress it a bit to make sure the quietest parts are audible.
The others might not have compressed but start with stereo recording and see if that sounds good enough to you.
Comment: How do I compress it?
Comment: @SkyStar Well, with a hardware compressor or a compressor plugin, but start by recording in stereo first. I think that will give you at least 80% of the quality improvement you're looking for. It doesn't sound like the Boku-no Hero one was compressed, so if you like the sound of that, you might not need compression at all.
Comment: I see, thanks, I'll pick up some cables and make a new recording and we'll see the difference
Comment: so I manage to get 2 lines in, and I recorded it https://youtu.be/Q3kf0xiFmNM I think some parts there are some clipping or distortion, I don't know what the problem is, as I didn't even record the sound with high gain. anyways please give me some input on how to make the sound better :)


Setting up a new DMZ for Web Servers

Question: When it comes to security, VLAN ACL's, firewall DMZ policy and the like I am a Newb.  So any help will be appreciated.
We are trying to architect our network to place all of our web accessible servers in a DMZ.  We have Watchguard Firewall and Dell Layer 3 Switch.  All of our Web Servers are virtual and hosted on a Hyper-V cluster.
We have set up two new VLAN's on the Layer 3 switch called DMZ (VLAN 210) and CMZ (VLAN 211) each with their own subnet in the 172.20.X.X range.  Our Web Servers each have two network interfaces, one for each of the new VLAN's.  We are trying to block all access to our LAN with ACL rules on the Layer 3 Switch, and only allow access to the Firewall which is in it's own VLAN 200.  On the firewall, we have set up the VLAN subnets.  On VLAN 210, we only want to be able to access the internet for Windows Updates since our Web Servers will not be joined to the domain. On VLAn 211, we want to allow access to the needed internal servers, through the firewall.
When we do not have any ACL rules in place for 210 and 211, we are able to ping all internal servers, and get the internet on the WebServers.  When we apply an ACL which blocks all internal subnets, but allows all other subnets, nothing seems to work correctly.  We have tried to do some "route adds" on the WebServers to get them to point to the correct internal servers, but again, with the ACL in place, nothing seems to work.
My two starting questions are:  Does what we are trying to do seem like a good way to go with the hardware we have? And do we need to do some routing on the Layer 3 Switch to get this to work?  So far I haven't done any and not sure how.
Thank you!!
Answer: The Watchguard is a firewall, it sounds unreasonable to try to use the switch as a firewall.
I'd plan to get rid of the server interfaces to the LAN, give them only one interface into the DMZ. Route all traffic through the Watchguard, which should have interfaces in both VLAN 210 and VLAN 211. Get rid of VLAN 200 entirely, get rid of any routing on the switch, use the Watchguard as the default gateway, get rid of most ACLs on the switch (possibly keeping any that restrict switch management access).
Then use Watchguard policies to manage what traffic can get from where to where, e.g. policies to allow the DMZ access to DNS servers, HTTP and HTTPS for Windows Update - preferably via proxy policies, and allow management connections (e.g. RDP) from the LAN to the Webservers.

Setting up a new DMZ for Web Servers


Prevent Firefox from making a new contenteditable div when user hits return

Question: I have a contenteditable div on my site which works great.
On Chrome i can just use the return key to add another line.
On Firefox it creates a new (extra) div.
I know I can use shift+return, but I don't think the users will now that :)
Is it possible to prevent this behaviour?
Check out the fiddle: http://jsfiddle.net/D7MJx/
I've tried it with FF 3.6
EDIT: The same thing happens on IE8
Answer: Ok I kinda figured it out now.
It's not the best (read cleanest) solution, but it works for me.
Only have tested this on Chrome, but I think other browsers will work the same.
I ended up doing this:
  $('div[contenteditable=true]').keydown(function(e) {
    // trap the return key being pressed
    if (e.keyCode == 13) {
      // insert 2 br tags (if only one br tag is inserted the cursor won't go to the second line)
      document.execCommand('insertHTML', false, '

');
      // prevent the default behaviour of return key pressed
      return false;
    }
  });

Comment: You can alway paste arbitrary markup into a contentediable region, unless you filter the paste process (which is a difficult task too)
Comment: It's not that simple. You have to consider a couple of special cases, for example in ``s. Look at https://github.com/tinymce/tinymce/blob/master/jscripts/tiny_mce/classes/ForceBlocks.js to see how tinymce does it.
Comment: @Pumbaa80: I will look into it. Although I have a real simple contenteditable. Just some basic bold tagging etc. So no `ul`'s and other (fancy :P ) stuff
Answer: I think you want the insertBrOnReturn command.
document.getElementById('myRichEditArea').contentDocument.execCommand('insertBrOnReturn',false, true)

https://developer.mozilla.org/en/rich-text_editing_in_mozilla
The Mozilla docs say insertBrOnReturn is not supported by IE but the docs are old and probably means IE7 or below. There's probably another way to do it in IE.
Comment: When I use that code I get the following error: `Uncaught TypeError: Cannot call method 'execCommand' of undefined` (in Chrome)
Comment: When I use that code I get the following error: Uncaught TypeError: Cannot call method 'execCommand' of undefined (2)
Comment: @NelsonTeixeira In 2011 this was very experimental stuff. A lot can change in 7 years. Try the updated docs at https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content


sendmail - how to unknown local user

Question: I'm using debian as my webserver and sendmail as my MTA
I do NOT have mydomain.com in the hosts file.
I have setup sendmail.cf with the following
dnl # Masquerading options
FEATURE(`always_add_domain')dnl
MASQUERADE_AS(`mydomain.com')dnl
FEATURE(`allmasquerade')dnl
FEATURE(`masquerade_envelope')dnl
FEATURE(`masquerade_entire_domain')dnl
MASQUERADE_DOMAIN(`mydomain.com')dnl

However user@mydomain is still being reported as an unknown user by sendmail.
What am I missing?
Answer: Sendmail by default auto-configures list of local email domains.
It can be tuned off by the following line in sendmail.mc:
define(`confDONT_PROBE_INTERFACES',`True')

You can check list of local email domains using
echo '$=w' | sendmail -bt

You can manually add domains to local email domains via /etc/mail/local-host-names file (one domain per line).
`
Standard reminders:

sendmail.mc needs recompilation into sendmail.cf
sendmail daemon needs to be restarted or send HUP signal to see new version of sendmail.cf

sendmail - how to unknown local user


Cannot pull data from pantip.com

Question: I have been trying to pull data from pantip.com including title, post stoy and all comments using beautifulsoup.
However, I could pull only title and post stoy. I could not get comments.
Here is code for title and post stoy
import requests
import re
from bs4 import BeautifulSoup

# specify the url
url = 'https://pantip.com/topic/38372443'

# Split Topic number
topic_number = re.split('https://pantip.com/topic/', url)
topic_number = topic_number[1]

page = requests.get(url)
soup = BeautifulSoup(page.content, 'html.parser')

# Capture title
elementTag_title = soup.find(id = 'topic-'+ topic_number)
title = str(elementTag_title.find_all(class_ = 'display-post-title')[0].string)

# Capture post story
resultSet_post = elementTag_title.find_all(class_ = 'display-post-story')[0]
post = resultSet_post.contents[1].text.strip()

I tried to find by id
elementTag_comment = soup.find(id = "comments-jsrender")

according to

I got the result below.
elementTag_comment  =

▼ กำลังโหลดข้อมูล... ▼

The question is how can I get all comments. Please, suggest me how to fix it.
Comment: At a glance, it seems theres lazy loading for the posts. ( Comments are loaded asynchronously after page). If you look at the network tab, you can see a 'render_comments' resource  network call is made...Please refer to this answer: https://stackoverflow.com/a/47851306/6283258
Comment: `soup.find()` will only return the first element is finds. If you want all tags with id = "comments-jsrender", you need to use `soup.find_all()`. Then depending what you want to do, may need to iterate through each element.
Answer: The reason your having trouble locating the rest of these posts is because the site is populated with dynamic javascript. To get around this you can implement a solution with selenium, see here how to get the correct driver and add to your system variables https://github.com/mozilla/geckodriver/releases . Selenium will load the page and you will have full access to all the attributes you see in your screenshot, with just beautiful soup that data is not being parsed.
Once you do that you can use the following to return each of the posts data:
from bs4 import BeautifulSoup
from selenium import webdriver

url='https://pantip.com/topic/38372443'
driver = webdriver.Firefox()
driver.get(url)
content=driver.page_source
soup=BeautifulSoup(content,'lxml')

for div in soup.find_all("div", id=lambda value: value and value.startswith("comment-")):
    if len(str(div.text).strip()) > 1:
        print(str(div.text).strip())

driver.quit()

Comment: Thank you very much. I wonder whether I can do that without Web Browser popping up. I think it may help increase speed.

Cannot pull data from pantip.com


AWS Eventbridge Notifications Does Not Work Using SNS topic

Question: I want to receive notifications from AWS Eventbridge when there's a scheduled event for my Amazon Elastic Compute Cloud (Amazon EC2) instance.

I created an Eventbridge rule and set the target to an already working SNS topic. The SNS topic is subscribed to a working Lambda function that is used for other "Cloudwatch to slack" alarms already. The eventbridge setting is as follows:
{
  "source": ["aws.health"],
  "detail-type": ["AWS Health Event"],
  "detail": {
    "service": ["EC2"],
    "eventTypeCategory": ["scheduledChange"]
  }
}

I already got an EC2 scheduled maintenance(reboot) notification as e-mail from AWS, but this eventbridge I created did not trigger for that and did not send any notification to the slack channel.
I am unsure now if I am missing something in the setting. I am setting it for the first time and no way to simply test it with fake input. It is supposed to work even if there is a single schedule event that appears in the top bell icon(as shown in the screenshot above), correct?
Answer: In order to find out the root cause of this issue, I suggest to take a look a the CloudWatch usage metrics for SNS. SNS reports the following metrics which might be useful for you: NumberOfMessagesPublished, NumberOfNotificationsDelivered NumberOfNotificationsFailed. If you find these metrics reported an they have a value different than 0, this means that SNS receives events from Event Bridge and the problem is somewhere else.
If you are using a Lambda to send messages to Slack, you should take a look at the logs in CloudWatch to see if the Lambda did execute successfully. You might want to check out the setup for Lambda recommended by AWS: (link)
For further debugging you may want to check out test-event-pattern CLI command.

It is supposed to work even if there is a single schedule event that appears in the top bell icon(as shown in the screenshot above), correct?

Yeah, it supposed to work even if there already is an event.
Comment: Thank you Ervin for some good input here.
Can you check the screenshots?
http://c2n.me/4e2fqht
http://c2n.me/4e2fqrR
Could you help me further?.
It shows published and delivered as value 1. That means working, correct?. But I don't see anything on my slack channel.
Comment: I see that you have a maintenance event from CloudWatch, although I see no values for SNS successful publishing or failures. Please check if you have a Lambda or something subscribed to the SNS topic.
Comment: Hmm, the SNS topic is subscribed to the lambda function already and they are being used already for some CloudWatch alarms to slack.
Do you think if any IAM role needs to specify between AWS Eventbridge and SNS or between AWS Eventbridge and Lambda?.
Answer: I'm having a similar issue with eventbridge rule being built with cloudformation.  I had to manually go into the eventbridge rule via the AWS console and go to the trigger and select the SNS topic again.  It now works.  It took me a while to figure out.  Can you confirm that the fix did that for you as I'm not sure how to fix this...
Comment: Please do not post your questions in answer section!


Inner Product on $P_3(\mathbb{R})$ true/false

Question: The question was to classify each statement as true or false with justification:
Define $\langle f, g\rangle$ = $\int_0^1 f'(x)g(x) + f(x)g'(x) \,dx $. Then, $\langle , \rangle$ is an inner product on $P_3(\mathbb{R})$.
My solution below concluded that it was true, however my classmate said the statement was false, and although I didn't completely understand their proof, I am beginning to doubt mine. Can anyone clarify if my justification is legitimate?
Rewrite $\int_0^1 f'(x)g(x) + f(x)g'(x) \,dx $ as $$\int_0^1 f'(x)g(x)\,dx + \int_0^1 f(x)g'(x) \,dx $$
For $\int_0^1 f'(x)g(x)\,dx$, integrate by parts to get $f(x)g(x) - \int_0^1 f(x)g'(x)\,dx$. Substitute this result into the rewritten form of $\langle f, g \rangle$, we get $$<f,g>=f(x)g(x) - \int_0^1 f(x)g'(x)\,dx + \int_0^1 f(x)g'(x) \,dx =f(x)g(x)$$
Then, (proving the three properties of inner products) $\langle f,f\rangle =[f(x)]^2\ge0$, also $\langle f,f\rangle=0$ iff $f(x)=0$ for $x\in[0,1]$. Thus, it is positive definite.
Next, $\langle f,g\rangle=f(x)g(x)=g(x)f(x)=\langle g,f\rangle$ so $\langle f,g\rangle$ is symmetric.
Finally, $$\langle sf+tg,h \rangle=(sf(x)+tg(x))h(x)=s(f(x)h(x))+t(g(x)h(x))=s\langle f,h\rangle+t\langle g,h\rangle $$ So $\langle f,g \rangle$ is bilinear, and is thus an inner product on $P_3R$.
Likely made a silly mistake somewhere or my thinking is wrong, any tips would be helpful!
Comment: Note that $f'(x)g(x) + f(x)g'(x) = (f(x)g(x))'$ so your inner product is really just $f(1)g(1)-f(0)g(0)$. You made a (not so) minor error. When doing *definite* integrals, $\int_a^b f'(x)g(x)\,dx = f(x)g(x)|_a^b -\int_a^b f(x)g'(x)\,dx.$ If you are not sure about this, consider the fundamental theorem of calculus.
Comment: Well, actually, $$\int_0^12f'(x)f(x)\,dx=(f(1))^2-(f(0))^2$$ so $\langle f,\,f\rangle$ is not necesairly $\ge 0$. In fact, if $f(x)=1-x$, $$\langle f,\,f\rangle=\int_0^12x-2\,dx=-1$$
Comment: Notice that by your calculations $\langle f, g \rangle = f(x)g(x)$. But $x$ is just the dummy variable used for integrating, so this makes no sense. Furthermore, if $f$ and $g$ are both constant, then clearly $\langle f,g \rangle = 0$.
Answer: Your calculation of the inner product is not quite correct; you should have
\begin{align*}
\langle f, g \rangle &= \int_0^1 \frac{d}{dx} f(x) g(x) \, dx \\
&= f(x) g(x) \big|_0^1 \\
&= f(1) g(1) - f(0) g(0)
\end{align*}
This does not define an inner product, although it is bilinear. For example, any function $f$ that vanishes at both $0$ and $1$ will have zero "norm" - to be explicit, if $f(x) = x(x - 1)$ then $\langle f, f \rangle = 0$.


Find all solutions of $\cos (x) + 1/2 \sec (x) = -3/2$ in the interval $(2\pi, 4\pi)$

Question: Find all solutions of $\cos (x) + 1/2 \sec (x) = -3/2$ in the interval $(2\pi, 4\pi)$ (Leave your answers in exact form and enter them as a comma-separated list.)
Comment: Holly, please add what you have tried, the source of the question and where you got stuck.
Comment: I've turned it into an equation and solved for cox (x) = -1/2, -1.  I don't know where to go from there
Answer: $$\begin{align} \cos (x) + 1/2 \sec (x) = -3/2 & \iff \cos x + \dfrac 32 + \dfrac{1}{\cos x} = 0 \\ \\
& \iff \cos^2 x + \frac{3\cos x}{2} + \frac 12 = 0\end{align}$$
Substituting $\cos x = u$ gives us a quadratic in $u$:
$$\begin{align} u^2 + \frac {3u}{2} + \frac 12 & = 0 \\ \\
u^2 + 2\cdot \frac{3}{4} u + \frac 9{16} - \frac 1{16} & = 0 \\ \\
\left(u + \frac 34\right)^2 - \frac 1{16} & = 0 \\ \\
\left(u +\frac 34 - \frac 14\right)\left(u +\frac 34 + \frac 14\right) & = 0 \\ \\
\left(u + \frac 12\right)\left(u + 1\right) & = 0 \\ \\
u = \cos x =  -\frac 12, \;\text{or}\; u = \cos x = -1
\end{align}$$
Now, we find two solutions $x = \cos^{-1}(-1/2) \in (2\pi, 4\pi)$, and one satisfying $x = \cos^{-1}(-1)\in (2\pi, 4\pi)$
...knowing that $\cos(2\pi/3 + 2n\pi) = \cos(4\pi/3 + 2n\pi) = -1/2$,
and that $\cos(\pi + 2n\pi) = -1$, for $n \in \mathbb Z^+$.
Comment: This needs a TU! +1
Answer: Hint: Recall that $\sec{x} = \frac{1}{\cos(x)}$, so
$$\frac{-3}{2} = \cos(x) + \frac{1}{2 \cos{x}}$$
$$\implies \frac{-3\cos{x}}{2} = \cos^2{x} + \frac{1}{2}$$
Substitute $u = \cos{x}$ to get
$$\frac{-3u}{2} = u^2 + \frac{1}{2}$$
which is now a quadratic equation.
Comment: So cos (x) = -1/2 or cos (x) = -1 right?  I don't know where to go from there to find a solution.
Comment: Note that $\cos(\frac{2\pi}{3})=\frac{-1}{2}$, $\cos(\pi)=-1$, and $\cos(x+2\pi)=\cos(x)$.


Type inference with control statements

Question: var sortQ = filterQ;  // <--- update

if (iSortingCols > 0)
{
    sortQ = (sortDirs[0] == "asc") ?
        sortQ.OrderBy((d) => d.GetColumnData()[sortCols[0]]) :
        sortQ.OrderByDescending((d) => d.GetColumnData()[sortCols[0]]);

    if (iSortingCols > 1)
    {
        for (int i = 1; i < iSortingCols; i++)
        {
            sortQ = (sortDirs[i] == "asc") ?
                sortQ.ThenBy(d => d.GetColumnData()[sortCols[i]]) :
                sortQ.ThenByDescending(d => d.GetColumnData()[sortCols[i]]);

        }
     }
 }

The compiler underlines the two results of the ternary operator inside the for loop, saying that IEnumerable<...> doesn't have a method overload called ThenBy (and similarly for ThenByDescending), but the sortQ will be an IOrderedEnumerable<...> in that block.  Why isn't C# type inference picking that up?
Update: for those who might have been confused before, what I left out of the original snippet was that I was assigning sortQ to the result of another query which forced the type inference engine to type sortQ as an IEnumerable<..>, which of course is what was screwing up my example.  The answer below is the way around this.  Thanks to @Marc for reading between the lines.
Answer: I'm guessing sortQ is IEnumerable<T>; you need an IOrderedEnumerable<T> to use ThenBy; fortunately, your first OrderBy returns this, so just catch that:
var result = (sortDirs[0] == "asc") ?
    sortQ.OrderBy((d) => d.GetColumnData()[sortCols[0]]) :
    sortQ.OrderByDescending((d) => d.GetColumnData()[sortCols[0]]);

if (iSortingCols > 1)
{
    for (int i = 1; i < iSortingCols; i++)
    {
        result = (sortDirs[i] == "asc") ?
            result.ThenBy(d => d.GetColumnData()[sortCols[i]]) :
            result.ThenByDescending(d => d.GetColumnData()[sortCols[i]]);

    }
 }

Comment: Doh!  You're right.  I didn't even think about the prior assignment to sortQ.  Good call.

Type inference with control statements


Ler email mais recente - JavaMail

Question: Dei uma procurada por aqui mas sem sucesso. Alguém sabe como buscar o email mais recente usando o JavaMail? O que eu estou usando puxa todos os emails. Meu código:
        try {

            campolog.setContentType("text/html");

            Properties props = new Properties();

            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "587");
            props.put("mail.smtp.starttls.enable", "true");
            Session emailSession = Session.getDefaultInstance(props);

            Store store = emailSession.getStore("imaps");
            store.connect("pop.gmail.com", "email@example.com", "senha");

//            javax.mail.Folder[] folders = store.getDefaultFolder().list("*");
//            for (javax.mail.Folder folder : folders) {
//                if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
//                    System.out.println(folder.getFullName() + ": " + folder.getMessageCount());
//                }
//            }

            Folder pastaEmail = store.getFolder("SMS");
            pastaEmail.open(Folder.READ_ONLY);

            Message[] mensagens = pastaEmail.getMessages();
            System.out.println("Total de Emails: " + mensagens.length);

            for (int i = 0, n = mensagens.length; i < n; i++) {
                    Message mensagem = mensagens[i];
                    //campolog.append("---------------------------------");
                    //campolog.append("Email Nº " + (i + 1));
                    //campolog.append("Assunto: " + mensagem.getSubject());
                    //campolog.setText("De: " + mensagem.getFrom()[0]);
                    campolog.setText("Mensagem: " + mensagem.getContent().toString());
            }

            pastaEmail.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
}

Comment: Então, nesse caso eu precisaria ter a "posição" exata do email. Exemplo: Email1, Email2....
Answer: Nunca usei, mas lendo a documentação da API:

https://javaee.github.io/javamail/docs/api/com/sun/mail/imap/IMAPFolder.html#getSortedMessages-com.sun.mail.imap.SortTerm:A-

Creio que tenha que usar getSortedMessages então você ordenaria por data, assim:
SortTerm[] termos = new SortTerm[1];

termos[0] = SortTerm.DATE; //Pode adicionar mais critérios de ordem adicionando termos[1], termos[2], etc

Folder pastaEmail = store.getFolder("SMS");
pastaEmail.open(Folder.READ_ONLY);

Message[] mensagens = ((IMAPFolder) pastaEmail).getSortedMessages(termos);

O código fiz seguindo o exemplo desta resposta do SOen: https://stackoverflow.com/a/50994431/1518921

Então para ler a primeira mensagem ao invés do for faria apenas uma checagem assim:
if (mensagens.length > 0) {
    mensagens[0].getContent(); //Faça algo com o conteudo retornado
} else {
    //Não há mensagens
}

O SortTerm.DATE vai ordenar pela data (e hora) do envio da mensagem, assim você vai pegar pela hora que o remetente enviou, mas se precisar da hora da "chegada", quando chegou a sua caixa de email, então use:

https://javaee.github.io/javamail/docs/api/com/sun/mail/imap/SortTerm.html#ARRIVAL

Assim:
SortTerm[] termos = new SortTerm[1];

termos[0] = SortTerm.ARRIVAL;

Folder pastaEmail = store.getFolder("SMS");
pastaEmail.open(Folder.READ_ONLY);

Eu nunca usei, como disse, só li a documentação e a resposta, mas creio que isto ordene como o esperado, no entanto se estiver em ordem inversa, por exemplo retornar a mensagem mais antiga no mensagens[0].getContent(); então basta inverter pegando o ultimo item de Message[] mensagens, assim:
if (mensagens.length > 0) {
    final int ultimaMensagem = mensagens.length - 1;
    mensagens[ultimaMensagem].getContent();
} else {
    //Não há mensagens
}

Ou simplesmente:
if (mensagens.length > 0) {
    mensagens[ mensagens.length - 1 ].getContent();
} else {
    //Não há mensagens
}

Comment: muito obrigado cara, eu te amo! Hahahaha. VALEU MESMO <3
Comment: Funcionou! Muito obrigado mesmo! Eu aproveitei pra procurar na documentação como eu tratava o email, retirando algumas partes. Não consegui achar nada sobre. Não precisa me dar a resposta, mas você viu algo disso por lá? Ou pode me dar dicas sobre como pesquisar?
Comment: @AbnerRodrigues depende do que quer retirar do email para ser exibido, se puder dizer eu leio melhor a doc e tento colocar como exemplo ;)
Comment: Olha, eu recebo o email assim:

`Mensagem: *** EMAIL AUTOMATICO, POR FAVOR NAO RESPONDA ***  Ola abnerodrigs Voce recebeu uma resposta.  Numero do Celular: 11982743910 SMS que voce enviou: Ola, o visitante: Fulanochegou! Podemos autorizar a entrada? Digite 1 para sim ou 2 para nao. Mensagem Respondida pelo Celular: 1`

Eu queria deixar apenas a parte "Respondida pelo Celular: 1"
Comment: @AbnerRodrigues essa parte vai ter que usar regex, pode criar uma nova pergunta explicando que quer extrair de uma string essa parte, ai vou formular uma nova resposta, para não misturar os assuntos. Por favor marca essa resposta como correta, obrigado! Se não souber como fazer leia este link: https://pt.meta.stackoverflow.com/q/1078/3635
Comment: Eu que agradeço!!
Comment: @AbnerRodrigues assim que fizer a pergunta, copia o link e me manda aqui pra eu responder :)
Comment: Vixi, não vai rolar. Eu atingi o limite de questões (Uma por dia é sacanagem) e precisarei esperar mais `6` dias para perguntar de novo... Mas muito obrigado, vou tentar dar uma pesquisada por aqui. Muito obrigado mesmo!!
Comment: @AbnerRodrigues vou te mandar aqui o código, só preciso testar e já te mando
Comment: Opa, muito obrigado!!!
Comment: @AbnerRodrigues pronto, fiz um exemplo para você estudar como pegar a parte da string necessária: https://repl.it/@inphinit/extract-phone-regexjava

Ler email mais recente - JavaMail


How can I notify an admin when a user is contacted?

Question: On my Drupal 7 site, I have a user contact form.  How can I alter the form so that an admin is notified when the form is submitted?
Comment: use webform for any customization
Comment: Thank you for your response minymirza. I do not have webform installed, but entityforms. Also is there a way to assign (or attach) an entityform to each user2 profile, so it emails the owner of the profile and the admin? I asked this before here on stackexchange without luck, so I finally eneded up sticking to the sitewaide user contact form. I'm pretty stuck with this issue since the website owner wants to be notified when a user is contacted from his website...
Answer: In a custom module
hook_form_alter() yourForm.

Add custom submit handler, it will run alongside with your defaut submit
$form['#submit'][] = 'yourSubmitFunction';

Inside your custom submit handler use drupal_mail() or any other result you need
function yourSubmitFunction($form, &$form_state) {
  drupal_mail()
  ....
}

Note: the form_state array contains all the submited values.
Comment: This is how I would do it :-) +1
Comment: @Pan I have implemented hook_alter_form like this:
function request_info_form_alter(&$form, &$form_state, $form_id){
 if($form_id == "contact_personal_form"){
     $form['#submit'][] = 'request_information';
   }
}

function request_information($form, &$form_state) {
  global $user, $language;

  $site_email = variable_get('site_mail', '');
  $to = $site_email;
  drupal_mail('contact', 'page_mail', $to, language_default(), $values, $from);
}   ---and it's sending the email to the admin, but not the message, I thought the form state array contained all the submitted values...A tip?...
Comment: $values should be something like $form_state['values']['element_that_contains_message'] ...
Comment: @Pan Yep! Was missing $values = $form_state['values'];
  $values['sender'] = $user;
  $values['sender']->name = $values['name'];
  $values['sender']->mail = $values['mail'];
  $values['subject'] = $form_state['values']['subject'];
  $values['message'] = $form_state['values']['message'];
  $from = $values['name']; Now works as magic! Thanks!


how to change the current anchor tag href with the nearest anchor tag url with in specific div in jquery

Question: Hii i am trying to change the anchor tag href with class media-url with the nearest anchor tage url which is inside field__item div , but i am getting undefined , please let me know where i am doing wrong .

Group Exercise Programs

media image url

https://www.example.com/

here is my jquery :
  let mediaimageurl = $('.media-url').find('.field__item a').attr('href');
  $('.media-url').attr('href' , mediaimageurl);

Comment: Define nearest? Do they share a common ancestor?
Comment: @ITgoldman yeah, they do
Comment: What's wrong about using `$(".media-url").closest(".common-ancestor").find(".field__item a")` ?
Answer: You need to use closest() to get the parent container and then next() to get .component-spotlight__inner and finally use find() to get the container of your link.

let mediaimageurl = $('.media-url').closest('.media--bundle--image').next('.component-spotlight__inner').find('.field__item a').attr('href');
$('.media-url').attr('href' , mediaimageurl);
console.log(mediaimageurl);

Group Exercise Programs

media image url

https://www.example.com/


Replace IP address figures with 'X' letters using sed (preserve character number)

Question: I have a string containing several IPs. I need to replace all of the figures in all the IPs with the letter 'X' using sed, i.e. 10.135.1.03 will become XX.XXX.X.XX.
UPDATE String contains not only IPs, but other characters too: both letters and figures. Need to replace only IP's figures. Something like "Received 5 connections from 192.168.1.1, 26 connections from 10.0.0.1, total 31 - Tuesday, 20.09.2012. MessageID: 212.132.15".
Answer: $ str="10.135.1.03"
$ echo $str | sed -e "s/[0-9]/X/g"
XX.XXX.X.XX

or in a scripting context, this is probably better:
out=$(sed -e "s/[0-9]/X/g" <<< "$str")

not sure why you wanted sed btw, tr has a slightly cleaner syntax:
out=$(tr [:digit:] X <<< "$str")

when using bash, even cleaner:
out=${str//[0-9]/X}

Comment: Unfortunately my string contains not only IPs, but other characters too: both letters and figures. Need to replace only IP's figures.
Comment: @JohnDoe and is there a pressing need to replace every character with one X, or can we replace 123 with X as well, making all ip's X.X.X.X?
Comment: yes, we need to preserve the number of characters, one X for one figure.
Answer: This might work for you (GNU sed, tr and Bash):
sed -r 's/\<[0-9]{1,3}(\.[0-9]{1,3}){3}\>/$(tr [0-9] X <<<&)/g;s/.*/echo &/e' file

you could cheat and do:
sed -r 's/\<[0-9]{1,3}(\.[0-9]{1,3}){3}\>/X.X.X.X/g' file

Answer: Personally, I would find this very difficult with sed. I think this would be much easier with GNU awk:
awk --re-interval '{ for (i=1; i<=NF; i++) if ($i ~ /([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}/) gsub(/[[:digit:]]/, "X", $i) }1' file.txt

Results:
Received 5 connections from XXX.XXX.X.X, 26 connections from XX.X.X.X, total 31 - Tuesday, 20.09.2012. MessageID: 212.132.15


Measure of non-measurable set is zero

Question: I am working on a problem from Richard Bass' analysis, which to a slowpoke is just a jumbling of unrelated terms:

Suppose that set $N$ is non-measurable as defined in Section 4.4. Show that $m(A) = 0$ if $A \subset N$, where $A$ is Lebesgue measurable.
  (Section 4.4 has this theorem: Let $m^*$ be defined by the usual outer measure definition, where $\mathcal C$ is the collection of intervals that are open on the left and closed on the right and $\mathscr l ((a, b]) = b - a$. Then $m^*$ is not a measure on the collection of all subsets of $\mathbb R$.)

Here are what I managed to salvage from the mess before my mind goes on strike:
(1) Since $N$ is non-measurable per Section 4.4, which says that all subsets of $\mathbb R$ is non-measurable, then $N \subset \mathbb R.$
(2) Since $A \subset N$, isn't it $A \subset \mathbb R$ as well?
(3) Since $A$ is Lebesgue measurable, then
$$\forall B \subseteq \mathbb R, \ m(B) = m(B \cap A) + m(B \cap A^c).$$
Please let me know how and where I should go from here. Thank you for your time and effort.
Comment: The problem is stated for **the** particular set $N$ constructed in section 4.4.
Comment: Your point (3) holds only when $B$ is measurable, not for arbitrary subsets of $\mathbb R$.
Comment: Does section 4.4 contain a definition of "non-measurable" (or of a particular set $N$)? With the usual meaning what you're being asked to show isn't true. For example, if we let $C$ be a non-measurable subset of $[1,2]$, then $N=C\cup[0,1]$ is still not measurable, but $A=[0,1]\subset N$ and is Lebesgue measurable with nonzero measure.
Comment: Thanks! You can look at the entire page from the link below, Bass's online book, page 30 - 31, and the problem is Exercise 4.13, page 35. Please let me know and thanks again. http://homepages.uconn.edu/~rib02005/real-analysis-04nov2011.pdf
Comment: @Tom : So, $N = \{ (a, b] \mid a, b \in \mathbb R \}$? $N \in \mathcal C$?
Comment: No, you need to read the definition inside the proof of theorem 4.15.
Comment: Note that the proof of 4.15 calls the non-measurable set it defines $A$ rather than $N$.
Comment: @HenningMakholm Are you sure about your first comment? I think point 3 is precisely the Caratheodory condition for $A$ to be measurable, and it must hold for every $B\subset \mathbb{R}$.
Comment: @bartgol: The left-hand side of the equation says $m(B)$, which, by definition, is only even defined then $B$ is measurable.
Comment: Oh, my bad. I was thinking about the outer measure. The Caratheodory condition is formulated in terms of $m^*$. Which I guess is probably what the OP wanted to write?
Answer: The statement is for a particular $N$ constructed in that book.
The properties we need to use from $N$ is that its rational translations $N+r$ are disjoint and that $\bigcup_{r\in\mathbb{Q}\cap[0,1]}(N+r)\subset[-1,2]$.
Assume that $A\subset N$ is measurable.
This implies that $A+r$ are disjoint for $r\in\mathbb{Q}\cap[0,1]$. So
$$3\geq m([-1,2])\geq m(\bigcup_{r\in\mathbb{Q}\cap[0,1]}(A+r))=\sum_{r\in\mathbb{Q}\cap[0,1]}m(A+r)=\sum_{r\in\mathbb{Q}\cap[0,1]}m(A)$$
This can only happen if $m(A)=0$.

Notice this is the same as half of the proof of theorem 4.15. The only difference is that since $A$ is not all of $N$ we don't have the inclusion $\bigcup_{r\in\mathbb{Q}\cap[0,1]}(A+r)\supset[0,1]$ and therefore there is no inequality $\geq1$ from below preventing $m(A)=0$.
Comment: That construction of the set $N$ is due to [Vitali](http://en.wikipedia.org/wiki/Vitali_set). It is indeed ingenious, but like every idea, it is a combination of ideas coming from past experiences. At the time lots of people were working in defining length for all subsets of the real line and also studying the axiom of choice. The $\mathbb{Q}$ is yet more natural and old. The reals are constructed as the limit points of the rationals. So, all proofs about the reals can be written as statements about the rationals anyway.
Comment: Look at the sum on the right. You are adding the same number over and over. If it is non-zero it must be positive, and the sum would be infinite. That can't be less than $3$.
Comment: I am reading & digesting yours... I think on the 4th line from above, shouldn't it be "This implies that $A + r$ are disjoint for $r \in \mathbb Q$ ... " instead? Thanks again!
Comment: @A.Magnus Yes, $r\in\mathbb{Q}\cap[0,1]$.
Comment: In real setting, do you think I need to supply proofs to $N + r$ are disjoint and that $\bigcup_{r\in\mathbb{Q}\cap[0,1]}(N+r)\subset[-1,2]$? Or are they taken for granted?
Comment: It is up to you. At the very least you do need to convince yourself that those statements are true. Those are claimed and used in the proof of theorem 4.15. The first follows directly from the definition of $N$, the second follows from $N\subset[0,1]$ and $r\in[0,1]$.
Comment: Do you mind explaining to a slowpoke that from $3\geq m([-1,2])\geq m(\bigcup_{r\in\mathbb{Q}\cap[0,1]}(A+r))=\sum m(A)$ you are forced to conclude $m(A) = 0$? Thanks!
Comment: It's a rather general question: How do you (or Bass the author) suddenly came up out of blue with $\mathbb Q$ in the proof? It happens all the time in math proof, especially in real analysis. If it were left to me, I wouldn't come up with it in a million years. Is it part of math-maturity package? Thanks again, but I am still digesting bit by bit...
Comment: Thanks for your patience! Now I am able to work out a solution. Thanks again.

Measure of non-measurable set is zero


excluding non english field values from search_api index (or facet)

Question: I have a CT product and a CT factory. Products have an entity reference field pointing to factories. I use node translation on factories (en, fr, de) but products are not translated (en only).
Creating facet on the product's factory (entity reference field) and indexing works well but the problem is that the facet displays all translated versions of factories. e.g:
china factory in english (14)
china factory in french (14)
china factory in german (14)
taiwan factory in english (6)
taiwan factory in french (6)
taiwan factory in german (6)
EU factory in english (2)
EU factory in french (2)
EU factory in german (2)

Since the search page regards products which are only in english, I'd like to be able to remove the fr and de values from that facet, or even better, not allow them to be indexed at all.
I've tried the facetapi_bonus module but its options for values exlusions doesn't suit me because I don't know the titles of the factories or their node ids beforehand.
Answer: I will venture a guess that when choosing indexed fields for the Product CT, you selected 'Factories' field and created the facet against this. Since you are using node translation, it is quite sensible that all available nodes (in various languages) are displayed in the facet. I suggest you try the following:

Remove/disable field 'Factories' from the list of indexed fields and remove the respective facet
At the bottom of the fields configuration for the index, you will find an option labeled 'Add related fields'. Choose field 'Factories'. With this action, all fields of the referenced Factory CT will become available for indexing
Enable the field that is correlated with the translation source node. Label should be something like this 'Factories >> Translation source node'. Create a new facet against this field
Clear indexed data and re-index

Most probably, the new facet will only display the facet terms in the default translation language (English in your case)


Getting a new connection from the connection pool times out in ASP.Net application. I need suggestions for mitigation

Question: We are getting the following error on a certain database occasionally under moderate load.
"System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached."
I have combed through the code and we are closing the connections in finally blocks like we should except in a few cases which we have established are being called very infrequently. We will fix those pieces of code in our next release but to solve the current production issue, I am suggesting increasing the max pool size to 300. The max concurrent users we are currently experiencing is around 110 which is obviously over the default pool size (100).
I am also suggesting making sure all our connection strings to a particular SQL Server instance are identical to avoid creating multiple connection pools unnecessarily. I am hoping that we can use the USE [Database] statement before our actual SQL queries when we need to switch databases within a single SQL Server instance.
Do you guys have any ideas, pointers, suggestions, or gotchas for us to watch out for?
Answer: You must eliminate the connection leaks. If the cause of the pool exhaustion is leaks, increasing it to 300 is just gonna delay the inevitable. If you leak one connection in 10000 calls (ie. "very infrequently") and you have 110 concurrent requests at, say, 5 seconds a call, you are leaking at a rate of about one connection every 8 minutes that will drain the pool in 13 hours. The timeouts will start showing up much earlier though, as the available pool size will shrink.
If you have hard evidence that s not the leaks that are the root cause but indeed the rate of calls vs. pool size, then you should increase the pool size. Whatever your pool size is you decide to use, if your requests are requiring 1:1 a connection for the whole duration of the requests then you need to throttle/queue the HTTP accepts so it does not exceed your pool size. If not, you can still encounter spikes that exhaust the pool.
Also you may consider using a more resilient connection factory, one that retries and attempts an non-pooled connection if the pool is drained. Of course this goes hand-in-hand with my prior point that if you calibrate your max HTTP accept count to match the pool size, then the pool cannot be exhausted (unless you leak, back to square one). I would not recommend this though, I think is much better to queue up requests in the http.sys territory than in the application resource allocation territory (ie. throttle the max accepted HTTP calls).
And last but not least, reduce the duration of each call. If your call takes in average 5 seconds, then you're seeing 110 connection concurrently at only a mere 22 requests per second. If you reduce the duration of the call by eliminating SQL bottlenecks to 1 second, you'll be able to service 110 requests per second to hit the same resource cap (110 concurrent requests), that is a 5 time traffic increase. The biggest culprit is usually table scans, make sure all your queries are using sensible SQL and have an optimal data access path. As David says, SQL Profiler is your friend.
You can also use SqlConnection.ChangeDatabase to change the database.
Comment: The real problem was an obscure connection leak. Thanks for the detailed comments.
Comment: any suggestion on how to find out connection leaks? @ArsalanAhmed. I'm using nodejs with postgres


Uncaught TypeError: Cannot read property 'split' of undefined

Question: Olá!
No meu código JavaScript recebo o seguinte erro: "Uncaught TypeError: Cannot read property 'split' of undefined". Como sou nova na área, não entendo muito bem como resolver o problema, alguém pode me ajudar a identifica-lo?
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marks = [];
for (var i = 0; i < location.length; i++) {
    marks[i] = createMark(i); /*ERRO*/
}

function createMark() {
    var imagePath = "marker" + (i + 1) + ".png";
    var image = imagePath;
    var markers = [];
    var lat = locations[i].split(',')[0]; /*ERRO*/
    var long = locations[i].split(',')[1];
    var location = new google.maps.LatLng(lat, long);
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        icon: image
    });
    marker.setTitle("Cliente");
    var textOrder = " Ponto:  " + (i + 1) + ".
  Latitude: " + lat + ",  Longitude: " + long;
    var infowindow = new google.maps.InfoWindow({
        content: textOrder
    });
    google.maps.event.addListener(marker, "click", function() {
        infowindow.open(map, marker);
    });
}

Comment: Esqueceste de dar argumentos à função `function createMark()`... acho que queres `function createMark(i)`. Mas há mais coisas, essa função não retorna nada, por isso `marks[i]` vai dar `undefined`.
Comment: Podes fazer um exemplo a funcionar? (que mostre o erro e que tenha HTML). Acho que vais precisar de estas 3 alterações: https://paste.ofcode.org/33TFGAbVx5D5EjsVapDMgqd
Comment: No final da função junta `return marker;` Assim a intância do marcador fica guardada, no respetivo `mark[i]`.
Comment: Funcionou perfeitamente Sérgio!!! Obrigada!!! :-D
Comment: Agradeço Sérgio pela ajuda! Mas anteriormente este código funcionou, só agora começou a me retornar erros... Se não for abuso de minha parte, saberia me dizer que tipos de argumentos devo passar para marks[i]?
Comment: Sérgio, mais uma vez obrigada! Ainda sim não funcionou... Vou postar o código completo...
Answer: Na linha onde está ocorrendo o erro você passa o a variável i como parametro para a function createMark(), mas acontece que essa function não está esperando nenhum parâmetro:
for (var i = 0; i < location.length; i++) {
    marks[i] = createMark(i); /*ERRO*/
}

O que deve ser feito é alterar a linha
function createMark() {

Para
function createMark(i) {

Comment: Funcionou!! Obrigada!!!
Answer: 3 coisas a corrigir:
function createMark(i) { // <--------------- mudança 1
    var imagePath = "marker" + (i + 1) + ".png";
    var image = imagePath;
    var markers = [];
    if (!locations[i]) return null; // <--------------- mudança 2
    var lat = locations[i].split(',')[0]; /*ERRO*/
    var long = locations[i].split(',')[1];
    var location = new google.maps.LatLng(lat, long);
    var marker = new google.maps.Marker({
        position: location,
        map: map,
        icon: image
    });
    marker.setTitle("Cliente");
    var textOrder = " Ponto:  " + (i + 1) + ".
  Latitude: " + lat + ",  Longitude: " + long;
    var infowindow = new google.maps.InfoWindow({
        content: textOrder
    });
    google.maps.event.addListener(marker, "click", function() {
        infowindow.open(map, marker);
    });
    return marker; // <--------------- mudança 3
}

A primeira é falta do i dentro do escopo da função.
A segunda é uma salvaguarda caso locations[i] não tenha o que é esperado.
A terceira é para a função retornar algo para ser guardado em marks[i]
Comment: estou com mais uma dúvida sobre o assunto, poderia me ajudar? Se puder me chamar em chat, agradeceria muito. Obrigada!!!!
Comment: @Z.. podes escrever aqui. Quando tiveres mais pontos podes escrever no chat também
Comment: Ok @Sergio!! A dúvida está em resposta a essa questão...


Measuring infeasibility in convex optimization, relations with dual problem

Question: A question regarding convex optimization and (maybe) duality.
I have a problem in the form
\begin{align}
x^* = \mathrm{arg} \min_x f(x) \quad \text{s.t.} \quad A x \leq b, C x = d,
\end{align}
where $f$ is either quadratic or, if it makes things easier, linear. Let's also assume that $P = \{ x \mid A x \leq b \}$ is bounded and not empty.
I would like to design an auxiliary optimization problem that:

if the original problem is feasible returns the solution $x^*$ of the original problem,
if the original problem is infeasible returns the minimum perturbation (according to some norm) $e^*$ that I should add to $d$ to make the problem feasible (remember $P \neq \emptyset$).

A naive approach could be, for example, something like
\begin{align}
\min_{x,e} f(x) + M \| e \| \quad \text{s.t.} \quad A x \leq b, C x = d + e,
\end{align}
where $M$ is "big enough". This however is very unpractical since the high value of $M$ would lead to numeric problems.
Do you have any better idea?
Do you think duality can help in some way here?
If I solve the dual of the original problem, and I detect unboundedness (we know that, under these assumptions, the primal infeasible implies the dual unbounded) can I elaborate the result to get something related to $e^*$?
For example, could an extreme ray of the dual feasible set help?
Thank you very much!
Comment: If the primal is infeasible, the dual may also be infeasible. Why not solve 2 problems?
Comment: You could add a binary variable to deal with infeasibility, but I doubt it is faster.
Comment: In the quadratic case, the dual is always feasible, but in general you are right: the dual can also be infeasible. I guess solving two problems is always an option. I wanted to understand if I'm trowing away some useful information from the solution of the dual of the original problem.
Comment: This would be actually a lower level QP/LP solver of a branch and bound code for mixed integer programming (reason why I have the solution of the dual almost for free). Yes, the binary would work, but in practice it's equivalent to solve two problems...
Answer: Well, if the original problem is infeasible, you can just solve for
\begin{align}
\min_{x,e} \|e\|: & \\
Ax&\le b, \\
e &= d-Cx.
\end{align}
Comment: It's clear that solving two problems as you are suggesting would work: my question is in fact how to avoid that...
Comment: Unfortunately I do not know a priori if the problem is infeasible. Your approach would then boil down to just solve two problems, right?
Comment: You will have to first check the feasibility of the original problem anyway. Besides, this new problem is always feasible.
Comment: I do not agree that I have to first check the feasibility of the original problem anyway: the example I described with the big M in the objective function is a single problem, where I do not need that check first. No?
Comment: Your requirement is to solve for the original problem if the domain is feasible. Your objective function with the big M violates that requirement. The bigger the M is, the further away your solution deviates from the true solution, when the original problem is feasible. My formulation, on the other hand, fulfills exactly your two requirements.
Comment: When M is big enough the objective drives e to zero
(if feasible) and I recover the original problem. No? It's like the big M method in linear programming.
Comment: I am sorry that I misspoke. I should have said that as $M$ is bounded, as large $M$ leads to numerical issues, the solution to your current objective function deviates from your exact requirements. My formulation, however, gives you exactly what you ask for.
Comment: Sure. But is there a computational problem checking the feasibility of the original problem? It should be easy by taking the most trivial objective function as the constraints are all linear.


Neo.ClientError.Statement.ExternalResourceFailed on ubuntu

Question: I'm trying to import a csv file in NEO4j db using script :
LOAD CSV FROM "file:///dataframe6.txt" AS line
RETURN count(*)

But I get following error:
Neo.ClientError.Statement.ExternalResourceFailed
Couldn't load the external resource at: file:/home/gaurav/sharing/dataframe6.txt

P.S. : I'm using ubuntu machine
added this line dbms.directories.import=/home/gaurav/sharing/
and    dbms.security.allow_csv_import_from_file_urls=true
Comment: Well, it looks like it knows where to go, so lets check the obvious ... can you do a ls -l /home/gaurav/sharing/dataframe6.txt and check if the neo4j user (that runs the database if your using the apt install) can read that file ?
Answer: I had to change folder permission for user NEO4j, it works now
Comment: How you changed folder permissions for user Ne14j?


Does Fortran modify input arguments through subroutine multiple calls?

Question: I have a subroutine called several times in an if-then-goto loop.The subroutine has two input arguments:
1.is a constant
2.is an array of definite size(i.e 200X1) whose elements change in a do loop right before the subroutine is called.
The problem is that subroutine doesn't understand that change and returns the same results every time it is called (i.e the results of the first time that it is called).It seems as if the values of all variables that are calculated inside the sudroutine are somehow saved and do not change although input atgument no.2 changes..
Is something wrong with my code?Is there a Fortran bug i'm not aware of?
My code looks like this:
      PROGRAM calcul.f

      REAL aa(100000),dd(100000),mm(100000),yy(100000),hh(100000),mn(100000),ss(100000),ml(100000),m0(100000)
      INTEGER N,snv
      DOUBLE PRECISION m0(100000),excerpt(1000),k1(100000),sqsum,s2,vk1,mk1,sdk1,v

      filelength=610
      W=200

      OPEN (1,file='filename.dat')
      DO i=1,filelength
      READ (1,*) aa(i),dd(i),mm(i),yy(i),hh(i),mn(i),ss(i),ml(i),m0(i)
      END D0
      CLOSE (1)

   10 FORMAT(g12.6)
   11 FORMAT(I5,1x,g12.6)
       c1=1
       c2=W
       snv=0

   14   IF ((c2.LT.filelength).AND.(c1.LT.(filelength-(W-1)))) THEN

        DO i=c1,c2
        excerpt(i)=m0(i)
        END DO

        CALL calk1(W,excerpt)

        OPEN (3,file='meank1.dat')
        READ (3,*) N,mk1
        OPEN (2,file='resultsk1.dat')
        DO i=1,N
        READ (2,*) k1(i)
        END DO

        sqsum=0.0d0
        DO i=1,N
        sqsum=dble(sqsum+((k1(i)-mk1)**2))
        s2=sqsum
        END DO
        vk1=(s2)/N
        sdk1=dsqrt(vk1)

        OPEN (4,file='resultsv.dat')
        v=dble(sdk1/mk1)
        snv=snv+1
        WRITE (4,11) snv,v
        CLOSE (2)
        CLOSE (3)
        mk1=0.0d0
        vk1=0.0d0
        sdk1=0.0d0
        v=0.0d0
        c1=c1+1
        c2=c2+1
        GOTO 14
        END IF
        CLOSE (4)
        END

My subroutine is:
      SUBROUTINE calk1(winlength,sm)

      DOUBLE PRECISION sm(100000),sumk1,sum,s,x,x2,k1,sk1,mk1
      INTEGER snk1

      OPEN (2,file='resultsk1.dat')
 10   FORMAT (g12.6)
      start=1
      w=winlength
      c3=6
      snk1=0
      sumk1=0.0d0
      sk1=0.0d0

  13  IF (c3.LE.w) THEN
      l1=1
      l2=c3
      c=c3
  12  IF ((l1.LE.(w-5)).AND.(l2.LE.w)) THEN
      sum=0.0d0
      s=0.0d0

      DO k=l1,l2
      sum=sum+sm(k)
      s=sum
      END DO

      av=0.0d0
      av2=0.0d0
      x=0.0d0
      x2=0.0d0
      DO k=l1,l2
      av=av+dble(((k)/(c))*(sm(k)/s))
      av2=av2+dble((((k)/(c))**2)*(sm(k)/s))
      x=av
      x2=av2
      END DO

      k1=x2-((x)**2)
      sumk1=sumk1+k1
      snk1=snk1+1
      WRITE (2,10) k1
      l1=l1+1
      l2=l2+1
      k1=0.0d0
      GOTO 12
      ELSE
      c3=c3+1
      GOTO 13
      END IF
      END IF
      CLOSE (2)

      N=snk1
      sk1=sumk1
      mk1=dble((sk1)/N)
      OPEN (3,file='meank1.dat')
      WRITE (3,10) N,mk1
      CLOSE (3)
      RETURN
      END

Comment: Can't you fix your indentation? The code is almost unreadable and cannot be compiled too.
Comment: @user3784273 You should have make an edit, not create a new question. Please read the help section and find how this site works. Voting to close.
Comment: @francescalus It's the same code.All i did is to put 4 0.0d0 in the place of 4 0's.I'm working with the above code right now.
Comment: Here you have `call calk1(W,excerpt(i))` and the other `call calk1(W,excerpt)`.  That's a _very_ big difference.  And potentially the source of your problme.
Comment: @francescalus. Yes,i'm sorry..My mistake.I've been trying debugging it for seneral hours and i posted one of my trials..I fixed it.The right version is call calk1(W,excerpt).
Comment: Please, do us a favor and delete one of your questions and make one of them readable and compilable. Thanks.
Answer: I haven't attempted to compile the code (I see there are still some errors that would upset a compiler), but I can suggest a problem.
However, the first thing to say is: if this is your code you'll make things much easier for yourself if you use much more modern Fortran features.
You say that excerpt changes each time before the subroutine is entered.  This is true, but not in a meaningful way.  Let's look at what is happening to the array.
This is all looped:
       c1=1
       c2=W

       DO i=c1,c2
         excerpt(i)=m0(i)
       END DO

       CALL calk1(W,excerpt)

       c1=c1+1
       c2=c2+1

Well, W isn't changed in an interation.  In this first iteration you are (using array syntax) setting excerpt(1:W)=m0(1:W); in the second setting excerpt(2:W+1)=m0(2:W+1), and so on.  That is: each time you call calk1, excerpt(1:W) is still exactly m0(1:W) which hasn't changed.  The only change to excerpt is after the W-th element, which you suggest won't be used in the subroutine anyway.
As to what you should do instead with that excerpt setting loop, I can't say: it depends on what you want to happen.  Perhaps
       DO i=c1,c2
         excerpt(i-c1+1) = m0(i)
       END DO

?
But use modern Fortran instead.
Comment: Thank you very much!Your suggestion on the excerpt setting loop partialy solved my problem but something else emerged..
Comment: Further, the dummy argument `sm` is of longer length than the actual argument `excerpt`, but this probably isn't the problem (it's still wrong).
Comment: Fixed it!Thank you very,very much!!!Your suggestion on the excerpt setting loop solved the problem!I know but Fortan g77 is all that i have access to right now..
Answer: When I try to compile this I get numerous compiler warnings and errors.  I suggest using maximum compile-time warning options from our compiler and clean up those problems.  That will clear out some problems with minimal effort.  With gfortran, try -O2 -ffixed-form  -ffixed-line-length-none  -W  -Wall -pedantic  -fimplicit-none  -Wsurprising  -Waliasing  -Wimplicit-interface  -Wunused-parameter  -fcheck=all  -pedantic  -fbacktrace.
Indenting your code with help you understand it.  And why use FORTRAN 77 in 2014?  Fortran 95/2003 is much easier to program in.


Azure Mobile Services Push not working

Question: I am trying to implement push to my app.
I've followed this guide:
http://azure.microsoft.com/en-us/documentation/articles/mobile-services-javascript-backend-ios-get-started-push/
However, I am using API's instead of the Data-scripts, so in one of my API methods I am doing this:
   var push = request.service.push;

   push.apns.send(null, {
    alert: "Alert",
    payload: {
        inAppMessage: "Hey, a new item arrived"
    }
   }, {
    success: function(resp) {
        console.log(resp)
    },
    error: function(err) {
        console.error(err)
    }
   });

My log is showing this (So I land in the success-method [Also I know that I should never land in error for iOS due to apples push server not responding with error]):
{ isSuccessful: true,
  statusCode: 201,
  body: '',
  headers:
   { 'transfer-encoding': 'chunked',
     'content-type': 'application/xml; charset=utf-8',
     server: 'Microsoft-HTTPAPI/2.0',
     date: 'Mon, 20 Oct 2014 11:31:21 GMT' },
  md5: undefined }

My app is registered correctly like this, I see the callback message and no error:
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken: (NSData *)deviceToken
{
    [client.push registerNativeWithDeviceToken:deviceToken tags:@[@"uniqueTag"] completion:^(NSError *error)
    {
        NSLog(@"registerNativeWithDeviceToken callback");
        if (error != nil)
        {
            NSLog(@"Error registering for notifications: %@", error);
        }
    }];
}

But no push message land in my iphone! Nothing is happening.
Im trying to check for errors in my Notification Hub but I see no log there.
What am I missing? I really don't get it where my actual device id is stored server side anyway. I must be missing something.
Thank you!
Answer: The best way to debug what is occurring is to follow the Notification Hub debugging steps here: http://msdn.microsoft.com/en-us/library/azure/dn530751.aspx
I would begin by using Service Bus Explorer to double-check the registration has the device token and tags you expect. After verifying that, please test sending an alert directly via the Notification Hub portal. If you still have issues, please send me an email at firstname.lastname@example.com.
Comment: The following blog explains tags: http://blogs.msdn.com/b/africaapps/archive/2013/10/22/windows-azure-notification-hubs-tags-and-creating-a-breaking-news-app.aspx We recommend the use of tags for user identification and for group identification. You can add tags either in your client or in the service.
Comment: Awesome! Of course it was a credential issue. It's working now. However, my "subquestion" still stands: Where are the device id's stored? How can I for example bind the id's to a user in my database?
Comment: @Spoek Sorry I missed your reply! If you are using a node Mobile Service, you can add a registration script via the portal. If you are using the .Net Mobile Services, you can add an INotificationHandler using these instructions: http://blogs.msdn.com/b/azuremobile/archive/2014/04/08/push-notifications-using-notification-hub-and-net-backend.aspx. Without knowing the pattern of your application, I cannot say the best place to connect this data to your back-end data but I do recommend using the ZUMO InstallationID or the user token's UserID as key tags for linking rather than deviceId.
Comment: This link walks through sending a notification to a specific userId in a bit more detail: http://azure.microsoft.com/en-us/documentation/articles/mobile-services-javascript-backend-ios-push-notifications-app-users/
Answer: Use your debug menu in Azure as @Todd Reifsteck said, and please test the tag name both "myTag" and myTag while debugging.

Azure Mobile Services Push not working


Random Forest - Variable Importance over time

Question: I've been looking at measures of variable importance for a random forest model - and was wondering if there are ways in which you can track how the variable importance shifts as the model is applied to datasets in the future.
The purpose of this question is to gain information as to whether a variable that was very important at model development is no longer that important when making predictions on future datasets either due to a change in population or a change in the variable itself (i.e. if this variable was somehow distorted and replaced with a column of missings it would no longer be important!).
Some example code  (sourced from : How to interpret Mean Decrease in Accuracy and Mean Decrease GINI in Random Forest models) may help illustrate the problem:
require(randomForest)
data(iris)
set.seed(1)
dat <- iris
dat$Species <- factor(ifelse(dat$Species=='virginica','virginica','other'))
model.rf <- randomForest(Species~., dat, ntree=25,
importance=TRUE, nodesize=5)
model.rf
varImpPlot(model.rf)

It seems that the variable importance plot can only be created on the dataset in which the random forest model was trained on as the variable importance plot function can only be applied to a random forest object (which stays the same no matter what dataset it is trying to score in the future).
Is there a built-in way (in Python or R) to compute variable importance over time, or is it not possible for some reason? My understanding is that if a new dataset possessed an outcome flag it would be possible to compute the mean decrease in gini.
Edit: Would also like to slightly expand this question to discuss potential ways on measuring variable stability over time. For example, in a standard logistic scorecard one would compute a characteristic stability index using the pre-defined bins. However, as many random forests have continuous inputs the choice of bins isn't natural and potentially there should be an alternative method?
Answer: Permutation importances would be suited for your goal, you can compute them as follows (example R code apended below):

Fit a RF on a training dataset.
Compute MSE on test
observations.
For each predictor variable, randomly permute the
values of that variable in the test set and compute the MSE again.
The difference between this MSE and the MSE computed under 2. is the
variables' contribution to the MSE reduction of the RF.

Note that this approach will not yield identical importance estimates for the training data as the default ones, also because there are many different ways variable importances are standardized, see also documentation of e.g., randomForest.
R code example:
## Generate toy data:
set.seed(42)
x1 <- rnorm(1000)
x2 <- rnorm(1000)
y <- 1*x1 + 2*x2 + rnorm(1000)
train <- data.frame(x1 = x1[1:500], x2 = x2[1:500], y = y[1:500])
test <- data.frame(x1 = x1[501:1000], x2 = x2[501:1000], y = y[501:1000])

## Fit random forest:
library("randomForest")
set.seed(42)
RF <- randomForest(y ~ x1 + x2, data = train, importance = TRUE)
importance(RF)

## Compute MSEs:
MSE_train <- mean((train$y - predict(RF, newdata = train))^2)
MSE_test <- mean((test$y - predict(RF, newdata = test))^2)
pred_names <- c("x1", "x2")
perm_MSEs_train <- perm_MSEs_test <- c(NA, NA)
names(perm_MSEs_train) <- names(perm_MSEs_test) <- pred_names

## Compute permutation importances:
for (i in pred_names) {
  test_temp <- test
  test_temp[ , i] <- sample(test[ , i])
  perm_MSEs_train[i] <- mean((test$y - predict(RF, newdata=test_temp))^2)
  train_temp <- train
  train_temp[ , i] <- sample(train[ , i])
  perm_MSEs_test[i] <- mean((train$y - predict(RF, newdata=train_temp))^2)
}
var(train$y)
MSE_train ## Note that overfitting occurred quite a bit: MSE should be 1
perm_MSEs_train - MSE_train
var(test$y)
MSE_test
perm_MSEs_test - MSE_test

Comment: I like the permutation approach as it's simple to implement and intuitive - many thanks!
Answer: My current solution is simply to retrain the model on newer data (but keeping the tuning parameters the same as development). This way the built in "importance" function can calculate updated variable importances.
This method is not optimal as it does not necessarily explain the causes behind a shift in predictions from the actual model that is being used (i.e. the one made at development).
Hence, would still appreciate any answers that could help with the original question.
Answer: I believe that the reason why we don't have the option to calculate variable importance on newer data is more a computational/complexity issue rather than actual practicality?
This is because when training the Random Forest model we are already looking at decrease in Gini to optimise splits so essentially we are getting variable importance information for free when training the model. Whereas to calculate mean decrease in gini on newer data would require us to go back into the trees and almost repeat the training procedure.
Also as mean decrease in accuracy (which is in the same importance function) uses the "Out Of Bag" data which is not possible on new data that isn't used for training - I guess adding the option to calculate importance on a dataset other than the development one wasn't considered.


distribution according to random measures

Question: Is a random probability measure a probability measure, i.e. if $X_i$ is random variable on some probability space $(\Omega,\mathcal F,\mathbb P)$ could its induced distribution be a random probability measure $\mu$, say $X_i\sim \mu$?
Then, as $\mu$ is itself random, it has an own probability distribution, $\mu\sim Q$.
For example let's take the empirical measure $P_n(A)=\frac{1}{n}\sum_{i=1}^n \delta_{X_i}(A)$. Then the empirical distribution function $F_n(x):=\frac{1}{n}\sum_{i=1}^n 1\{X_i\le x\}$ is a random probability measure as it is an empirical measure indexed by the class $\mathcal C=\{(-\infty,x]: x\in \mathbb R\}$? Can one say $X_i\sim P_n$?
Answer: For a random measure, it is just the case that $\Omega = \mathcal{P}$ the set of all probability measures on space. For example $P_n$ in your definition.
The empirical measure is a random variable on the space of functions. This measure is obtained via taking the push forward measure of the mapping $\pi: \mathcal{P}(\mathbb{R}) \mapsto \mathcal{S}$, where $\mathcal{S}$ is the collection of step functions in $\mathbb{R}$.
$X\sim \mu$ is for a fixed measure $\mu$. In your example, you cannot say $X_i \sim P_n$ because the distribution $X_i$'s is something from which you have drawn the random variables $X_i$'s to construct the measure in the first place ($P_n$ is just a function of $X_i$'s). But, if you wanted mean that $X$ is a "sample" from the empirical measure, then you have to keep in mind that there are two steps of randomness. The first step to construct the measure, and the second is taking a sample from $P_n$ conditionally on the $X_i$'s in the first step. So one needs to write the distribution of $X$ using a conditional distribution.
Comment: Consider you have a sample $X=(X_1,\dots, X_n).$ Now assume $X_i\mid \mu \sim \mu$ and $\mu\sim Q$, where $\mu$ is a random probability measure and $Q$ is the Distribution of the random probability measure. I think that is an example for the "two steps of randomness" you talked about. Can you explain what $X_i\mid \mu \sim \mu$ means and why we can't use/ what's the difference to $X_i\sim \mu$? Many thanks!
Comment: The conditional distribution will be a discrete measure. Suppose you toss a coin 6 times and you get TTHTTH. So your empirical measure $P_n$ will give mass 1/3 on head and 2/3 on tail. But $X_1$ is Bernoulli$(1/2)$. What you can do is take a new coin with respect to the observed empirical measure. The outcome  $Y$ will be Bernoulli $(1/3)$ conditional on the event that there are exactly $2$ heads among $(X_1,\dots,X_6)$.