Interaction using generalized linear mixed model

Question: I am conducting a GLMM. I currently have two independent variables (1, 2) and a dependent variable () - all factors (either 0 or 1).
m <- glmer(y ~ x1+x2+x1:x2 + (1 | participant), data = mydata, family = binomial)
I am mostly interested in the x1 main effect and in the interaction between x1 and x2.
When all (x1  x2   x1:x2) in the model, only the two main effects are significant (the interaction is N.S.).
Is there something I can do in order to fit a better model?
Thank you :)
Your help is much appreciated!
Comment: You can check whether the assumptions of the binomial model are not violated. You can also try other classification models beside GLMM and then compare the models, for instance, using cross-validation.
Answer:
Is there something I can do in order to fit a better model?

I would recommend not seeking to find a "better model".
You have 3 variables besides the outcome. One is a grouping factor that you are fitting random intercepts for. The outcome is binary so you are fitting a logistic model with 2 covariates and the interaction between them. There is nothing wrong with this as a model for these data, based on the information given. There is nothing you can really do unless you have more data and/or more variables (competing exposures). Perhaps there is really no interaction in the population. Presumably you did a power calculation before collecting the data, but if not, perhaps the dataset is too small to find the interaction of interest. What if you had found a "significant" interaction, but the effect size was tiny and meaningless ?
Comment: @Sharon does this answer your question ? If so, please consider marking it as the accepted answer. If not then please let us know why


Foreach dentro de foreach

Question: Preciso executar um foreach dentro de outro foreach no PHP. Porém ele me retorna o seguinte erro:

Parse error: syntax error, unexpected T_FOREACH
se referindo à linha onde ocorre o segundo foreach.

Segue parte do código:
$select = $bd -> prepare("SELECT * FROM umatabela ORDER BY id DESC");
$select -> execute();
$Fetch = $select -> fetchAll(PDO::FETCH_ASSOC);
$Conta = $select -> rowCount();

if ($Conta) {
  foreach ($Fetch as $postagem) {
    $oilUser = $postagem["sla"];

    $selectFoto = $bd->prepare("SELECT foto FROM outratabela WHERE cond='$oilUser' LIMIT 1");
    $selectFoto -> execute();
    $FetchFoto = $selectFoto -> fetchAll(PDO::FETCH_ASSOC);

    echo "
    ".foreach($FetchFoto as $autorFoto) {
    echo "";
    }."
  }
}

Como posso resolver isso? Lembrando que, preciso fazer as consultas em 2 tabelas diferentes.
Answer: Você não pode concatener um foreach com uma string como tentou fazer. Precisa separar as coisas:
echo "";
foreach($FetchFoto as $autorFoto) {
    echo "";
}
echo "";

Answer: Não pode concatenar um foreach segue como deveria ficar.
<?php
$select = $bd -> prepare("SELECT * FROM umatabela ORDER BY id DESC");
$select -> execute();
$Fetch = $select -> fetchAll(PDO::FETCH_ASSOC);
$Conta = $select -> rowCount();

if($Conta) {
    foreach($Fetch as $postagem) {
        $oilUser = $postagem["sla"];

        $selectFoto = $bd -> prepare("SELECT foto FROM outratabela WHERE cond = '$oilUser' LIMIT 1");
        $selectFoto -> execute();
        $FetchFoto = $selectFoto -> fetchAll(PDO::FETCH_ASSOC);

        $fotos = "";

        foreach ($FetchFoto as $autorFoto ) {
           $fotos .= "";
        }

        echo "

                '.$fotos.'
            ";
    }
}

?>

Comment: Só pra eu entender, qual é a diferença entre essa solução e a do @bfavaretto?
Comment: A diferença e so pela maneira de fazer as coisas eu dessa forma guardo todas as imagens do foreach na variável `$fotos` e depois do chamo a variável `$fotos` para as listar e só uma maneira que fica mais limpo o código

Foreach dentro de foreach


Classes abstratas em Python

Question: O método __subclasscheck__ deve ser definido a nível de metaclasse, já o método __subclasshook__ pode ser definido como um método de classe desde que a classe possua como metaclasse ABC (ou uma de suas derivadas).
Minha dúvida é quando criamos uma abstração implementando ABCMeta como metaclasse, podemos fazer uso do decorador @abstractmethod que define que o método deve ser sobrescrito na classe derivada, mas vi em muitos códigos fazerem o uso desses métodos (__subclasscheck__, __subclasshook__) para fazer a validação seja da implementação dos métodos que devem ser sobrescritos ou alterar o comportamento do método issubclass(). Alguém poderia me dizer um caso de uso onde deva-se implementar esses métodos.
Answer: "Prover casos de uso" para esse tipo de feature é bem complicado - tratam-se de funcionalidades colocadas no core da linguagem para permitir manipualção e customização avançada de hierarquia de classes -  o tipo de coisas que vai precisar ser feito uma vez, por exemplo, num ORM, ou próximo as classes-base de um projeto com uma hierarquia grande de classes e especificidades muito bem definidas.
A maior parte dos projetos - mesmo os grandes, vai usar frameworks que já vão ter esse tipo de funcionalidade definida (seja o Django, seja algum outro usando SQLAlchemy): ou seja - é bem dificil  imaginar um caso de uso para essas funcionalidades. Um caso de uso concreto e simples mais díficil ainda.
Basicamente, o __subclasscheck__ em si, junto com o __instancecheck__ são funcionalidades da linguagem em si. Não seria falso dizer que foram introduzidas na linguagem justamente para permitir que o módulo ABC (Abstract base Classes) fosse criado com as funcionalidades que tem hoje.
Basicamente eles permitem que ao definir uma metaclasse você possa customizar e dizer que alguma outra classe, ou objeto de uma classe não relacionado com as classes da sua hierarquia (isso é, as classes definidas com a sua metaclasse), são instâncias das mesmas - mesmo que isso nunca tenha sido a intenção de quem escreveu a classe original.
Então - para dar um exemplo concreto: Python usa as ABCMeta para definir as classes em collections.ABC - essas sim, podendo ter bastante uso no dia a dia, permitindo a implementação rápida e simples de sequências e mappings pelo usuário (mesmo assim, tem mais uso em uma biblioteca intermediária que num projeto final). Mas basicamente, ao desenhar a collections.abc.MutableSequence seria interessante que se alguém perguntasse se uma list de Python é uma MutableSequence a resposta fosse True: ou seja, uma lista tem sim a interface de uma MutableSequence. E é para isso que esses mecanismos são usados na biblioteca padrão do Python:  para dizer que os tipos de dados nativos do Python - set, frozenset, list, tuple, string, dict são "subclasses" das classes abstratas correspondentes:
In [39]: issubclass(dict, collections.abc.MutableMapping)
Out[39]: True

O mesmo mecanismo é usado na classe typing da stdlib, que está lá para prover mecanismos de type-hinting para código moderno:
In [41]: issubclass(list, typing.MutableSequence)
Out[41]: True

(a MutableSequence do módulo typing no entanto, existe  para indicar que naquele ponto qualquer tipo que tenha a interface de uma "Sequência mutável" vai ser aceito - enquanto que collections.abc.MutableSequence por outro lado existe para ser uma classe base para implementações pelo usuário de MutableSequences escrevendo-se o mínimo de código possível. São coisas diferentes)
Já - ao contrário do __subclasscheck__, que vai na metaclasse e é uma feature da linguagem, o __subclasshook__ é definido apenas pelo módulo abc e sua metaclasse ABCMeta - basicamente, o __subclasscheck__ de abc.ABCMeta faz a chamada ao __subclashook__. Ou seja - o próprio mecanismo do __subclasshook__ é um exemplo do que pode ser feito com o __subclasscheck__: permitir que a própria classe tenha um método para dizer se uma outra classe é uma subclasse dela mesma (sem precisar escrever código diferente na metaclasse para cada classe que você quiser testar esse tipo de coisa)
Resumindo:
Em 98% dos casos você não vai precisar de nenhuma dessas funcionalidades.
No caso de você estar definindo uma hierarquia de classes que faça uso de calsses abstratas, você pode, nas classes base da sua hierarquia, usar o __subclashook__ para dizer qual vai ser a resposta das chamadas embutidas do Python issubclass e isinstance para objetos (e classes) fora da sua hierarquia.  (ou cruzando ramos da sua hierarquia). Esses são os "2%" restantes.
Na biblioteca padrão esse mecanismo é usado para dizer que os tipos nativos como dict, list, etc...são subclasses de "MutableMapping", "MutableSequence"... conforme apropriado.

Classes abstratas em Python


Covariance structure for random intercepts and slopes

Question: Can you please help me figuring out what the covariance structure of a model with random intercept and random slope is?
Here is my model $Y_{ij} = \beta_0 + \beta_1 t_{ij} + b_{0,i} + b_{1,i}t_{ij} + e_{ij}$
where $b_{0,i}$ and $b_{1,i}$ are random intercept and random slope and we know that $e_{ij}$ are mutually independent and also:
$b_i$ ~ $N(0,D)$ where $b_i = (b_{0,i},b_{1,i})$ and $e_{ij}$ ~ $N(0,\sigma^2)$
I appreciate your help.
Answer: Using the properties of the covariance operator we have
$$$$
$$\begin{align*}
\textrm{Cov}(Y_{ij}, Y_{ik})
& = \textrm{Cov}(\beta_0 + \beta_1 t_{ij} + b_{0i} + b_{1i} t_{ij} + e_{ij}, \;
                 \beta_0 + \beta_1 t_{ik} + b_{0i} + b_{1i} t_{ik} + e_{ik}) \\
& = \textrm{Cov}(b_{0i} + b_{1i} t_{ij} + e_{ij}, \;
                 b_{0i} + b_{1i} t_{ik} + e_{ik}) \\
& = \textrm{Cov}(b_{0i}, \; b_{0i})
        + t_{ik} \, \textrm{Cov}(b_{0i}, \; b_{1i})
        + \textrm{Cov}(b_{0i}, \; e_{ik}) \\
& \quad +\, t_{ij} \, \textrm{Cov}(b_{1i}, \; b_{0i})
        + t_{ij} t_{ik} \, \textrm{Cov}(b_{1i}, \; b_{1i})
        + t_{ij} \, \textrm{Cov}(b_{1i}, \; e_{ik}) \\
& \quad +\, \textrm{Cov}(e_{ij}, \; b_{0i})
        + t_{ik} \, \textrm{Cov}(e_{ij}, \; b_{1i})
        + \textrm{Cov}(e_{ij}, \; e_{ik})  \\
& = \textrm{Var}(b_{0i})
        +\, (t_{ij} + t_{ik}) \textrm{Cov}(b_{0i}, \; b_{1i})
        +\, t_{ij}t_{ik} \textrm{Var}(b_{1i})
        +\, \textrm{Cov}(e_{ij}, \; e_{ik})
\end{align*}$$
$$$$
If $j \neq k$, then
$$\begin{align*}
\textrm{Cov}(Y_{ij}, Y_{ik})
 & = \textrm{Var}(b_{0i})
        + (t_{ij} + t_{ik}) \, \textrm{Cov}(b_{0i}, \; b_{1i})
        + t_{ij} t_{ik} \textrm{Var}(b_{1i})
\end{align*}$$
If $j = k$, then
$$\begin{align*}
\textrm{Cov}(Y_{ij}, Y_{ik})
 & = \textrm{Var}(Y_{ij}) \\
 & = \textrm{Var}(b_{0i})
        + 2 \, t_{ij} \, \textrm{Cov}(b_{0i}, \; b_{1i})
        + t_{ij}^2 \textrm{Var}(b_{1i})
        + \sigma^2
\end{align*}$$
$$$$
$\textrm{Var}(b_{0i})$, $\textrm{Var}(b_{1i})$, and $\textrm{Cov}(b_{0i}, \; b_{1i})$ are found in your matrix $D$.


Existe alguma maneira de eliminar elementos duplicados que não sejam exatamente iguais?

Question: dados1 <- c("10 ANOS DA POLÍTICA NACIONAL DE PROMOÇÃO DA SAÚDE: TRAJETÓRIAS E DESAFIOS", "4-CYCLOPROPYL-1-(1-METHYL-4-NITRO-1H-IMIDAZOL-5-YL)-1H-1,2,3-TRIAZOLE AND ETHYL 1-(1-METHYL-4-NITRO-1H-IMIDAZOL-5-YL)-1H-1,2,3-TRIAZOLE-4-CARBOXYLATE","7,7-DIMETHYLAPORPHINE AND OTHER ALKALOIDS FROM THE BARK OF", "ABSCESSO DO MÚSCULO PSOAS ASSOCIADO À INFECÇÃO POR MYCOBACTERIUM TUBERCULOSIS EM PACIENTE COM AIDS", "ABUNDANCE OF LUTZOMYIA LONGIPALPIS TESTE","ABUNDANCE OF LUTZOMYIA LONGIPALPIS", "ABUSO E DEPENDÊNCIA DE DROGAS NA PERSPECTIVA DA SAÚDE PÚBLICA (EDITORIAL)")

qualis <- c("A2", "B3", "A1", "B2", "A2", "A2", "A1")

m <- data.frame("Título da Produção" = dados1,
                "Qualis" = qualis,
                "Ano" = c(2010:2016))

O df acima é apenas ilustrativo. Notem que o quinto e sexto elemento de "dados1" são praticamente a mesma coisa, mas como não estão escritos da mesma maneira não consigo utilizar o duplicated e nem o unique.
Há alguma outra opção para limpar essas linhas, filtrando por parte do nome?
Answer: Fiz uma função que pode te ajudar. Ela usa o pacote stringdist que calcula a distância entre strings:
combinar_textos_parecidos <- function(x, max_dist){
  x <- as.character(x)
  distancias <- stringdist::stringdistmatrix(x, x)
  for(i in 1:length(x)){
    small_dist <- distancias[i,] < max_dist
    if(sum(small_dist) > 1){
      x[small_dist] <- x[which(small_dist)[1]]
    }
  }
  return(x)
}

Veja o que ela retorna quando aplico no seu vetor Título.da.Produção. Agora os itens 5 e 6 possuem exatamente o mesmo nome.
combinar_textos_parecidos(m$Título.da.Produção, 10)
[1] "10 ANOS DA POLÍTICA NACIONAL DE PROMOÇÃO DA SAÚDE: TRAJETÓRIAS E DESAFIOS"
[2] "4-CYCLOPROPYL-1-(1-METHYL-4-NITRO-1H-IMIDAZOL-5-YL)-1H-1,2,3-TRIAZOLE AND ETHYL 1-(1-METHYL-4-NITRO-1H-IMIDAZOL-5-YL)-1H-1,2,3-TRIAZOLE-4-CARBOXYLATE"
[3] "7,7-DIMETHYLAPORPHINE AND OTHER ALKALOIDS FROM THE BARK OF"
[4] "ABSCESSO DO MÚSCULO PSOAS ASSOCIADO À INFECÇÃO POR MYCOBACTERIUM TUBERCULOSIS EM PACIENTE COM AIDS"
[5] "ABUNDANCE OF LUTZOMYIA LONGIPALPIS TESTE"
[6] "ABUNDANCE OF LUTZOMYIA LONGIPALPIS TESTE"
[7] "ABUSO E DEPENDÊNCIA DE DROGAS NA PERSPECTIVA DA SAÚDE PÚBLICA (EDITORIAL)"

Então fazendo:
m$Título.da.Produção <- combinar_textos_parecidos(m$Título.da.Produção, 10)
m[!duplicated(m$Título.da.Produção),]

A linha 5 seria excluida.
Obs usei a distancia 10 como ponto de corte. Talvez você queira ser mais ou menos tolerante com a proximidade das strings. Para isso basta controlar o parâmetro max_dist da minha função.
Você pode ler mais sobre o cálculo das distâncias aqui ou digitando help("stringdist-metrics") no seu console do R.
Comment: Muito obrigado.
Comment: `dados$Título.da.Produção <- combinar_textos_parecidos(dados$Título.da.Produção, 10)
Error in distancias[i, ] : subscript out of bounds` obrigado.
mas ainda estou tentando entender o problema.
Comment: Esse erro está acontecendo provavelmente pq vc não tem essa coluna no seu banco de dados. Veja o que acontece qundo faço a função de `NULL`: `> combinar_textos_parecidos(NULL, 10)
Error in distancias[i, ] : subscript out of bounds`.


Multiple Django sites on a single SSL certificate using a single IP with Apache

Question: Is it technically possible to setup multiple Django sites using a single SSL certificate on a single IP address with Apache?
Below is an excerpt from my SSL config:
Alias /media/ x:/home/djang-apps/myapp
WSGIScriptAlias / x:/home/djang-apps/myapp/apache/django.wsgi

<Directory x:/home/djang-apps/>
   Order allow,deny
   Allow from all
</Directory>

One of the issues I've come up against is since I only have a single IP address I have only 1 virtual host therefore how can I reference the varius media folders that contain the css/images/js etc for each Django website as well as the WSGIScriptAlias for each site?
I currently have a wild card certificate for *.foo.com
So I would like to be able to add several sites in this fashion:
website1.foo.com
website2.foo.com
website3.foo.com
Answer: You'll need to configure a NameVirtualHost directive, and configure a VirtualHost for each different domain.
For example:
NameVirtualHost *:443

<VirtualHost *:443>
    ServerName app1.foo.com
    ServerAlias www.app1.foo.com
    SSLEngine On
    SSLCertificateFile x:/path/to/cert.pem
    SSLCertificateKeyFile x:/path/to/cert.key
    # Any other basic config, logging, etc..
    DocumentRoot x:/home/djang-apps/app1
    # Any other document mapping; that Alias directive, WSGIScriptAlias, etc
</VirtualHost>

<VirtualHost *:443>
    ServerName app2.foo.com
    ServerAlias www.app2.foo.com
    SSLEngine On
    SSLCertificateFile x:/path/to/cert.pem
    SSLCertificateKeyFile x:/path/to/cert.key
    # Any other basic config, logging, etc..
    DocumentRoot x:/home/djang-apps/app2
    # Any other document mapping; that Alias directive, WSGIScriptAlias, etc
</VirtualHost>

Apache may do some whining during startup about Server Name Indication, which you can safely ignore since you're using a wildcard certificate (just make sure that the SSL directives in each vhost all point to the wildcard cert).
Comment: many thanks, I had managed to get it to work before you answered my question, however Apache was complaining so I thought I was doing something wrong, but now I know why and I can ignore it thanks to you!


Question from permutations.

Question: Six boys and six girls sit along a line alternately in $x$ ways and then sit along a circle alternately is $y$ ways. then express a relationship between $x$ and $y$ .
The answer is supposed to be $x=12y$ however I am having trouble understanding it. Here is how i attempted it. Please correct me.
For the linear arrangement , let the six boys first occupy six seats leaving a seat each seat between any two boys vacant. They can be arranged in $6!$ ways. Now there are $7$ seats for the girls so the girls can be arranged in ${{7}\choose{6}}6!$ ways. So the linear arrangement of boys and girls is possible in $(7!)(6!)$ ways. For the circular arrangement, place a boy first and arrange the remaining boys in alternating seats in $5!$ ways. Now , similarly the girls can be arranged in $5!$ ways. Hence the circular arrangement is possible in $(5!)(5!)$ ways.
However , according to the solution that I read , the the linear arrangement is possible in $2(6!)^2$ and the circular arrangement is possible in $(5!)(6!)$ways. Can you please explain where I went wrong ? Thank you for your help !
Answer: The simple way is to bend the line into a circle.  The only change is we don't know where the line started, which is a factor $12$ and we are done.
In your approach you don't have seven seats for girls, you have six seats plus a factor $2$ for whether the first seat is a girl or boy.  There are $2\cdot 6! \cdot 6!$ ways to arrange them in a line.  The $5!6!$ for a circle is correct and the ration between these is again $12$

Question from permutations.


An example of a linear transformation that is not 1-1 or onto but has bijective dual

Question: This is a question from some ring theory problems in Linear Algebra.
I am not sure if this question is simple enough to come up with a linear map on a finite dimensional vector space but here it goes.

Give an example of a linear map between two vectors spaces such that the dual is bijective but the original map is neither 1-1 or onto.

If the vector spaces in question have finite dimension we would require the matrix representing the transpose to have determinant zero but the transpose to be singular so that is why I am thinking there must be an infinite dimensional example.
Comment: No such example exists: If $f$ is not injective, then $f^*$ is not surjective. If $f$ is not surjective, then $f^*$ is not injective.
Comment: I know what the transpose of a matrix is.  I don't know what the transpose of a linear map is, especially on an infinite-dimensional vector space.  Do you perhaps mean dual, adjoint,...?
Comment: Hi @Pete: I think it's more or less standard to call *transpose* what you probably call *dual*. It's Bourbaki's terminology. I personally use it. (Of course, it's more important to know what **the OP** means...)
Comment: Here is an example: Let $R$ be $\mathbb Z$ and $f$ the zero endomorphism of $\mathbb Z/2\mathbb Z$.
Comment: Thanks is there still no examples  if we relax the hypothesis to R-module homomorphisms between two modules where R is a commutative ring with identity?
Comment: @Pierre-Yves: thanks for the pointer to the terminology.  I guess I haven't read enough of Bourbaki's ("Not necessarily commutative") *Algebra* to see/remember this.  If I am not mistaken though, most anglophone mathematicians speak of dual maps, not transpose maps.  (A magical phrase, "If I am not mistaken": it makes almost anything true!) By the way...you seem to have **answered the question**: perhaps you should leave your comment as an answer?
Answer: I'll follow Wikipedia's terminology: If $f:V\to W$ is a linear map, then the transpose (or dual) $f^*:W^*\to V^*$ is defined by $$f^*(\varphi)=\varphi\circ f.$$
The first question is: Give an example of a linear map between two vectors spaces such that the transpose is bijective but the original map is neither 1-1 nor onto.
There are no such examples. Indeed, in the above notation, if $f:V\to W$ is not injective, then $f^*:W^*\to V^*$ is not surjective, because the image of $f^*$ consists of those linear forms on $V$ which vanish on $\ker f$. Similarly, if $f$ is not surjective, then $f^*$ is not injective, because the kernel of $f^*$ consists of those linear forms on $W$ which vanish on $f(V)$.
Another question was added in the comments: Are there still no examples if, instead of vector spaces, we consider modules over a commutative ring $R$ with identity?
Such examples exist. A cheap one is given by setting $R=\mathbb Z$, $V=W=\mathbb Z/2\mathbb Z$, $f=0$.
EDIT. In fact we have canonical isomorphisms
(1) $\text{Ker}(f^*)=\text{Coker}(f)^*$ and $\text{Coker}(f^*)=\text{Ker}(f)^*$.
This can bee seen as follows:
(2) If
$$
0\to A\overset{i}{\to}V\overset{f}{\to}W\overset{p}{\to}B\to0
$$
and
$$
0\to A'\overset{i'}{\to}V\overset{f}{\to}W\overset{p'}{\to}B'\to0
$$
are exact sequences of $K$-vector spaces, then there is a unique linear map $a:A\to A'$, and a unique linear map $b:B\to B'$ such that $i'\circ a=i$ and $b\circ p=p'$. Moreover $a$ and $b$ are bijective. The proof is easy.
(3) We have the exact sequences
$$\begin{matrix}
0\to&\text{Ker}(f)&\overset{i}{\to}V\overset{f}{\to}W\overset{p}{\to}&\text{Coker}(f)&\to0,\\ \\
0\to&\text{Coker}(f)^*&\overset{p^*}{\to}W^*\overset{f^*}{\to}V^*\overset{i^*}{\to}&\text{Ker}(f)^*&\to0,\\ \\
0\to&\text{Ker}(f^*)&\to W^*\overset{f^*}{\to}V^*\to&\text{Coker}(f^*)&\to0.
\end{matrix}
$$
Then (1) follows from (2) and (3).
Comment: Dear @user7980: You're welcome. Put $A:=\mathbb Z/2\mathbb Z$. We have $$H:=\text{Hom}_\mathbb Z(A,\mathbb Z)=0.$$ Indeed, an $f\in H$ is just a morphism of abelian groups, and for any $a$ in $A$, we have $$f(a)+f(a)=f(a+a)=f(0)=0,$$ and thus $f(a)=0$. The iso $\text{End}_\mathbb Z (A)\cong A$ is correct. Here is a possible generalization: if $C$ is a cyclic group with generator $c$, then $\text{End}_\mathbb Z (C)\cong C$, the iso being the evaluation at $c$.
Comment: Thanks for the answer - I am just going through checking the details and cannot remember if the following isomorphisms are correct:  $Hom_\mathbb{Z}(\mathbb{Z}_2, \mathbb{Z}) \cong \mathbb{Z}_2$ and  $Hom_\mathbb{Z}(\mathbb{Z}_2, \mathbb{Z}_2) \cong \mathbb{Z}_2$


Edit style of grid.arrange title. Bold, italic etc. R

Question: I am creating a multi plot in R using grid.arrange, and wanted to change my title so that it is bold (and italic if possible).
As this is a general question, I will not include the code for my plots, but the code I am using to make my multi plot is:
grid.arrange(g1, g3, g4+theme(legend.position="none"),mylegend, top="Test title",
             layout_matrix=matrix(c(1,1,2,3,4,4), ncol=2, byrow=TRUE),heights=c(1,1.5,0.3))

Are there any additional arguments which can be passed to the top argument to change the font face?
Answer: I've worked it out myself..
You can use the text_grob function to create a text element, which can then be passed to the top function of grid.arrange.
For example,
##title1=textGrob("Test title", gp=gpar(fontface="bold")) ## this does not work anymore

title1=text_grob(main, size = 15, face = "bold")   #### this worked for me
grid.arrange(g1, g3, g4+theme(legend.position="none"),mylegend, top=title1, ncol=2, byrow=TRUE),heights=c(1,1.5,0.3))

Just a small update:
Instead of using text
textGrob

use text_grob from ggpubr package


Ratio of cosines in a triangle with bisector is eccentricity of hyperbola

Question:
Given $F_1$, $F_2$ are foci of hyperbola $h$, $A$ is a point on the second branch of $h$, $AB$ is a bisector of $F_1AF_2$, $\alpha = \angle F_1AB=\angle BAF_2$, $\beta=\angle ABF_2$, proof that:
$$
\frac{\cos\alpha}{\cos\beta} = \epsilon,
$$
where $\epsilon$ is eccentricity.
I am interested in a simple geometric proof.
Below is the physics/algebraic proof I came up with. It can be made rigorous if needed.

Take a neighbour point $A'\in h$, $AA' = dx \ll AF_{1,2}$, draw perpendiculars $A'H_1$, $A'H_2$ to $AF_1$ and $AF_2$
Since $\angle AF_1B = \beta-\alpha$ and $\angle AF_2B = \pi-\beta-\alpha$, , we conclude

$$A'H_1 = AF_1 (d\beta-d\alpha), \qquad A'H_2 = AF_2(d\beta+d\alpha)$$

From $A'H_1=A'H_2 = dx \sin\alpha$, we find
$$
\frac{d\alpha}{d\beta} = \frac{AF_1-AF_2}{AF_1+AF_2}
$$

From sine law in $ABF_2$ and bisector property ($F_1A:F_2A = F_1B:F_2B$):
$$
\frac{\sin\alpha}{\sin\beta} = \frac{BF_2}{AF_2} = \frac{F_1F_2}{AF_1+AF_2}
$$

From (3) and (4):
$$
\frac{d\cos\alpha}{d\cos\beta} = \frac{\sin\alpha\ d\alpha}{\sin\beta\ d\beta} = \frac{AF_1-AF_2}{F_1F_2} = \frac{2a}{2c}=\epsilon
$$

Thus, $\cos \alpha = \epsilon\cos\beta + C$, and when $A\to$ point on $F_1F_2$, $\cos\alpha\to 0$ and $\cos\beta\to 0$, so $C=0$
Answer: Apply the cosine rule to triangles $AF_1B$ and $AF_2B$, to find $BF_1^2$ and $BF_2^2$. Subtracting the results we get:
$$
BF_1^2-BF_2^2=AF_1^2-AF_2^2-2AB(AF_1-AF_2)\cos\alpha.
$$
Apply then the cosine rule to the same triangles, to find $AF_1^2$ and $AF_2^2$. Subtracting the results we get:
$$
AF_1^2-AF_2^2=BF_1^2-BF_2^2+2AB(BF_1+BF_2)\cos\beta.
$$
Comparison of these equalities yields
$$
2AB(BF_1+BF_2)\cos\beta=2AB(AF_1-AF_2)\cos\alpha,
$$
that is:
$$
{\cos\alpha\over\cos\beta}={BF_1+BF_2\over AF_1-AF_2}=\epsilon.
$$
Comment: Nice one! Thanks!


Como obter um único elemento através do array.filter

Question: Utilizando array.map e array.filter, seleciono apenas um objeto de address, porém seu retorno contém um array com índices vazios.
O array possui a seguinte estrutura:
[
  {
    "formatted_address": "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
    "address_components": [
      {
        "long_name": "long name",
        "short_name": "short name",
        "types": [
          "route"
        ]
      }
    ]
  },
  {
    "formatted_address": "Williamsburg, NY, USA",
    "address_components": [
      {
        "long_name": "long name",
        "short_name": "short name",
        "types": [
          "locality"
        ]
      }
    ]
  },
  {
    "formatted_address": "New York 11211, USA",
    "address_components": [
      {
        "long_name": "long name",
        "short_name": "short name",
        "types": [
          "postalCode"
        ]
      }
    ]
  },
  {
    "formatted_address": "Kings, New York, USA",
    "address_components": [
      {
        "long_name": "long name",
        "short_name": "short name",
        "types": [
          "locality"
        ]
      }
    ]
  },
  {
    "formatted_address": "Brooklyn, New York, USA",
    "address_components": [
      {
        "long_name": "long name",
        "short_name": "short name",
        "types": [
          "administrative_area_level_2"
        ]
      }
    ]
  },
  {
    "formatted_address": "New York, New York, USA",
    "address_components": [
      {
        "long_name": "long name",
        "short_name": "short name",
        "types": [
          "administrative_area_level_2"
        ]
      }
    ]
  },
  {
    "formatted_address": "New York, USA",
    "address_components": [
      {
        "long_name": "long name",
        "short_name": "short name",
        "types": [
          "administrative_area_level_1"
        ]
      }
    ]
  },
  {
    "formatted_address": "United States",
    "address_components": [
      {
        "long_name": "long name",
        "short_name": "short name",
        "types": [
          "country"
        ]
      }
    ]
  }
]

let address = [];

address.push({
  formatted_address: "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['route']
  }]
});
address.push({
  formatted_address: "Williamsburg, NY, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['locality']
  }]
});
address.push({
  formatted_address: "New York 11211, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['postalCode']
  }]
});
address.push({
  formatted_address: "Kings, New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['locality']
  }]
});
address.push({
  formatted_address: "Brooklyn, New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['administrative_area_level_2']
  }]
});
address.push({
  formatted_address: "New York, New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['administrative_area_level_2']
  }]
});
address.push({
  formatted_address: "New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['administrative_area_level_1']
  }]
});
address.push({
  formatted_address: "United States",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['country']
  }]
});

let administrative_area_level_1 = address.map((address) => {
  return address.address_components.filter((elem, i, array) => {
    if (elem.types.includes('administrative_area_level_1')) {
      return elem;
    }
  });
});

console.log(administrative_area_level_1);

Após o tratamento, é retornado:
[
  [],
  [],
  [],
  [],
  [],
  [],
  [
    {
      "long_name": "long name",
      "short_name": "short name",
      "types": [
        "administrative_area_level_1"
      ]
    }
  ],
  []
]

Quando o esperado seria:
 {
  "long_name": "long name",
  "short_name": "short name",
  "types": [
    "administrative_area_level_1"
  ]
}

Comment: Marcelo, na pergunta dás exemplo de somente 1 objeto, mas pode ter mais certo? e pode ter mais que um por cada `address_components`?
Comment: Pode sim, @Sergio. Terminei reduzindo no exemplo utilizado.
Comment: Ok, então a minha resposta deve fazer o que queres. Se quisesses reduzir mais podias usar o `.find` também.
Comment: Sim, tua resposta já direcionou-me a um resultado positivo.
Comment: Ok, mas era isso que demos nas respostas que procuravas ou ainda falta alguma coisa?
Answer: let address = [];

address.push({
  formatted_address: "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['route']
  }]
});
address.push({
  formatted_address: "Williamsburg, NY, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['locality']
  }]
});
address.push({
  formatted_address: "New York 11211, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['postalCode']
  }]
});
address.push({
  formatted_address: "Kings, New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['locality']
  }]
});
address.push({
  formatted_address: "Brooklyn, New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['administrative_area_level_2']
  }]
});
address.push({
  formatted_address: "New York, New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['administrative_area_level_2']
  }]
});
address.push({
  formatted_address: "New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['administrative_area_level_1']
  }]
});
address.push({
  formatted_address: "United States",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['country']
  }]
});

address.map((address) => {
  return address.address_components.filter((elem, i, array) => {
    if (elem.types.includes('administrative_area_level_1')) {
       administrative_area_level_1 = elem;
    }
  });
});

console.log(administrative_area_level_1);

Answer: Sugiro filtrar primeiro pois reduzes logo o tamanho da array para futuro processamento, e depois mapear o que passar o filter.

let address = [];

address.push({
  formatted_address: "275-291 Bedford Ave, Brooklyn, NY 11211, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['route']
  }]
});
address.push({
  formatted_address: "Williamsburg, NY, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['locality']
  }]
});
address.push({
  formatted_address: "New York 11211, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['postalCode']
  }]
});
address.push({
  formatted_address: "Kings, New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['locality']
  }]
});
address.push({
  formatted_address: "Brooklyn, New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['administrative_area_level_2']
  }]
});
address.push({
  formatted_address: "New York, New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['administrative_area_level_2']
  }]
});
address.push({
  formatted_address: "New York, USA",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['administrative_area_level_1']
  }]
});
address.push({
  formatted_address: "United States",
  address_components: [{
    long_name: 'long name',
    short_name: 'short name',
    types: ['country']
  }]
});

let administrative_area_level_1 = address.filter((address) => {
  return address.address_components.find(
    comp => comp.types.includes('administrative_area_level_1')
  );
}).map(address => address.address_components);

console.log(administrative_area_level_1);


Results with and without interaction

Question: I'm working on an analysis with another person. First we did a logistic regression with study group and variable X. They were both significant. Then we added the interaction between study group and X only the study group and the interaction were significant. Actually, there are 3 groups and only one of the groups and one of the group*X interactions is significant.
I am having a hard time to convince this person that we should not present the odds ratios for X from the first analysis that do not account for this interaction. This person thinks that we can show the results of the first analysis AND then the second analysis. I think this is misleading and will confuse people.
I am not the best at explaining things (as you can tell), so any help with how to argue my point would be appreciated.
Answer: I agree that it could cause confusion to present two fitted models, especially since it appears that one of them may not fit the data very well. You can tell by comparing the deviance or some other fit statistics for the two models to see if adding the interaction makes an important difference overall.
The reason the significance of the effects changes is because there is multicollinearity. The interaction effects are doing a better job of explaining some of the effects that previously were explained by $X$ alone. This could happen, for example, if $X$ Is important for one group but not the others. Without the interaction, we are fitting an average X trend to the groups, which could be significant by virtue of the one group where it is significant. I'm not saying that's exactly what is happening, just that that is one plausible scenario.
What you can do to explain the one model is to PLOT the fitted lines for each group! Then you can see what the model is describing. You could even go a step further and apply the inverse logit to these lines to show the estimated probability for each group, versus X.
Answer: Showing both models is fairly common in some disciplines. In those disciplines showing only the model with the interactions can cause confusion, rather than the other way around. So I don't think your client is necessarily wrong.
Answer: The interaction means the effect to X in the response Y is different in the categories defined by the Group variable.
Sometime it is useful to do a stratified analysis, by Groups, where you analysis the effect of X in Y in each group. You should see the effects are different. You could present these stratified analysis and show the P-value of the interaction for justify the stratification.

Results with and without interaction


Chart JS add max value to legend

Question: I'm new in Chart JS and I'm trying to add the maximum values for each dataset inside the legend. I've tried using legendCallback :
HTML:
<canvas id="lineChart"></canvas>

Javascript:
var ctx = document.getElementById("lineChart");
    var lineChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['1','2','3','4','5','6','7','8','9','10'],
            datasets: [{
                label: "Max",
                backgroundColor: "rgba(235, 70, 70, 0.31)",
                borderColor: "rgba(231, 25, 25, 0.7)",
                pointBorderColor: "rgba(231, 25, 25, 0.7)",
                pointBackgroundColor: "rgba(231, 25, 25, 0.7)",
                pointHoverBackgroundColor: "#fff",
                pointHoverBorderColor: "rgba(220,220,220,1)",
                pointBorderWidth: 1,
                data: [31, 74, 6, 39, 20, 85, 7, 80, 35, 70]
            }, {
                label: "Avg",
                backgroundColor: "rgba(255, 255, 111, 0.3)",
                borderColor: "rgba(255, 255, 50, 0.70)",
                pointBorderColor: "rgba(255, 255, 50, 0.70)",
                pointBackgroundColor: "rgba(255, 255, 50, 0.70)",
                pointHoverBackgroundColor: "#fff",
                pointHoverBorderColor: "rgba(151,187,205,1)",
                pointBorderWidth: 1,
                data: [82, 23, 66, 9, 99, 4, 2, 25, 67, 20]
            },
            {
                label: "Min",
                backgroundColor: "rgba(90, 189, 90, 0.3)",
                borderColor: "rgba(50, 173, 50, 0.70)",
                pointBorderColor: "rgba(50, 173, 50, 0.70)",
                pointBackgroundColor: "rgba(50, 173, 50, 0.70)",
                pointHoverBackgroundColor: "#fff",
                pointHoverBorderColor: "rgba(151,187,205,1)",
                pointBorderWidth: 1,
                data: [30, 46, 60, 29, 79, 54, 23, 25, 47, 10]
            }]
        },
        options: {
            legend: {
                display: true,
                position: 'bottom'
            },
            legendCallback: function(chart) {
                return 'a';
            },
            scales: {
                xAxes: [{
                    gridLines: {
                        color: "rgba(0, 0, 0, 0)",
                    }
                }]
            }
        }
    });

but the displayed legend didn't changed. I've searched for some answers and I also tried using: lineChart.generateLegend(); but still no result.
It is possible to add the maximum value for each dataset inside legend?
Thanks in advance!
Answer: Yes, it is possible to show the max value for each dataset inside the legend.  You can use the legend.labels.generateLabels config property to do this.
This property allows you to define your own function that generates the legend labels.  To add the max, we simply iterate through each dataset's data array, find the max, and build it into the label string.
Here is an example configuration.  The magic happens when we set the text property in the return.
legend: {
  display: true,
  position: 'bottom',
  labels: {
    generateLabels: function(chart) {
      var data = chart.data;
      return Chart.helpers.isArray(data.datasets) ? data.datasets.map(function(dataset, i) {

        return {
          text: dataset.label + " (Max Value: " + Chart.helpers.max(dataset.data).toLocaleString() + ")",
          fillStyle: (!Chart.helpers.isArray(dataset.backgroundColor) ? dataset.backgroundColor : dataset.backgroundColor[0]),
          hidden: !chart.isDatasetVisible(i),
          lineCap: dataset.borderCapStyle,
          lineDash: dataset.borderDash,
          lineDashOffset: dataset.borderDashOffset,
          lineJoin: dataset.borderJoinStyle,
          lineWidth: dataset.borderWidth,
          strokeStyle: dataset.borderColor,
          pointStyle: dataset.pointStyle,

          // Below is extra data used for toggling the datasets
          datasetIndex: i
        };
      }, this) : [];
    },
  },
},

I also created a codepen to demonstrate this.
Comment: Awesome! Thanks a lot! :)

Chart JS add max value to legend


Third party library added via composer.json but how can I load it in a module now?

Question: I have set up a module in my Drupal 8 project to handle some tasks I need doing using AWS.
I added the awssdk (for PHP) to my composer.json and ran the composer update command successfully. the AWS SDK is now sitting nicely in my /vendor directory under the folder aws.
Composer entry
'aws/aws-sdk-php': '^3.0'

I cannot seem to get this to load within my custom module. I have tried referencing the SDK as follows at the top of my one Controllers (After the use keyword but before the class keyword)
require_once (\Drupal::root() . '/vendor/autoload.php');

The result of trying this gives me a blank white page with this error in the apache log:

PHP message: PHP Fatal error:  require_once(): Failed opening required '/home/dash/public_html/docroot/vendor/autoload.php' (include_path='.:/usr/share/php') in /home/dash/public_html/docroot/modules/custom/awsintegration/src/Controller/AwsiInstanceListController.php on line 9

Also tried using an absolute path as
require '/home/dash/public_html/vendor/autoload.php';

Result: Page loads no watchdog error but I get an apache php error as soon as I try reference one of the SDK classes:

PHP message: PHP Fatal error:  Class 'Drupal\awsintegration\Controller\Aws\Sdk' not found in /home/dash/public_html/docroot/modules/custom/awsintegration/src/Controller/AwsiInstanceListController.php on line 27

UPDATE
After Clive's suggestion in comments I removed the require calls. I then added some simple code that used AWS to try create a credentials provider, I simply get errors in the apache log about missing Class as per:

PHP Fatal error:  Class 'Drupal\awsintegration\Controller\Aws\S3\S3Client' not found in /home/dash/public_html/docroot/modules/custom/awsintegration/src/Controller/AwsiInstanceListController.php on line 21

My code is as follows:
namespace Drupal\awsintegration\Controller;

use Drupal\awsintegration\AwsInstances;
use Drupal\Core\Controller\ControllerBase;

use Aws\Credentials\CredentialProvider;
use Aws\S3\S3Client;

class AwsiInstanceListController extends ControllerBase {

    public function content() {

        $s3 = new Aws\S3\S3Client([
            'version'     => 'latest',
            'region'      => 'eu-west-2a',
            'credentials' => [
                'key'    => 'AbAbAbAbDcDcDc',
                'secret' => 'QwertyQweRty'
            ]
        ]);

        return array(
            '#type' => 'markup',
            '#markup' => $this->t('Hello, World!'),
        );
    }

}

Comment: Composer handles the autoloading, you should only need to `use Path\To\AWS\Namespace\Class` in your class/file
Comment: Nope, autoloading is a level or two above that. Composer does the thinking for you, you just need to have the correct `use` statements in your files
Comment: Probably not, PHPStorm is pretty epic at resolving class paths (unless it's in the middle of an index). You can see from [their docs](https://packagist.org/packages/aws/aws-sdk-php) that you just need `use Aws\S3\S3Client;` at the top of the file (the autoload require is redundant since Drupal/Symfony does that anyway otherwise nothing would work at all). Try `composer dump-autoload` as a last resort, but if you've required the AWS library, and it's been installed into /vendor, you've technically done everything you need to
Comment: Thanks for the reply Clive, is a libraries entry needed in one of my module YAML files ? e.g. *.libraries.yml or *.info.yml
Comment: Simply getting class no found error. I am sure the aws files exist, just unsure if composer is loading them or not. Also in PHPStorm its not autocompleting the path when typing in the use statement, but that might be due to PHPStorm and not the framework
Comment: Yea it is 'required' in the composer.json etc. Odd then that its not been picked up. Thanks Clive, I'll have to continue looking. I am at least closer.
Comment: Oddly, if I remove the S3Client namespace and code from above and change that out to use Ec2Client and make a call on that I get past the Class not found error, although I get a error about no credentials. So this seems to suggest it cant find the S3 Class specifically
Answer: You don't need to use require_once for autoload. It handles by the composer automatically. You should create a use statement in your php file.
As an example if you want to use a class s3 module of aws;
use Aws\S3\SomeClassName;

Comment: Curious, Clive in the comments above addresses this as you stated, but for some reason the sdk is not been picked up. Appreciated the info though.


Accessing Eval() from codebehind after DataBind

Question: I have a GridView where the ItemTemplates are just Eval("ColumnName"), how can I access this field after the data has been bound?
I tried gv.Rows[0].Cells[0] etc. but there is nothing there.
Is this because of late binding? or is it just because the Eval is not in a control?
Answer: You want to get the data in the event 'RowCommand' or 'RowDataBind'?
Comment: it doesn't matter to me, just as long as I can access it somehow
Answer: I worked it out:
<code>((DataBoundLiteralControl)gv.Rows[0].Cells[0].Controls[0]).Text
</code>


What is the correct way to instantiate c++11 random facilities

Question: After looking a various examples on the uses of the new 'random' facilities in C++, I'm left a little confused as to best practices - specifically related to lifetimes of various instances.
For instance in some examples the use of "random_device" is either static in a local scope like a function, or is a static global variable or is just plainly a local.
--- TU ---

static std::random_device global_source;

void foo()
{
   static std::random_device local_static_source;
   static std::mt19937 gen(local_static_source());
   std::uniform_int_distribution<> dist(0,10);
   ...
   dist(gen);
   ...
}

void boo()
{
   std::mt19937 gen(global_source());
   std::uniform_int_distribution<> dist(0,10);
   ...
   dist(gen);
   ...
}

void roo()
{
   std::random_device local_source;
   std::mt19937 gen(local_source());
   std::uniform_int_distribution<> dist(0,10);
   ...
   dist(gen);
   ...
}

int main()
{
   static std::mt19937 gen(global_source());
   std::uniform_int_distribution<> dist(0,10);
   ...
   dist(gen);
   ...
  return 0;
}

--- TU ---

Q1: If "foo" or "boo" can be accessed by multiple threads, is it ok to have the generator and source be static? - is there any kind of thread safety guarantees like those in shared_ptr?
Q2: Is there any wording in the standard that discusses assumptions and issues related to instantiation?
Comment: There are exactly the same thread safety guarantees as for `shared_ptr`: distinct objects are independent and can be freely accessed or modified concurrently; access to the same object must be properly synchronized. Neither `foo` nor `boo` are thread-safe (though it's OK for one thread to call `foo` while another calls `boo`). The standard provides general library-wide thread safety guarantees in 220.127.116.11; there's nothing specifically for random number generators.
Comment: Correction: `foo` and `boo` are not thread-safe assuming they actually call `dist(gen)` somewhere in the code hidden by ellipsis. As written, they are safe as they don't actually do anything.
Comment: @IgorTandetnik My apologies, I was under the assumption that it was clearly self evident, that the ellipsises would imply usage of the types - I've updated the question.
Comment: @IgorTandetnik Consider expanding your comments into an answer so Gerdiner can close this question as "answered".
Answer: Some background: the reasons for allowing multiple instances of random number generators are mainly thread safety (not burdening random number generator implementations with thread synchronization) and repeatability (allowing a sequence of numbers to be repeated using the same seed).

The former is pretty self-explanatory - there are valid cases for using RNGs in performance-critical code. With multiple instances possible, there is no expensive mutex required and random numbers can be generated on multiple CPU cores in parallel.
The latter is generally useful when generating data sets by random. As a common example, video games may recreate the same (random) game world by driving all decisions related to the creation of the game world from the same RNG (possibly even on different networked PCs).

So the best scope for a C++ RNG depends on what you're writing:
If you're writing a library that might be used in the context of the above to scenarios, it is probably a good idea to let the caller provide the RNG to the individual methods or classes:
// Can be used on multiple CPU cores in parallel or with seed values
template <typename TRandomNumberEngine>
Point2 GetRandomPointInRectangle(
  const Rectangle2 &rect, TRandomNumberEngine &random
) {
  std::uniform_real_distribution<float> horizontal(rect.Min.X, rect.Max.X);
  float x = horizontal(random);

  std::uniform_real_distribution<float> vertical(rect.Min.Y, rect.Max.Y);
  float y = vertical(random);

  return Point2(x, y);
}

If you're writing an application or a library that uses the RNG in a supporing role (eg. geometric fitting algorithms), ie. you're just interested in non-repeatable random numbers, the best scope for a random number generator would be the largest possible scope that doesn't introduce unwanted coupling between modules.
That could be a simple private object variable in whatever class needs random numbers or even a thread_local singleton providing the RNG of your choice if it has a lot of short-lived consumers that justify such complexity.

The distributions (like std::uniform_real_distribution) can be as short-lived as you want. They're plain functors where the constructor either has no arguments or only stores the arguments for when the functor gets executed.


Set a dynamic meta title on Node with MetaTag module installed

Question: I've got one specific node where I need to dynamically set the meta title. The logic to determine the correct title is too involved to express in tokens; I need to do it in code.
It seems that I should be able to override the title using the hook_preprocess_html; I get the current title, and replace it with the proper title.
After I set the title here though, the Metatag module (8.x-1.26) waltzes in, and replaces my meticulously assembled title by its own fairly generic pattern generated title.
I suppose I could try using the same hooks that Metatag uses to try to outsmart it, but that seems like a fragile approach.
Is there a better way, maybe through Metatag itself?
Comment: you can get hint from here: https://drupal.stackexchange.com/questions/317227/add-taxonomy-term-assignment-to-meta-tag/317241#317241 check this hook custom_module_metatags_alter mentioned here
Comment: @mini: turns out using this hook was making things unnecessarily hard for myself: why overwrite the rendered title, if I can just overwrite the token it's based on?
Answer: The best solution in my case turned out to be to simply override the value of the 'current-page:title' token. This is the token I used in my metatags pattern, and could be easily overriden in hook_tokens_alter.
Other solutions I tried which worked to some degree:

Using hook_metatags_alter to override the metatags
Hijacking the _title_callback on the entity.node.canonincal route


Do caution laps count in average speed?

Question: Often, when reporting the results of an automobile race, one will see a driver's average speed given.  Does this average speed include caution laps, or are they discounted for the purposes of determining time/distance?
Answer: The following race series use caution laps as a part of the average race speed
I know of no race series that does not include caution laps into the average speed of the overall race.  The series listed in particular do incorporate all track time for checkered flag (start) to checkered flag (finish) into the average race speed.

MotoGP
Formula 1
World Superbike
British Superbike
NASCAR
World Endurance Championship
Motocross Grand Prix
Supercross
British Touring Cars
Deutsche Tourenwagen Masters
Rolex Sports Car Series
IRL (Indy Racing League)
World Touring Car Championship
FIA GT1 World Championship
Answer: Under the FIA Formula One Official FAQs

Do the laps covered behind the safety car count?

Yes, all the laps covered behind the Safety Car count as part of the total distance of the race.
This is why the Monaco Grand Prix has a low average speed as there are many crashes requiring a safety car.
Comment: As an aside, I'd say that the number of slow corners and hairpins has a more to do with low average speed than crashes and safety cars. For example the [1998 Monaco Grand Prix](http://atlasf1.com/news/1999fiafaq.htm#q28) was the slowest of the season, despite there being no safety car deployed at that race.

Do caution laps count in average speed?


React-Bootstrap Dropdown with Input won't stay open

Question: I am using React-Bootstrap DropDown with an Input inside a MenuItem (otherwise the console yells at me Uncaught TypeError: Cannot read property 'focus' of undefined)
Okay so the drop down renders, and the input is inside a menu item (all is well) except when I click inside the input, the dropdown closes.
Here is my JSX
<Bootstrap.DropdownButton title={this.state.callIdTitle} id="callId">
  <Bootstrap.MenuItem eventKey='1'>
   <input ref="callIdInput" type='text' eventKey='2' placeholder='Enter Call ID' />
  </Bootstrap.MenuItem>
</Bootstrap.DropdownButton>

Any pointing in the right direction is very much appreciated, I have been trying to solve this all day.
Thank you.
Answer: I managed to get it working by having a custom onToggle for dropdown that does nothing if click comes from input element. I basically ended up with something like this:
So something like this:
var React = require('react');

var ReactBootstrap = require('react-bootstrap'),
    Dropdown = ReactBootstrap.Dropdown,
    DropdownToggle = Dropdown.Toggle,
    DropdownMenu = Dropdown.Menu,
    Input = ReactBootstrap.Input,
    MenuItem = ReactBootstrap.MenuItem;

module.exports = React.createClass({
  displayName: 'DropdownWithInput',

  setValue: function(e) {
    var value = e.target.value;

    this.setState({value: value});
  },

  onSelect: function(event, value) {
    this.setState({value: value});
  },

  inputWasClicked: function() {
    this._inputWasClicked = true;
  },

  onToggle: function(open) {
    if (this._inputWasClicked) {
      this._inputWasClicked = false;
      return;
    }
    this.setState({open: open});
  },

  render: function() {
    return (
        <Dropdown id={this.props.id} open={this.state.open} onToggle={this.onToggle}
                  className="btn-group-xs btn-group-default">
          <DropdownToggle bsStyle="default" bsSize="xs" className="dropdown-with-input dropdown-toggle">
            Dropdown with input
          </DropdownToggle>

          <DropdownMenu>
            <Input
                type="text"
                ref="inputElem"
                autoComplete="off"
                name={this.props.name}
                placeholder="Type something here"
                onSelect={this.inputWasClicked}
                onChange={this.setValue}
                />
            <MenuItem divider key={this.props.id + '-dropdown-input-divider'}/>
            <MenuItem eventKey={1} onSelect={this.onSelect}>One</MenuItem>
            <MenuItem eventKey={2} onSelect={this.onSelect}>Two</MenuItem>
            <MenuItem eventKey={3} onSelect={this.onSelect}>Three</MenuItem>
          </DropdownMenu>
        </Dropdown>
    );
  }

});

Hope this works for you as well.
Answer: This capability is a relatively new feature for React-Bootstrap. Checkout the newer Dropdown Customization docs: http://react-bootstrap.github.io/components.html#btn-dropdowns-custom The last example of that section includes a dropdown with an input. The dropdown trigger looks like a link there, but you can also customize that.
Comment: The link is broken, now(9.1.2023) it's:
https://react-bootstrap.netlify.app/components/dropdowns/#rb-docs-content
Answer: I found a solution to this issue that worked pretty well for me. Inside the dropdown menu I had a a text input (not inside of a MenuItem).
<input onSelect={e => e.stopPropagation()} ... />

Comment: Here is my code still not work
```
}/>

 e.stopPropagation()} />

```
Answer: After all day...this is what I came up with.
I hope there's a better way.
    <Bootstrap.DropdownButton onClick={this.setFocusToCallIdInput} title={this.state.callIdTitle}>
      <Bootstrap.MenuItem href="javascript:void(0);" eventKey='1'>
        <Bootstrap.Input onClick={this.dontCloseMeBro} ref="callIdInput" type='text' onChange={this.callIdInputSelected} placeholder='Enter Call ID' />
      </Bootstrap.MenuItem>
    </Bootstrap.DropdownButton>

setFocusToCallIdInput:function(e){
    console.log("Call Id clicked");
    React.findDOMNode(this.refs.callIdInput).focus();
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
},
dontCloseMeBro:function(e){
    console.log("menu item clicked");
    React.findDOMNode(this.refs.callIdInput).focus();
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
},

Comment: you are trying to hack in a function that MenuItem is not built for, bootstrap in general does not support this. You need to create a custom MenuItem for inputs.
Answer: This seems to be working for me.
<Dropdown id="my-dropdown">
  <Input
    type="text"
    bsRole="toggle"
    value={this.state.inputValue}
    onChange={this.onChange} />
  <Dropdown.Menu>
    <MenuItem key={1}>Item 1</MenuItem>
    <MenuItem key={2}>Item 2</MenuItem>
    <MenuItem key={3}>Item 3</MenuItem>
  </Dropdown.Menu>
</Dropdown>

Answer: This is an example of a reusable function component that will stay open unless you click away from it (i.e. it will stay open when you type in the input). This is also useful if you have a dropdown with checkboxes inside it etc.
const StayOpenDropdown = ({ children, ...rest }) => {
    const [show, setShow] = useState(false)
    const onToggle = (isOpen, e, metadata) => {
        setShow(isOpen || metadata.source === 'select')
    }
    return (
        <DropdownButton show={show} onToggle={onToggle} {...rest}>
            {children}
        </DropdownButton>
    )
}

const MyComponent = () => (
    <StayOpenDropdown title='Some Title' >
        <input type='text' placeholder='Enter Call ID' />
    </StayOpenDropdown>
)


A very simple look on limits

Question: Could we define limits of functions like this?
A function f(x) has no value in x0 because the denominator at x0 is 0. By applying limit we determine a fictive value for x0 which the function tends to have from both sides but can not . In order to do this we eliminate factors that make it impossible to calculate f(x0); meaning they make the denominator 0.
I know it's not simple as that but I wonder could this be the starting point for studying limits? It's first year college math course btw.
Thanks in advance
Comment: This definition is definitely *not* precise enough to use as the basis for a mathematical theory.
Comment: An example to explain what you are thinking helps readers understand better.
Answer: Sure, I think this is a fine way to calculate limits.  For example,
$$f(x)=\frac{x^2-1}{x-1}$$
And we want to take the limit $x\to1$:
$$\frac{x^2-1}{x-1}=\frac{(x-1)(x+1)}{x-1}=\frac{\require{cancel}\cancel{(x-1)}(x+1)}{\cancel{x-1}}=x+1$$
So that we have
$$\lim_{x\to1}f(x)=\lim_{x\to1}x+1=1+1=2$$
This is often seen as the 'algebraic' way to evaluating a limit, and the key is to remove whatever is keeping us from calculating the limit.
Comment: Thanks all I needed was a starting point to see what exactly I was dealing with.
Comment: @Onthespot No problem.  ;)

A very simple look on limits


How to sql-sync database between two remotes which share the same host?

Question: I've two remotes: @source and @destination.
I'm trying to transfer the database from dev to test environment by using sql-sync:
$ drush -vy sql-sync @source @destination

But at the end drush complains that:

The source and destination cannot both be remote.
rsync error: syntax or usage error (code 1) at main.c(1166) [Receiver=3.0.9]

Both remotes are on the same machine, but they're using different path.
I'm using latest drush 7.0-dev.
Is there any workaround?
Answer: Here is how drush sql-sync works between two remotes:

Logs into remote @destination via SSH and creates destination database if needed via sql-create.
Backs up database on @sourceby performing sql-dump on source unless told otherwise and saves it into drush-backups folder.
Logs into @destination remote via SSH and executes rsync to transfer database from Source to Destination.
Example: rsync @source:drush-backups/db.sql.gz @destination:/tmp/db.sql.gz

To make this work, you have to make sure that:

both local and remote drush have the same version (either 6.x or 7.x),
on Destination the @source alias should be accessible for drush,
rsync tool doesn't support two remotes, so only one may be remote.

Based on above it seems you can't use sql-sync drush command to transfer the database between two remotes in drush 7.x (see: #161).
As for workaround, first dump the database from your source onto your local and transfer back to the destination, in example:
drush @source sql-dump | drush @destination sql-cli

This should transfer the database between two remotes without sql-sync limitation.
Answer: Another option I use is to use drush ssh command to execute drush on the source :
drush @source ssh "drush sql-sync @self @destination"

Comment: This got drush 9 working for me. Also works:

`drush @dest ssh "drush sql-sync @source @self"`


Jenkins Sonar fails on Periodic Jobs but works on manually started jobs

Question: Im using Sonar with Sonar Runner and Jenkins.
Strange thing is that when i start the job manually everything works fine but on the periodic nightly builds it fails and says:
org.sonar.runner.RunnerException: No files matching pattern "java" in directory
So i understand that Sonar Runner cant find my source files. But why is that so? I mean when i start it manually Sonar is working fine and using source files. i didn't change anything.
Its the exact same job...
Comment: Sounds like Jenkins is running from a different directory. Are the java files located within the Jenkins project workspace?
Comment: Jenkins is downloading all java files in the project workspace folder in the Jenkins folder. Thats were im pointing at. Ok now I get the same error when i start it manually. Last week it worked.. didn't change anything... strange thing
Answer: If I generalize your question to "What should I do if my Jenkins job fails at random times after working other times?" one of the first steps I always do is delete the workspace and rerun the build.  You can also usually configure the SCM plugin to do a clean checkout of the source rather than an update.  That has solved issues for me in the past.
Comment: Sometimes actually deleting the workspace solves weird issues for me.  It is sort of like "reboot Windows" -- a catch-all solution.  But granted I don't have a specific reason to think it will solve your issue.


When I run the test " rspec item_container_spec.rb "In the console, I'll get a warning

Question:   it 'add items into the container' do
    item1 = Item.new('kettle', price: 200)
    item2 = Item.new('kettle', price: 300)
    @box.add_item(item1)
    @box.add_item(item2)
    @box.items.should have(2).items
  end

This team might mistake? " @box.items.should have(2).items  " .
In the console, I'll get a warning
**E:\work\storeapp\spec>rspec item_container_spec.rb
F

Failures:

  1) ItemContainer add items into the container
     Failure/Error: @box.items.should have(2).items
     NoMethodError:
       undefined method `have' for #<RSpec::ExampleGroups::ItemContainer:0x2419908>
     # ./item_container_spec.rb:27:in `block (2 levels) in <top (required)>'

Finished in 0 seconds (files took 0.23234 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./item_container_spec.rb:22 # ItemContainer add items into the container**

where is my mistake?
Answer: I bet that you have installed rspec 3.0.
The have family of matchers was deprecated in RSpec 2.99 and has been moved to a separate rspec-collection_matchers gem as of RSpec 3.0.
Take a look here.
Comment: I'm just learning and I do not really understand.
I want to remove my " rspec -v 3.2.2 " and install " RSpec 2.99.0.beta1 " ?
Comment: Change the version of rspec in your gemfile then run bundle install in your terminal.
Comment: I think it would better to update the test rather than use an old version of RSpec: `@box.items.size.should == 2`
Comment: @AndyWaite , I ran the test :  @box.items.size.should == 2 , and there was an error :

Deprecation Warnings:

Using `should` from rspec-expectations' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` with
`config.expect_with(:rspec) { |c| c.syntax = :should }` instead. Called from E:/work/storeapp/spec/item_container_spec.rb:27:in `block (2 levels) in '.
Comment: @Vitalik Andrysha : if you chose to keep rspec 3, then you will have to change your whole test. You should use expect().to instead of ().should. Look at the documentation of rspec.
Comment: @VitalikAndrysha in Ruby, a warning is not an error. The test should still have passed. But as @Chambeur suggests, you should use the newer `expect` syntax to avoid this happening.
Comment: @Chambeur how to replace the version I set earlier, and I installed version of rspec-3.2.0 ? ____________

E:\work\storeapp\spec>gem install rspec 2.14
Fetching: rspec-3.2.0.gem (100%)
Successfully installed rspec-3.2.0
Parsing documentation for rspec-3.2.0
Installing ri documentation for rspec-3.2.0
Done installing documentation for rspec after 0 seconds
ERROR:  Could not find a valid gem '2.14' (>= 0) in any repository
1 gem installed
Comment: @VitalikAndrysha maybe the version you're seeking is so deprecated that it's not available anymore. As AndyWaite said, try to upgrade your code instead of downgrade your stack. And if you plan to ask on SO everytime you have an error, you gonna have a bad time.

When I run the test “ rspec item_container_spec.rb ”In the console, I'll get a warning


Drupal and Domain

Question: I have a strange redirect if I access my Drupal installation without subdomain:
http://efg-zoar.de
leads to
http://www.efg-zoar.de/drupal7
and the "drupal7" is just wrong....
If I enter
www.efg-zoar.de
directly, everything works fine. I already asked my webspace provider for support, but these settings are completly fine. The Drupal installation was installed intially with an other domain. May this change cause this problem? And how can I fix this?
Thanks a lot!
Saduras
Edit:
I found some entries in the database table prefix_locales_source which has "/drupal7/install.php?profile=standard&locale=de" in the field 'location'.
Are these somehow related to my problem?
Comment: Did you check your A record for efg-zoar.de where is it pointing to? Did you change the .htaccess file at all?
Comment: The whole webspace is managed by Domainfactory and I can't set any IP configurations or A records. I just specified an path on the webspace for the domain and it's not possible to set a different path for the subdomain www (but for any other and they work perfect as well)
Answer: i think you have this:
www.domain.de in /bla/bla/drupal7

domain.de in /bla/bla/drupal7

you need:
www.domain.de in /bla/bla

domain.de in /bla/bla

redirect folder /bla/bla via .htaccess or php to /bla/bla/drupal7
Comment: I tried something like this with an html-meta redirect. It work's indeed, but then I have the ugly URL www.efg-zoar.de/drupal7 as base url. I would like to get rid of the "drupal7" instead...
Answer: When I acccess the URL http://efg-zoar.de/ in Firefox with the HttpFox extension installed, it shows this response header.
(Status-Line)   HTTP/1.1 301 Moved Permanently
Date    Thu, 02 May 2013 21:45:41 GMT
Server  Apache/2.2.22
Location    http://www.efg-zoar.de/drupal7/

This shows that you have Apache installed, and something is performing a server-side redirect. As an earlier post mentioned, this redirect might take place at different levels.
The web browser hits Apache first. Apache can store redirects in both the httpd.conf and .htaccess files. It sounds like you're hosting in a shared environment, so my bet would be the .htaccess file.
Apache then passes the request to PHP and Drupal. A four-line PHP file can perform the same redirect, as shown here. http://www.cyberciti.biz/faq/php-redirect/
I checked the headers when accessing the home page with the WWW prefix http://www.efg-zoar.de/. This shows the header X-Powered-By: PHP/5.3.10. This makes me suspect that http://efg-zoar.de/ is hitting plain Apache with no PHP or Drupal involved. Here's the header from http://www.efg-zoar.de/.
(Status-Line)   HTTP/1.1 200 OK
Date    Thu, 02 May 2013 22:02:30 GMT
Server  Apache/2.2.22
X-Powered-By    PHP/5.3.10
X-Generator Drupal 7 (http://drupal.org)

You should contact your web host and ask them how to change the Apache redirect in either the .htaccess or httpd.conf file. Sometimes web hosts allow you to FTP the .htaccess file, but you need to configure your FTP client to show hidden files (file names preceded by a period, like .htaccess).
Here's the HttpFox extension for Firefox. It's helpful for debugging these issue.
https://addons.mozilla.org/En-us/firefox/addon/httpfox/
Comment: Thanks, I found the problem.
A wrong .htaccess file (for joomla) caused this one.

Drupal and Domain


Activity instance still exists even after onDestroy() is called

Question: I pass a handler created on mainUI thread from Activity and passed to a thread which performs some network operation and when i obtain result i send the result back to the activity using the handler.
This approach had issue in memory leaks when i went through these links: Inner ClassHandler Memory Leak  Android Developers
So i had implemented WeakReference, and kept the activity instance using WeakReference. But i am still seeing Activity instance alive even after activity is destroyed.
I created a Handler inside activity and passed activity instance as weakreference to handler.
By the time my Handler responds with a message delivered to it after 10secs, Activity is destroyed. But the weak reference still has the Activity instance and i am seeing the Toast, after Activity is destroyed.
Is there some where my understanding wrong ? Can someone explain how to handle messages delivered to a handler,but the UI is not around ?
import java.lang.ref.WeakReference;

import android.os.Handler;
import android.os.Message;

public abstract class SingleParamHandler <T> extends Handler
{
private WeakReference<T> mActivityReference;

public SingleParamHandler(T activity) {
    mActivityReference = new WeakReference<T>(activity);
}

@Override
public void handleMessage(Message msg) {
    if (mActivityReference.get() == null) {
        return;
    }
    handleMessage(mActivityReference.get(), msg);
}

protected abstract void handleMessage(T activity, Message msg);

}

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.widget.Toast;

public class MainActivity extends Activity {

MyHandler<MainActivity> handler;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main1);
    handler = new MyHandler<MainActivity>(this);
    new Thread(new MyRunnable(handler)).start();
}

public void onDestroy() {
    super.onDestroy();
    System.out.println("######## Activity onDestroy() ###### ");
}

private class MyRunnable implements Runnable {
    private Handler mHandler;
    public MyRunnable(Handler handler) {
        mHandler = handler;
    }

    public void run() {
        try {
            Thread.sleep(10000);
            mHandler.sendMessage(Message.obtain(handler, 1));
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }
}

private static class MyHandler<T> extends SingleParamHandler<T> {

    public MyHandler(T activity) {
        super(activity);
    }

    @Override
    public void handleMessage(T act, Message msg) {
        if(msg.what == 1) {
            Toast.makeText((MainActivity)act, "Called after activity destroyed", Toast.LENGTH_LONG).show();;
        }
    }
}

}

Based on the response obtained, i am updating the answer here. You may do it in the way u liked. But this is one way.
Added the below function in SingleParamHandler
public void clear() {
    mActivityReference.clear();
}

And in Activity onDestroy()
public void onDestroy() {
    super.onDestroy();
    System.out.println("######## Activity onDestroy() ###### ");
    handler.clear();
}

Answer: You don't need a WeakReference here. The Handler can just contain a reference to the Activity. In activity's onDestroy() just call a method on MyHandler that sets the reference to the Activity to null. Check for null in handleMessage().
Another choice would be this: in activity's onDestroy() call a method that interrupts the sleeping thread so that it shuts down before sending the message.
Comment: The article you linked to covers a specific situation, and I don't agree with everything that is written there. The case that is covered is a "delayed message" posted to a `Handler`. The article describes a case where a message is posted to a `Handler` that will de delivered in 10 minutes. This message has a reference to the `Handler` and the `Handler` has a reference to the `Activity` and that implies that neither the `Handler` nor the `Activity` will be able to be removed by the garbage collector **while this message is still in the queue**.
Comment: The author goes on to say that this causes a _massive memory leak_. Actually, this only "leaks" memory for 10 minutes (until the message is delivered, at which point the garbage collector can then remove the message, the `Handler` and the `Activity`). Personally I wouldn't call this a **massive memory leak**, as it fixes itself in 10 minutes. In your case, as long as you clean up everything yourself (which you are doing in `onDestroy()`) there is no leak.
Comment: Thanks for the logic. May i know, what makes you say weakreference is not needed, becoz the link which i posted says Handler needs to be static and make weakreference to the activity or service and check before handling message ? is not that contradicts ? Your knowledge on this would be appreciated..!!
Comment: @Mani This suggestion goes in the same direction as mine (registering/unregistering Activities). I was only making fewer assumptions. David, I still think in this simple scenario, it would be easier if the Handler checks for `Activity.isDestroyed()` instead, because `onDestroy()` is not guaranteed to execute?
Comment: @Mani You _can_ use a weak reference, but you already discovered its downside, namely that it does _not_ tell you when the object really dies, and that's what you want to know (or so do I understand your question). So if you do _not_ use a weak reference but a regular one, and set that to _null_ at the exact point in time, you're telling _both_ the garbage collector _and_ your program logic when the object is dead.
Comment: @ClassStacker first of all, `isDestroyed()` is only available from API level 17, which means it won't work on most devices in the field; Second, `isDestroyed()` only returns `true` if the `onDestroy()` has already been called on the `Activity`, so that makes it useless in the case where `onDestroy()` hasn't been called by the Android framework; Thirdly, the only cases I have seen where `onDestroy()` is **not called** are when Android decides to kill off the process in order to reclaim resources. In that case, we don't care, because the `Activity`, `Handler` and everything else will be dead.
Comment: @ClassStacker Thanks for the response. The Activity.isDestroyed() api is available from only api version 17, which makes it less usable in lower version.But i would try setting the activity to null in onDestroy() and observe.
Comment: @DavidWasser Right. Then we're back at the usual attach/detach scheme.
Comment: @DavidWasser . Your explanation is awesome...!! Indeed both of you...!!
Answer: There's no guarantee that Android will really delete an object from memory if it's not required to do so. In other words, Activity objects can stay in memory even after onDestroy() has been called (if there's enough memory available). On the other hand, there's no guarantee that onDestroy() will be called if there's not enough memory; quite to the contrary, Android is allowed to kill your whole process after calling onPause() on your current Activity (depending on the Android version).
I think there's a better path to follow for your purpose. What you may want to do is attach, detach and possibly re-attach (e.g. on configuration changes) Activities to your Service. Don't hope for the garbage collector to do the work for you. Rather, make it explicitly.
Subclass Activity and override the lifecycle methods as well as startActivity() and startActivityForResult() to let your Service know who's in charge right now. Of course, that's only a best-effort approach since some callbacks aren't guaranteed, but that only matters in certain situations which aren't dangerous. For example, your Activity won't detach from your Service in onPause(), but it could get killed right afterwards. But either your Service runs in the same process, so it gets killed at the same time. Or it runs in a different process, but then Android will notice the broken connection and may or may not kill the service as well; if not, then all you need to do is implement it in a robust fashion to be able to deal with the connection loss.
Update
After reading your comment: You're right, I didn't address that specifically.

i am figuring out how to avoid messages being sent to a handler which is created in a activity which is destroyed

Given your code above, and assuming that you really just want to display Toasts with an Activity as long as it exists, the following approach should help.

If your Thread is supposed to serve more than one Activity, extend it such that Activities can register with the Thread after it is created. If your Thread just serves one Activity, pass the Activity reference along with the Handler reference upon your Thread's (Runnable's) construction.
Before your Thread sends the message via the Handler, check activity.isDestroyed(). If the Activity is not destroyed, send the message. If the Activity is destroyed, do not send the message.
Depending on whether your Thread should server more than one Activity, either exit it's Runnable's run() method or set it's Activity reference to null if it finds that the Activity has been destroyed.

This should fix your above code. However, if your scenario grows, other approaches may be more suitable.
Comment: Thanks for the resopnse. I understand that Activity instance wont be deleted becoz onDestroy() has been called. But i am figuring out how to avoid messages being sent to a handler which is created in a activity which is destroyed...!! I know handler is not tied to Activity, it is to main UI thread, but wondering how to handle this ?
Comment: @Mani Updated my answer, Hope it helps!


how to solve $3 - \cfrac{2}{3 - \cfrac {2}{3 - \cfrac {2}{3 - \cfrac {2}{...}}}}$

Question: $$A = 3 - \cfrac{2}{3 - \cfrac {2}{3 - \cfrac {2}{3 - \cfrac {2}{...}}}}$$
My answer is:
$$\begin{align}
&A = 3 - \frac {2}{A}\\
\implies &\frac {A^2-3A+2}{A}=0\\
\implies &A^2-3A+2=0\\
\implies &(A-1)\cdot(A-2)=0\\
\implies &A=1\;\text{ or }\; A=2
\end{align}$$
I should note that I'm not sure if the above answer is true. Because I expected just one answer for A (A is a numeric expression), but I found two, $1$ and $2$. This seems to be a paradox.
Comment: It remains to show that one of them is not possible.
Comment: Alternatively, compute the first continued fraction then the second. Remember this sequence must converge to "something".
Comment: @user2770287 I have no idea how to write such a computer program.
Comment: I meant the partial continued fraction. So you can do it by hand.
Comment: @user2770287 Have you tried?
Comment: Yes, I have. See Mose Wintner's solution below. Just compute the first few values of $a_n$
Comment: @user2770287 Thanks. See my comment after Mose Winter's solution.
Answer: This continued fraction is the limit of
the sequence $a_n=3-2/a_{n-1}$. Computing the first few terms shows that $2$ is the correct limit; if our initial term $a_1=3$ were different then the limit could be $1$.
Comment: Good idea!  This continued fraction could also be the limit of the sequence$a_{n-1}=3-2/a_{n}$.  The limit might then be 2.
Comment: can we use an initial start at 1? :-)
Comment: I guess yes because it IS the second solution (1)
Answer: Let us define two series. The first is
\begin{align}
a_1 &= 3 \\
a_2 &= 3 - \frac{2}{3} \\
a_3 &= 3 - \frac{2}{3 - \frac{2}{3}} \\
a_4 &= 3- \frac{2}{3 - \frac{2}{3 - \frac{2}{3}}} \\
&\vdots \\
a_{n+1} &= 3 - \frac{2}{a_n} \quad (*)
\end{align}
and
\begin{align}
b_1 &= 3 - 2 \\
b_2 &= 3 - \frac{2}{3-2} \\
b_3 &= 3 - \frac{2}{3 - \frac{2}{3-2}} \\
b_4 &= 3 - \frac{2}{3 - \frac{2}{3 - \frac{2}{3-2}}} \\
&\vdots \\
b_{n+1} &= 3 - \frac{2}{b_n} \quad (**) \\
\end{align}
Note: This is the same recurrence relation $(*)$ or $(**)$ but with different start value $a_1 = 3$ and $b_1 = 1$.
For convergence we need $a_{n+1} - a_{n} \to 0$ or $a_n \to a$.
This way (in case of convergence) equations $(*)$ and $(**)$ have a limit
$$
a = 3 - \frac{2}{a} \quad (\#)
$$
which has indeed the solutions $a = 1$ and $a = 2$.
However that means we could also try
$$
c_n = 3 - \frac{2}{c_{n+1}}
$$
or
$$
c_{n+1} = \frac{2}{3 - c_n} \quad (\#\#)
$$
because it has the limit form $(\#)$.
Note that equation $(\#\#)$ is quite different from equation $(*)$ (see image below).
And indeed this recurrence relation $(\#\#)$ works too. Using $c_1 = 1$ will give $c_n \to 1$, Using $c_1 = 2$ will give $c_n \to 2$. Using $c_1 = 1000$ will give $c_n \to 1$.
So why is this? Still two solutions and the start value decides the limit.
Here is an image:

The green graph is related to $(*)$:
$$
f(x) = 3-\frac{2}{x}
$$
the blue graph is related to $(\#\#)$:
$$
g(x) = \frac{2}{3-x}
$$
and the red graph is the identity function:
$$
\mbox{id}(x) = x
$$
We see that both $f$ and $g$ hit the identity at $x=1$ and $x=2$. Those points are fixed points of $f$ and $g$:
\begin{align}
x^* &= f(x^*) \\
x^* &= g(x^*)
\end{align}
And one could now try to apply the theory of fixed points, esp. properties of fixed point iterations.
\begin{align}
x_{n+1} &= f(x_n) \quad (\$) \\
x_{n+1} &= g(x_n)
\end{align}
The fixed point iteration of $f$ is like the the iteration of original continued fractions (compare $(\$)$ with $(*)$ or $(**)$).
The theory behind can now help with statements about convergence and the dependency of start values.
Comment: nice and complete solution!
Comment: One of my favorite solutions so far on this site.
Answer: Note that as we add more terms to the continued fraction, it oscillates between $1$ and slightly higher than $2$.
$$
\begin{align}
n&=1&
3&=3&
3-2&=1\\\\
n&=2&
3-\cfrac23&=\frac73&
3-\cfrac{2}{3-2}&=1\\\\
n&=3&
3-\cfrac{2}{3-\cfrac23}&=\frac{15}7&
3-\cfrac2{3-\cfrac2{3-2}}&=1\\\\
n&=4&
3-\cfrac2{3-\cfrac2{3-\cfrac23}}&=\frac{31}{15}&
3-\cfrac2{3-\cfrac2{3-\cfrac2{3-2}}}&=1\\\\
&&
3-\cfrac2{\cfrac{2^n-1}{2^{n-1}-1}}&=\frac{2^{n+1}-1}{2^n-1}&
3-\cfrac21&=1
\end{align}
$$
Therefore, the limit of the continued fractions with $2n-1$ twos and threes is
$$
\lim_{n\to\infty}\frac{2^{n+1}-1}{2^n-1}=2
$$
and the limit of the continued fractions with $2n$ twos and threes is
$$
\lim_{n\to\infty}1=1
$$
Therefore, one value represents the limit of an odd number of twos and threes and the other value represents the limit of an even number of twos and threes.
Comment: I have clarified what I was trying to say before to make it more explicit. If the reason for the downvote was something else, please let me know.
Comment: Brilliant answer!
Comment: @HarishChandraRajpoot: Thanks. I just wish the downvoter felt the same way ;-)
Answer: Your two solutions are correct. You can verify them as follows.
$$\color{blue}{1} = 3 - 2=3-\frac{2}{\color{\red}{1}}\tag{1}$$
Now replace the red 1 with the blue 1, which equals to the right hand side in (1).
$$\color{blue}{2} = 3 - 1=3-\frac{\color{cyan}{2}}{\color{\red}{2}}\tag{2}$$
Now replace the red 2 with the blue 2, which equals to the right hand side in (2).
I heard from the internet that this is one of the ways Ramanujan created some of his equalities.
Now 2 questions for you,
(1) what if you replace the cyan 2 with blue 2 and so on so forth?
(2) what if you replace the cyan 2 with blue 2 and then replace the red 2 with blue 2 and so on so forth?
Comment: If one write a computer program to solve it, at the end which result the program will output _one_ or _two_?


Active Directory 2003 Native mode vs Mixed Mode

Question: My company is switching the Active Directory schema from Mixed Mode to Native Mode.
Did anyone had any problems when doing this?. It is a one way process and I'm wondering if there are any impacts on the way apps will work with AD. (VB6 or .NET apps)
To give you an example of something that I think is under question mark: there is one old app that resolves users from AD using a linked server in SQL. Would this still work?
Appreciated,
Adrian
Answer: The only reason to have problems is if you have any old NT4 domain controllers.  If they're all gone, going native is advisable.
Answer: I haven't heard of any problems switching form mixed to native, especially not linked servers in SQL. That said, you need to test, test and then test some more...
Here's a quick rundown on the different AD modes:
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-22_11-5140371.html
Answer: It's a simple switch and has nothing to do with your applications.  Don't forget there is both a domain mode and a forest mode.
Read up here on the differences and what "advantages" come from W2k3 native modes:http://www.computerperformance.co.uk/w2k3/w2k3_mixedvnative.htm
Answer: The only reason it would be an issue is if you still had NT4 BDCs in place. If you don't have any NT4 BDCs, then switching to Native Mode will not affect your SQL Servers. Now, with that said, some folks expect to be able to use user principal name (UPN) format (user@domain), but SQL Server doesn't support that. It only supports the standard NetBIOS way of specifying the user (Domain\User). This is true through SQL Server 2008.
Answer: If you've got a multi-domain forest, ensure you have strict replication consistency enabled across all your DCs. The FFL upgrade can bring lingering objects out of the woodwork.
Thanks,
Brian Desmond
Active Directory MVP


When creating new view: "Base table or view not found" problem

Question: When creating a new view and then trying to save it, I get this error:
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal.views_display' doesn't exist: INSERT INTO {views_display} (vid, id, display_title, display_plugin, position, display_options) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => 11 [:db_insert_placeholder_1] => default [:db_insert_placeholder_2] => Master [:db_insert_placeholder_3] => default [:db_insert_placeholder_4] => 1 [:db_insert_placeholder_5] => a:12:{s:5:"query";a:2:{s:4:"type";s:11:"views_query";s:7:"options";a:0:{}}s:6:"access";a:1:{s:4:"type";s:4:"perm";}s:5:"cache";a:1:{s:4:"type";s:4:"none";}s:12:"exposed_form";a:1:{s:4:"type";s:5:"basic";}s:5:"pager";a:2:{s:4:"type";s:4:"full";s:7:"options";a:1:{s:14:"items_per_page";s:2:"10";}}s:12:"style_plugin";s:4:"list";s:10:"row_plugin";s:4:"node";s:6:"fields";a:1:{s:5:"title";a:8:{s:2:"id";s:5:"title";s:5:"table";s:4:"node";s:5:"field";s:5:"title";s:5:"label";s:0:"";s:5:"alter";a:8:{s:10:"alter_text";i:0;s:9:"make_link";i:0;s:8:"absolute";i:0;s:4:"trim";i:0;s:13:"word_boundary";i:0;s:8:"ellipsis";i:0;s:10:"strip_tags";i:0;s:4:"html";i:0;}s:10:"hide_empty";i:0;s:10:"empty_zero";i:0;s:12:"link_to_node";i:1;}}s:7:"filters";a:3:{s:6:"status";a:6:{s:5:"value";i:1;s:5:"table";s:4:"node";s:5:"field";s:6:"status";s:2:"id";s:6:"status";s:6:"expose";a:1:{s:8:"operator";b:0;}s:5:"group";i:1;}s:4:"type";a:4:{s:2:"id";s:4:"type";s:5:"table";s:4:"node";s:5:"field";s:4:"type";s:5:"value";a:1:{s:7:"teznews";s:7:"teznews";}}s:3:"tid";a:5:{s:2:"id";s:3:"tid";s:5:"table";s:14:"taxonomy_index";s:5:"field";s:3:"tid";s:5:"value";a:1:{i:0;s:1:"1";}s:10:"vocabulary";s:4:"tags";}}s:5:"sorts";a:1:{s:7:"created";a:4:{s:2:"id";s:7:"created";s:5:"table";s:4:"node";s:5:"field";s:7:"created";s:5:"order";s:4:"DESC";}}s:5:"title";s:11:"Latest News";s:11:"row_options";a:3:{s:10:"build_mode";s:4:"full";s:5:"links";b:1;s:8:"comments";b:0;}} ) in views_db_object->save_row() (line 2224 of D:\xampp\htdocs\drupal\sites\all\modules\views\includes\view.inc).
I have struggled with this for a while and have used SQL snippets to create tables which were previously 'missing'. I have also googled it extensively, without seeming to find an answer, and sure that someone will understand what the problem relates to immediately. This is the first time I have come up against it. This is a fresh install of drupal 7.22 and I have never experienced this problem previously whilst building drupal sites.
I have tried updating everything and wondered if there was some way to install a clean version of 'views' in core or if this related to another problem.
Any advice from a more skilled set of eyes would be invaluable.
Thanks
Ed
Answer: <code>'drupal.views_display' doesn't exist.
</code>
That pretty much sums up the problem. The table wasn't created in the initial setup of views. Without knowing more I can't tell you exactly what's going on but a couple of things you could try is to run update.php and check for the issue in the views queue. You may have a mysql issue as well that's not allowing the table to be created.
Good luck!
Comment: Thanks! I reinstalled drupal and did a new database and that fixed it. A shorter workaround as it happens.


Erro ao fazer update de imagem "Array to string conversion"

Question: Tenho um formulário onde são enviados informações para o banco de dados, todos são alterados corretamente, exceto a imagem que não é alterada.
ed_cons_.php
<?php
//inicia a conexao com o banco

include ("conexao.php");
?>

    <meta charset="utf-8">
    <title>Formulario</title>
    <link rel="stylesheet" href="../agoravai/css/estilo.css">

Inicio

Consulta

        <?php
 //recebe o codigo da pag de consulta
$iden = isset($_GET['iden'])?$_GET['iden']:"";

$iden = $_GET ['codigo'];

// consulta no banco de dados
$sql = "select * from eqp where codigo = '$iden'";
$consulta = mysqli_query($conexao,$sql);
$registros = mysqli_num_rows($consulta);
while($linhas = mysqli_fetch_array($consulta)){

//recebe os dados

$codigo = $linhas ['codigo'];
$arquivo = $linhas['arquivo'];

            echo ("

             <form method='post' enctype='multipart/form-data' action='salva_ed.php''>
            Codigo:	 <input type='text' name='codigo' value='"  .   $codigo . "'>

              Arquivo em anexo: <input type='file' class= 'anexo' name='arquivo'>

      <input type='submit' class='bnt salvar' value='Salvar'>

 ");

        }

        ?>

salva_ed.php
<?php
//inicia conexão com o banco
include ("conexao.php");
$new_name = "";

 // recebe o codigo do registro

$iden = isset($_POST['iden'])?$_POST['iden']:"";

$iden = $_POST ['codigo'];

$arquivo = isset($_FILES['arquivo'])?$_FILES['arquivo']:"";
$arquivo = $_FILES ['arquivo'];

// aqui seria onde ele veifica se existe algo no campo arquivo e o substitui por um valor em branco
if($arquivo == ""){
    $query =("update eqp set arquivo = '' WHERE codigo='$iden'");
}else{

// aqui seria onde fazia o update da imagem, dando um novo nome e movendo para a pasta de upload
 if(isset($_FILES['imagem']))
   {
      $sql =  mysqli_query("SELECT * FROM eqp WHERE codigo = '$iden' LIMIT 1");
      $resultado = mysql_fetch_assoc($result);

    date_default_timezone_set("Brazil/East"); //Definindo timezone padrão
    $ext = strtolower(substr($_FILES['imagem']['name'],-4)); //Pegando extensão do arquivo
    $new_name = $resultado['foto']; //Definindo um novo nome para o arquivo
    $dir = "upload/"; //Diretório para uploads

    move_uploaded_file($_FILES['imagem']['tmp_name'], $dir.$new_name); //Fazer upload do arquivo

   }
$new_name = $_FILES['arquivo'];
$imagem = $new_name;

var_dump($imagem);
echo '
';
print_r($imagem);
echo '
';
$query=("UPDATE eqp SET arquivo= '$imagem' WHERE codigo='$iden'");

  $result = mysqli_query($conexao,$query);

  // Verifica se o comando foi executado com sucesso
  if(!$result)
    echo "Registro NÃO alterado.";
  else
    echo "Registro Alterado com sucesso.";
}
?>

Erro que deu:
array(5) { ["name"]=> string(10) "images.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(24) "C:\xammp\tmp\phpE054.tmp" ["error"]=> int(0) ["size"]=> int(7225) }

Array
(
    [name] => images.jpg
    [type] => image/jpeg
    [tmp_name] => C:\xammp\tmp\phpE054.tmp
    [error] => 0
    [size] => 7225
)

Notice: Array to string conversion in C:\xammp\htdocs\agoravai\salva_ed.php on line 41
Registro Alterado com sucesso.

Tenho a função var_dump($imagem); que mostra que ele está recebendo a imagem, porém não altera no banco, o que pode estar ocasionando isso?
Comment: Se `$imagem` é um *array*, qual valor deveria ser a coluna `arquivo` quando você faz `arquivo= '$imagem'`? Pode uma coluna do banco receber um *array*?
Comment: olá Anderson, bom dia e obrigado pela atenção! não entendi muito bem a pergunta que você me fez haha mas vamos la, bom.. na minha ideia, $imagem receberia o name "arquivo" que esta vindo da minha pagina de consulta para a de edição, então a variavel $imagem recebe o valor da imagem que estou tentando enviar, e "arquivo='$imagem' seria para no caso ser adicionado a foto no meu banco de dados no campo arquivo, pois quando e mandado pelo meu formulario e adicionado normalmente mas quando edito não envia apenas apaga a imagem que ja tinha no banco
Answer: Quando você tenta concatenar a variável $imagem dentro da string do seu comando UPDATE não é possível porque $imagem é um array e não uma string.
Acredito que você esteja tentando pegar o nome da imagem. Nesse caso, em salva_ed.php, ao invés de $new_name = $_FILES['arquivo'];, pois $_FILES['arquivo'] é um array, pegue apenas o nome do arquivo que está dentro desse array. Assim:
$new_name = $_FILES['arquivo']["name"];

Pronto, agora $new_name é uma string que pode ser passada para $imagem e não deve mais dar problema de concatenação no seu comando UPDATE.
Comment: Opaaaa, Muito obrigado Denys, agora esta alterando certinho, porem a imagem não aparece quando eu faço uma busca no meu banco, como faço para exibir ela?
Comment: ´print "Anexo: ";´ uso esse comando para exibir a imagem na consulta, porem depois de alterada ela nao aparece nada.


ON/OFF toggle as a custom view field

Question: I have a table view output of node data. The node type has a list field called status.
Status is set to accept a single value. It has the following option to select from:
<code>Inactive
Active
Submitted
Approved
</code>
They work in pairs. When a node is created it's Inactive by default. Someone reviews it and sets it to Active. Upon further work it is set to Submitted and eventually someone else will set it to Approved.
What I am tasked with is creating a toggle button against each row of the table output
containing [Inactive|Active] or [Submitted|Approved] which a user can simply click on and change it's status rather than go to the actual nodes' edit page.
I'm interested in ideas on how I can accomplish this or perhaps if there is a module that fully or partially does this.
Answer: For Drupal 8 You have to use Toogle Editable Fields https://www.drupal.org/project/toggle_editable_fields
Answer: Try using the Editable Fields module. It let you edit any CCK field on node/view display page, and it changes field values on the fly using AJAX.
Answer: You can achieve that using the flag and rules modules.
Set a role named "moderator". Moderator users can flag the content as active. Then other role ("super moderator" for example) can flag the content as approved/ submitted.
Configure a rule to publish the content when it's flagged as approved.
You can also create views accessible only to specific roles where they can view the nodes flagged as inactive/ active/ submitted/ or approved.
In order to create a toggle button - try this tutorial - http://www.wdtutorials.com/2011/10/18/drupal-7-how-create-do-list-flag-module.
You can also try the Workflow module.

ON/OFF toggle as a custom view field