How to factor a polynomial quickly in $\mathbb{F}_5[x]$

Question: I was doing an exercise in Brzezinski's Galois Theory Through Exercises and needed to factor the polynomial
$x^6+5x^2+x+1=x^6+x+1$ in $\mathbb{F}_5[x]$. Is there a quick way to do this?
I can see it has no roots and therefore no linear factors, so it must either factor as the product of a quadratic and a quartic or two cubics, but listing the irreducible quadratics and cubics mod $5$ is laborious. I found all of the irreducible quadratics, which are \begin{multline}
x^2\pm 2, \, x^2+x+1, \, x^2+x+2, \, x^2+2x-2, \, x^2+2x-1, \\
x^2-2x+2, \, x^2-2x-2, \, x^2-x+1, x^2-x+2
\end{multline}
and checked that none of these are factors, so it must factor as the product of two cubics, which I know I could find either by finding all irreducible cubics or by writing
$$
x^6+x+1 = (x^3+ax^2+bx+c)(x^3+dx^2+ex+f)
$$
and then equating coefficients.
I used a computer to perform the Berlekamp algorithm which yielded the factorisation
$$
x^6+5x^2+x+1 = (x^3-2x^2-1)(x^3+2x^2-x-1)
$$
but it would take me a very long time to do this by hand. Can anyone suggest any tricks that could be applied here?
Comment: this is something really special about your polynomial: its roots satisfy $a^5=f(a):=-1-1/a$ and you can notice that $f(f(f(t)))=t$ and so every root of your polynomial gives (at most) a cubic extension
Comment: I am not really convinced that applying "tricks" is so desirable. If it is a homework, I wouldn't be concerned to use the known list of cubic polynomials. For certain polynomials, you can apply a "trick", but in general it is not possible.
Comment: It is not so difficult to compute the irreducible cubic polynomials over $\Bbb F_5$ by hand (because you only need to find a root or see that there is none). Then you can easily multiply those to see if you can get $x^6+5x^2+x+1$.
Comment: @DietrichBurde Thanks for your comment. Aren't there rather a lot of irreducible monic cubics over $\mathbb{F}_5$? If I write the polynomial as $x^3+ax^2+bx+c$, $c\neq0$, there are $5\cdot5\cdot4=100$ possibilities to check.
Comment: There are $p(p-1)$ monic irreducible cubics over $\Bbb F_p$, see [here](https://math.stackexchange.com/questions/3280530/number-of-irreducible-monic-polynomials-of-degree-3-over-bbb-f-p-p-prime?noredirect=1&lq=1). So yes, we have $20$ of them for $p=5$, but they are already known. So you don't have to work for it. Finally, why not use a computer? Berlekamp is great! If you are required for an exam to do it by hand, then you will have a very special polynomial, where you don't have to compute too much.
Comment: @DietrichBurde That's useful to know, but the exercise is intended to be done by hand. The book has separate exercises to be done with a computer.
Answer: The observation made by user8268 is the key to the following paper and pencil factorization. Not ruling out the existence of other possibilities — that trick simply works like charm.

Let $\alpha$ be a root of $p(x)=x^6+x+1$ in some extension field of $\Bbb{F}_5$. By Galois theory it follows that
$$
\alpha^5=\frac{\alpha^6}{\alpha}=-\frac{\alpha+1}{\alpha}=-1-1/\alpha
$$
is another root. The projective linear trasformation (aka a Möbius transformation)
$$f(t)=-1-1/t$$
is "famous" for having order three. Meaning that its third iterate is the identity:
$f(f(f(t)))=t$. It follows that the Frobenius automorphism $\alpha\mapsto \alpha^5$ cycles back to $\alpha$ after three rounds. Therefore the minimum polynomial of $\alpha$ is (a factor of)
$$
m(x)=(x-\alpha)(x-f(\alpha))(x-f(f(\alpha)))=(x-\alpha)(x+1+\frac1\alpha)(x+\frac1{1+\alpha}).
$$
Here I used the fact that $f(f(t))=-1/(1+t)$.
Expanding $m(x)$ gives
$$
m(x)=x^3+Ax^2+Bx-1,
$$
where $A=(1+3\alpha-\alpha^3)/(\alpha+\alpha^2)$ and $B=(1-3\alpha^2-\alpha^3)/(\alpha+\alpha^2).$
How does this help the factorization? The key is that, upon inspection, we see that $A-B=3$. This narrows down the family of putative factors to those of the form
$$
x^3+Ax^2+(A-3)x-1.
$$
All of the above, together with the OPs observation that the polynomial has no roots in $\Bbb{F}_5$, implies that we are looking for a factorization of the form
$$
x^6+x+1=(x^3+Ax^2+(A-3)x-1)(x^3+Cx^2+(C-3)x-1)\qquad(*)
$$
with $A,C\in\Bbb{F}_5$. Looking at the terms of degree five (or the linear terms) on the R.H.S. of $(*)$ tells us that $A+C=0$, so $C=-A$. Expanding further, and looking at the quadratic terms we get the equation
$$
0=-A+(A-3)(C-3)-C=AC-4(A+C)+9=AC-1=-A^2-1.
$$
This has two solutions $A=\pm2$ in $\Bbb{F}_5$. It is straight forward to check that this gives the desired factorization.

The same observation allows us to factor for example $g(x)=x^8+x+1$ in $\Bbb{F}_7[x]$. Testing shows that $g(2)=0=g(4)$. The above process, this time starting from $\alpha^7=f(\alpha)$, leads to a full factorization
$$g(x)=(x-2)(x-4)(x^3-3x-1)(x^3-x^2+3x-1).$$
We see the same difference of three in the coefficients of the quadratic and linear terms of the two cubic factors.
See this older question and its answers for an earlier incarnation of this projective linear transformation in this context. There was no need to identify the cubic factors there. I only posted this because I had never noticed that difference of three. Undoubtedly that is a known fact given that this particular Möbius transformation appears regularly.
Comment: Galois theory of rational function fields does imply that the coefficients of $m(x)\in F(\alpha)[x]$, in the case where $\alpha$ is transcendental over a base field $F$, belong to a subfield $K\subset F(\alpha)$ such that $F(\alpha)/K$ is a cyclic Galois extension. By Lüroth we know that $K=F(\beta)$ for some $\beta$ (also transcendental over $F$). Thus it was obvious that there would be relation between the coefficients of $m(x)$. I don't recall ever realizing exactly how simple the relation is :-)
Comment: So two of the irreducible cubics factor $x^5=f(x)$, and the other two $x^5 = f\circ f(x)$ ?   I think I understood the solution, and it is lovely!
Comment: +1 for a beautiful solution (and also because of being glad that my little observation could be used to actually solve the problem :)
Comment: @user8268 Thanks. I feel a bit bad for stealing your well deserved starring role. I wasn't sure whether you want to post something about this, and decided to do it in the end. I have been criticized for posting "answers in the comments".
Comment: no worries in this case; answering in the comments is certainly criminal, but this time I just suggested where one might look
Answer: My approach is almost certainly not what the author had in mind, but this technique seems quite effective:
If $\alpha$ is a root of a cubic factor in some extension, then by Vieta the constant term of the cubic factor is $- \alpha \cdot \alpha^5 \cdot \alpha^{25} = -\alpha^{31}.$
So compute $x^{31}$ modulo $x^6+x+1$ in $\mathbb{F}_5[x]$:
$$\begin{align*}
x^6 &\equiv -x - 1\\
x^{30} &\equiv -x^5 -1 \\
x^{31} &\equiv -x^6 - x \\
&\equiv 1,
\end{align*}$$
This means $-\alpha^{31} = -1$ for every root $\alpha$ of $x^6+x+1$, so both cubic factors have constant term $-1$. (This computation also rules out the possibility of quadratic or linear factors: all such factors divide $x^{25}-x$, and only $x-1$ divides both $x^{25}-x$ and $x^{31}-1$.)
So each cubic factor looks like $x^3 + xL(x) -1$, where $L(x)$ is a degree $1$ polynomial in $\mathbb{F}_5[x]$.
This means we are looking for linear polynomials $L_1(x)$ and $L_2(x)$ such that
$$
\begin{align*}
x^6 + x + 1 &= (x^3 + x\,L_1(x) - 1)\cdot (x^3 + x\,L_2(x)-1) \\
&= (x^3-1)^2 + x(x^3-1)\cdot(L_1(x)+L_2(x)) + x^2\cdot L_1(x)L_2(x).
\end{align*}
$$
It's worth noting that a decomposition of the form
$$ (x^3-1)^2 + x(x^3-1)\cdot \text{ linear } + x^2 \cdot \text{ quadratic }$$
is unique, as the linear term can be determined from the $x^5$ and $x^1$ coefficients, and then the quadratic factor can be solved for. Here we have
$$x^6 + x + 1 = (x^3-1)^2 + x(x^3-1)\cdot (-1) + x^2\cdot(x^2+2x)$$
so
$$
\begin{align*}
L_1(x) + L_2(x) &= -1 \\
L_1(x) \cdot L_2(x) &= x^2 + 2x
\end{align*}
$$
and we can use (for example) the quadratic formula to find $L_1$ and $L_2$:
$$
\begin{align*}
L_1(x), \; L_2(x) &= \frac{-1 \pm \sqrt{-4x^2-8x+1}}{2} \\
&= \frac{-1\pm\sqrt{x^2+2x+1}}{2} \qquad \text{ (reminder: coefficients are in $\mathbb{F}_5$)} \\
&= -2x, \; 2x-1.
\end{align*}
$$
So $x^6+x+1 = (x^3-2x^2-1)(x^3+2x^2-x-1)$ in $\mathbb{F}_5[x]$.


Validate a Markov Chain with few states (model switching)

Question: Suppose I have a five state Markov chain. The states are observable (in fact I defined them, they are outcomes of an classification algorithm). So I have a long time series, see the first picture.
The states correspond to a real stochastic situation, it represents the environment for a car driver, e.g., the highway, motorway, city etc. The data comes from several independent drivers and I think this should be "purely" stochastic, so I can't use any regression method, correct? So I chose the (time discrete) Markov chains. My goal is to create a model-switching Markov chain.
In each state there is another "model" to predict the speed of the car. The prediction is done via sampling from the speed distribution which has different parameters for each Markov-chain state.
I've read about hidden Markov chains with autoregressive models, but here I don't have hidden states.

Now I try to estimate the transfer-probability matrices via a maximum-likelihood estimation. The TPM for example is
<code>0.85393     0.033708     0.078652     0.033708            0
0.11111      0.66667      0.11111     0.055556     0.055556
    0.2          0.1      0.66667     0.033333            0
0.11905            0      0.02381      0.83333      0.02381
      0            0            0          0.5          0.5
</code>
I calculate the realization, according to Handbook of MCM, chapter 3 and two possible timeseries are:

Fine, does not really look like the original time series. Sure, it's stochastic. So, how do I prove, that these series represent the real time series? I think that looking at the time series is not sufficient. If I had many states, I would go for a histogram. I tried the autocorrelation function to see, if there are dependencies, but I'm not sure, if there are ways to validate my Markov Chain with the auto- or crosscorrelation function.
Or is the only possibility to use the states and predict the vehicle speed and validate it via MSE or similar? But again there is the problem, that it is not a "real" time series, since it is stochastic.
Answer: What you have to verify is your model, not your time series (though sample time series from your model can be used for this).

For example, you are assuming that your data is described by a first-order Markov chain, i.e., the probability of observing a given state only depends on the past state or, with other words, the process has a memory of 1. You can substantiate this assumption by showing that the process does not have a longer memory.
As an example, consider a Markov chain with only two states, called A and B. Let's say that you have counted the subchains of length 3 with A in the middle and got:

A→A→A: 723 times
A→A→B: 387 times
B→A→A: 233 times
B→A→B: 130 times

If the Markov chain is of order 1, the proportions of subchains ending with A should not depend on whether the chain started with A or B. This is a general statistical task, which is often represented in form of a contingency table. The corresponding contigency table for this case would be:
<code>               prior state
                 A    B   total
––––––––––––––––––––––––––––––––
next state A |  723  233   956
next state B |  387  130   517
total        | 1110  363  1473
</code>
This can, e.g., be tested with Fisher's exact test, which for this data should yield that the next state and the prior state are independent and thus the state A in our example Markov chain does not preserve any memory of the preceding state (state B hower might do this, so we have to test it as well).
As you have six states, you would have to perform six such tests with 6×6 contingency tables. Be aware that this is multiple testing. Also, in theory your data can pass this test but have an even longer memory, but given your data, I consider this unlikely.

Another way would be comparing some statistical properties of your original data with your simulated ones (which should be the same), for example the distribution of state durations or waiting times between two instances of a state. Should these differ, there is something wrong about your model. (However, your model can still be wrong if the distributions comply.)
Of course you could go one step further and use your model to get a simulated time series of vehicle speeds and compare appropriate properties such as the autocorrelation or the frequency content (FFT) with your original data. Being stochastic makes the results somewhat different from those for regular time series, but they are still meaningful and should be comparable if your model is good.
Either way, the more independent properties you can reproduce, the better – but you will there may always be aspects your model fails to reproduce despite complying to the original data in many aspects. Be also careful that you do not use aspects for verification that your model fulfills by construction. For example the histogram for the individual Markov-chain states of your model will always comply with the one for the original data, as it's determined by the transition rates.

Finally keep in mind that no model is perfect and that it may still be good for what you are doing despite failing to comply with the original data. For example if there is some low frequency content in your original data but your model fails to reproduce this, this may be alright, if what is important for your application happens on much smaller time scales.
Comment: Okay thank you, I'll look into that. One last question: How can i formulate mathematically correct, what I am testing? I.e. I'm creating a contingency table for each state and use the fisher's test and see, if the null hypothesis, that the conditional probabilities are independent can be rejected. How to formulate that? Thank you!
Comment: Incredible, thank you very much! That was an answer in last minute ;) Do you have literature I could cite?
Comment: @user8648: Literature on what? (Be prepared for a negative answer, however.)
Comment: Literature on the whole model checking/verification thing (is this the same?) For example I've read this book http://mitpress.mit.edu/books/principles-model-checking , but it's something different here. Which statistical properties can I check, the "default" ones (mean, variance, i-th moment etc)? Is there a theoretical legitimation, that I can use the frequency distributions? I guess prediction length and the number of parallel Simulations do matter (or is that the same, since it is memoryless?) Thank you!
Comment: @user8648: I cannot help you there (the book you linked sounds like being about modelling something quite different), but it is very straightforward: You make assumptions – you try to verify them. Or: You want to reproduce the general behaviour of your data – you show that you do. I added a paragraph regarding what properties to use for verification, but in general use whatever properties you want – if your model is perfect, they should all comply (if it isn't, then you need to decide what is important).
Comment: The number of simulations does matter, but if you properly use a test, the significance levels account for how much data you have. Regarding the number of simulations, you are on the safe side, if you reproduce the lengths of your original data, as you will reproduce potential finite-size effects this way.
Comment: I would strongly suggest that you perform the contingency test first and regard the other tests as sanity check. I have no literature regarding this either, but I might a question about it.
Comment: Thank you! So the contingency table test is testing for the hypothesis, that the model has markov order 1, correct? I'm not sure how to do it, but I will try.

Another question is: Why could I use the distribution of the state durations? Aren't they also implicitly defined by the transitions? Or do you mean the distribution of all states, so just count the lengths of the state duration in every state and make a histogram?
What additional statistical properties are coming in your mind, too?

Thank you very much!
Comment: It's me again. I tested your matrix from above with http://www.mathworks.com/matlabcentral/fileexchange/26883-myfisher . The p-value is 0.75, so it should be independent. Where did you get these values from?

But I tried to to this on my data, the p value is very low, about 1e-20. I used `table = full(sparse(data(1:end-2),data(3:end),1))` in matlab to produce the 2 step table. Is that correct? I tried higher "orders", up to 40, but the p value stays low. Is there anything wrong in my procedure, or is the data still dependent? Thanks
Comment: @user8648: I meant the state-wise distribution of the durations. It would only be implicitly defined by the (first-order) transitions, if your data is generated by a first-order Markov chain. The values from the example were made up knowing that 387/723 ≈ 130/233. I cannot tell you anything about Matlab but I would strongly recommend not to apply any method/program that you do not understand sufficiently to verify the results yourself (however, I would guess that there is no program that can deal with 6⁴⁰ contingency tables as it cannot be stored in explicit form on any computer.
Comment: Anyway, if you applied everything correctly, your *p* value tells you that your assumption of Markovicity is wrong. *How* wrong it is depends on the amount of data (look at the test statistics instead – but you have to learn how to interprete that) and whether that is a problem depends on your application, so you have to decide that yourself.


Expected height of a randomly growing tree

Question: Q: We have a tree node with probability 0.5 to produce a left branch, 0.5 to produce a right branch (independent events), with each branch acting as an own sub-tree, what is the expected height of the tree?
My thought process is as follows: for starting node and each child node, there's equal probability of  0.25 for 4 events: having left but no right branch (LR'), having right but no left branch (L'R), having no branch (L'R'),and having both branches (LR).
Thus, if X = height of the tree, then
$$
\begin{aligned}
E[X] &= E[X|LR']*P(LR') + E[X|L'R]*P(L'R)+E[X|L'R']*P(L'R')+E[X|LR]*P(LR)\\
     &= (1+E[X])/4 + (1+E[X])/4 + 0 + ???
\end{aligned}
$$
I'm stuck at $E[X|LR]$, the expected height given we have a left and right branch. Maybe I should be using the max function here? Or is it still just $(1+E[X])$?
Answer: Your process is a critical branching process (the expected number of offsprings is $1$), and you are asking for its expected extinction time. The expected extinction time of a critical branching process is infinite. See for example Problem 4 in these lecture notes.
Comment: I am pretty sure it is not his case. I think it is not well described but think that it is a 2 stage choice, chose the leaf and then chose left or right. For N choices there is a finite maximum length (N) and a minimum length (log2(N)) hence there is a mean length.
Comment: Ah i see.  I'm still wrapping my head around the fact that the expected extinction time is infinite even though the probability of extinction time is actually 1. Thank you!
Comment: This is similar to a random walk on the integer line — you return to the origin with probability $1$, but the expected return time is infinite.


Very ample line bundle and the induced embedding

Question: Over $\mathbb C$, let $X$ be a projective variety and let $\mathcal L$ be a very ample line bundle. Then there is an induced embedding $X\to \mathbb P(V)$ for $V=H^0(X;\mathcal L)^*$.
It is easy to see there is a surjection  $\Gamma(\mathcal O(1))\to\Gamma(\mathcal L)$. I wonder if this is also true for $\mathcal O(n)$ and $\mathcal L^n$ in general.
Or equivalently can people find a counterexample of a projective variety with a very ample line bundle such that $\bigoplus H^0(X;L^n)$ is not generated by degree one elements?
Answer: If $X$ is normal, the condition that $H^0(\Bbb P^n,\mathcal{O}(d))\to H^0(X,\mathcal{O}_X(d))$ is surjective for all $d\geq 0$ is equivalent to $X\subset\Bbb P^n$ being projectively normal. (The condition that $\Gamma(\mathcal{O}(1))\to\Gamma(\mathcal{L})$ is surjective is called being linearly normal.) There's essentially no reason for a linearly normal variety to be projectively normal. For instance, here's an example from MO by user abx:

Here is a concrete example : take a curve $C$ of genus 4 and a line bundle $L$ on $C$ of degree 7 which is very ample (that means that $L$ is not of the form $K_C(p+q-r)$ for $p,q,r\in C$). Then  $L$ embeds $C$ in $\mathbb{P}^3$,  $\dim H^0(\mathbb{P}^3,\mathcal{O}_{\mathbb{P}^3}(2))=10$ and $\dim H^0(C,L^2)= 11$, so the above map cannot be surjective.


Find which entry occurs maximum number of time in Mysql

Question: I have a table T like this :
ID | brand
2 | 100
2 | 300
2 | 300
1 | 100
1 | 200

I want to find which ID,brand combination occur more than 50% for an ID. For ex : here the result should come as
ID | brand
2 | 300

as (2,300) occurs 2 out of 3 times in ID 2. In ID1, both combinations are 50% times so no row for ID 1.
Now I approached it like this:
First I found count of each ID,brand combination :
(select id,brand,count(*) c from T group by id,brand) as F

Then I list all IDs which satisfy above mentioned criteria
select ID from F group by ID having max(c)/count(*) > 0.5

It works perfectly, but the problem is I can't get corresponding brand because when in above query, I give
select ID, brand ...

Then it always gives first brand of the table.
Here is the sql fiddle
Answer: Here's my first attemp.
SELECT ID, BRAND
FROM
(
  SELECT t.ID, t.BRAND, s.TotalCount,
          COUNT(*) * 1.0 / s.TotalCount Percentage
  FROM   T
         INNER JOIN
        (
          SELECT ID, COUNT(*) totalCOunt
          FROM   T
          GROUP  BY ID
        ) s ON T.ID = s.ID
  GROUP  BY ID, BRAND
  HAVING (COUNT(*) * 1.0 / s.TotalCount) > 0.5
) r

SQLFiddle Demo
SQLFiddle Demo
Comment: because the value of each is 50%, you want greater than 50% right?
Comment: maybe you want this, http://www.sqlfiddle.com/#!2/5ce9b/5 OR http://www.sqlfiddle.com/#!2/5ce9b/6


Posso escrever em JavaScript dentro de PHP?

Question: Posso escrever em php a tag html usando echo?
Se eu fizer por exemplo echo("");
Este é o meu código mas o JS não funciona:
$color = "red";
echo("

 <button onclick='change_background('".$color."')'>$color</button>

");

Por bem decidi postar as minhas perguntas semelhantes
Posso fazer o JavaScript escrever PHP?
Posso escrever o ajax e javascript juntos?
Comment: Pode sim, estás tendo algum erro com isso?
Comment: O javascript não funciona eu devo ter algo errado então
Comment: Eu não acho isso uma boa idéia. Mas dá pra fazer uma coisinha legal usando ob_start
Comment: Peço que você considere a minha resposta como um exemplo para melhorar essas práticas. Creio que a resposta do @bigown já foi esclarecedora pra você.
Answer: JavaScript como texto
Se a sua dúvida é saber se pode criar um texto que contém um código JS que será inserido junto com o texto HTML que está gerando com o PHP. Sim, pode.
O que o PHP faz é apenas isto, gerar um texto "linguição" que será enviado para o servidor HTTP que enviará para o navegador ou quem tenha pedido. Pode ser até que não seja uma página HTML que esteja fazendo. Entenda o código PHP como um grande processador de texto.
Claro que ele pode fazer muito mais que isto, mas na forma como ele costuma ser usado o resultado final sempre será o texto que pode conter qualquer coisa que você quiser, pode ter HTML, JS, CSS, JSON, texto comum sem formatação, ou outro formato qualquer. Na verdade nem precisa ser texto, este é o tipo de dado gerado para saída mais comum. Se o texto tem algo errado dentro dele, não é problema do PHP.
Pode parecer confuso porque é o código de uma linguagem dentro do código de outra linguagem. Estes códigos não tem relação entre si. Eles não "conversam", até porque o código do JS não é executado pelo PHP, pra ele isto é apenas um texto qualquer, só você sabe que aquilo é JS. Quando está programado pense no código PHP de forma independente do JS. O problema de um não é problema do outro.
O echo é justamente para isto, tudo o que você "imprime" no PHP será enviado para o servidor HTTP. Pelo menos esta é a forma mais comum de usar o PHP (é possível usar de outras formas, mas a maioria dos programadores não sabem fazer isto e nem sabem que é possível). Obviamente que onde colocar este echo no código é importante para atingir o resultado esperado.
Já tentou ver no navegador o resultado de um página gerada com PHP? Faça experimentos tentando enviar de formas diferentes e sempre que tiver dúvidas específicas, poste aqui dando o máximo de detalhes possível do que está fazendo e qual o problema.
JavaScript executando
Se quer saber se pode inserir este código JS dentro do próprio código PHP e executar nele mesmo, aí a resposta é não, não pode fazer isto, são linguagens distintas. Até pode existir alguma forma de chamar um mecanismo que execute o JS externamente, mas é algo que ninguém faz e é algo esquisito mesmo. Não vejo motivos para fazer isto.
Problema específico
Note que o ideal é que você não tenha código JS inserido dentro de uma página HTML. Seria melhor ter todo código JS em um arquivo separado, e de preferência que este arquivo fosse estático, ou seja, que fosse fixo e não gerado na hora.
Gerar código JS dinamicamente via PHP geralmente faz pouco sentido na maioria das vezes. Inserir ele dentro do JS também não costuma ser necessário, embora possa ser usado sem problemas.
Após a edição da pergunta vejo que o código está fazendo o que deseja, ou não? Colocou ele para executar? Ele apareceu no navegador? É isto. Claro que este código pressupõe que exitam outras partes HTML ou mesmo JS na mesma página ou arquivo adicional.
Mas eu tenho minhas dúvidas se precisa gerar todo este código JS em PHP. Eu acho que dá para deixar o JS separado e configurar para ele manipular a cor por parâmetro e só a cor ser inserida na chamada deste código. Precisa ver um contexto maior. Mas reforço o que disse antes, em geral não tem porque gerar códigos JS pelo PHP.
Se o JS não está gerado ok e não funciona, o problema é outro do descrito na pergunta, então deve abrir outra pergunta com o problema específico dele. Poste o resto do código da página nesta nova pergunta. Acredito não ser necessário nada do PHP, até porque nem nesta foi colocado efetivamente.
Coloquei no GitHub para referência futura.
Comment: Obrigado esclareceu minha duvida eu sabia que html conseguia colocar dentro do php mas não sabia que ainda conseguiria coloca javascript dentro.
Comment: Note que no fundo você está colocando HTML que por acaso dentro dele tem JS. Mas poderia por JS puro também.
Comment: estou ainda aprender então estou experimentar é o melhor caminho
Comment: Muito bem esclarecido, gostaria de adicionar a informação que  muitas vezes o arquivo JS fica como cache, ou seja, mesmo que sofra uma atualização dinâmica pelo Php, quem acessa o site continua tendo acesso ao arquivo antigo por causa do cache.
Answer: Você pode sim.
O problema é que isso dificulta um pouco a leitura do seu código (em javascript), já que ele é uma string PHP, e dificilmente o seu editor de texto vai sinalizar que a sintaxe está correta ou não.
Eu não sei qual é a finalidade disso, mas existem outras coisas que o PHP pode fazer que você pode levar em conta na hora de utilizar um javascript em conjunto.
função ob_start
A função ob_start permite capturar o buffer de saída que o PHP gera para a memória. Sendo assim, é possível capturar essa saída (antes de ir para o navegador, a grosso modo) e salvá-la numa string.
Exemplo
<?php if ($alguma_coisa): ?>
<?php ob_start() ?>

<?php
   $buffer_js = ob_get_clean();
    var_dump($buffer_js);
?>
<?php endif ?>

Isso pode ser útil se você quiser escrever o seu código javascript normalmente (como o conteúdo de um HTML, ao invés de uma string PHP) e guardá-lo na memória. Quando chamamos a função ob_get_clean() estamos capturando o que foi guardado no buffer e encerrando a captura do mesmo - ou seja, só o trecho javascript será pego.
função file_get_contents
Se realmente é necessário, já pensou na possibilidade de abrir um arquivo javascript pelo PHP e imprimi-lo como string?

HEREDOC
Uma outra boa ideia é utilizar a Sintaxe Heredoc. Mas ao utilizar ela você não vai ficar preocupado se tem que usar ' aspas simples ou " aspas duplas.
$script = <<<EOT

EOT;

Conclusão
Eu particurlamente já escrevi um código para poder debugar valores do PHP através do console do navegador. Para isso escrevi um pequeno código dessa forma:
function js_console_log($mixed) {
  printf('', json_encode($mixed));
}

Answer: Tira a palavra var do argumento da função, e vê se funciona, conforme abaixo:
$color = "red";
echo("

 <button onclick='change_background('".$color."')'>$color</button>

");

Answer: document.body.style.backgroundColor = red;

troque o red por cor. Não existe a variavel red.


Remove or disable ActionBar Hide animation?

Question: I have a custom video player,when user enters into fullscreen i am hiding actionbar but due to its animations its being delayed.
how to avoid it in normal ActionBar or SherlockActionBar  ?
Answer: I recommend to make use of Material Design with the new support library. By doing so you can replace your ActionBar with a Toolbar which gives you a lot more control. By using the Toolbar you can achieve your goal with the setVisibility() method.


Expected value of stochastic process given probability of number of sign changes on interval

Question:
We have a stochastic process $X_t$, which at a given time $t$ have a value of $-1$ or $1$. Number of sign changes on an interval $(t; t + \Delta)$ have a Poisson distribution $P(N = k) = e^{-\lambda\Delta} \cdot \frac{(\lambda\Delta)^k}{k!}, \lambda > 0, k \geq 0$. Compute the expected value $E[X_t]$, covariance $K(t_1, t_2)$ and variance $V[X_t]$.

I sort of can't wrap my head around how to take into account all the possible ways the sign change can occur in a sequence (which is probably not the correct way of thinking about it). Any hint would be appreciated.
Comment: The expectation will be determined by the probability that the sign flips exactly an even number of times. To obtain this, you need to calculate the sum of the infinite series whose terms are $\mathbb{P}(N = 2k)$ for all nonnegative $k$.
Answer: In the communications literature, this stochastic process is referred to as a random telegraph wave or semi-random telegraph wave depending on whether $X_0$ is modeled as a random variable equally likely to take on values $+1$ and $-1$ or as a deterministic value of $+1$ or $-1$ with no randomness involved.  Now consider a Poisson process with arrival rate $\lambda$ and let $N(t,t+s)$ denote the number of arrivals in the interval $(t,t+s]$ so that $N(t,t+s)$ is a Poisson random variable with parameter $\lambda s$.  With all this as background material, the process $X_t$ in question has the property that
$$X_{t+s} = \begin{cases}\,X_t, & \text{if}~N(t,t+s)~ \text{is an even number,}\\
-X_t, & \text{if}~N(t,t+s)~ \text{is an odd number.}\end{cases}$$
Since \begin{align}P(N(t,t+s)~ \text{is an even number}) &= \exp(-\lambda s)\cosh (s),\\
P(N(t,t+s)~ \text{is an odd number}) &= \exp(-\lambda s)\sinh (s)\end{align}
we get that
\begin{align}P(X_{t+s}=X_t) &= \exp(-\lambda s)\cosh (s),\\
P(X_{t+s} = -X_t) &= \exp(-\lambda s)\sinh (s)\end{align}
and
\begin{align}P(X_{s}=X_0) &= \exp(-\lambda s)\cosh (s),\\
P(X_{s} = -X_0) &= \exp(-\lambda s)\sinh (s).\end{align}
For the random telegraph wave, $X_0$ is equally likely to have value $+1$ and $-1$, and so
\begin{align}P(X_s=+1) &= P(X_0=+1) \exp(-\lambda s)\cosh (s) + P(X_0=-1) \exp(-\lambda s)\sinh (s)\\
&= \frac 12 \exp(-\lambda s)\cosh (s) + \frac 12 \exp(-\lambda s)\sinh (s)\\
&= \frac 12.\end{align}
Thus, $E[X_t] = 0$ for all $t\geq 0$ and $K(t,t+s) = E[X_tX_{t+s}]$ can be figured out from the information provided above.
For the semirandom telegraph wave with $X_0=+1$ (say),
$$P(X_t=+1) = \exp(-\lambda t)\cosh (t)$$ which has value $1$ at $t=0$ and then decays away to approach $\frac 12$ as $t\to \infty$ while
$$P(X_t=-1) = \exp(-\lambda t)\sinh (t)$$
which has value $0$ at $t=0$ and then increases to approach $\frac 12$ as $t\to \infty$. I will leave it to the OP to determine whether $E[X_t]=0$ for all $t\geq 0$ in this case also, and to figure out what $K(t,t+s)$ is from this information. As $s \to \infty$ for fixed $t$, the semi-random telegraph wave looks asymptotically like the random telegraph wave.


Sets shattered by $\mathcal{F}=\{\emptyset, \{2\},\{3\},\{1,2\},\{1,2,3\}\}$

Question: I have worked through this problem and determined that the $\mathcal{F}$ listed in the title is shattering-extremal and shatters the following sets: $\emptyset, \{2\},\{3\},\{2,3\},\{1,3\}$.
Now I was fairly confident that I had correctly found the collection of shattered sets, however it misaligns with a supposedly true necessary and sufficient condition. I'm hoping that someone can verify that I have correctly identified all the sets shattered by $\mathcal{F}$. I know there can't be more than 5 by the Sauer inequality, however maybe I mixed one up. A second pair of eyes would be very useful here!
Answer: The Sauer inequality says that $\mathscr{F}$ cannot shatter fewer than $5$ sets. If I'm not mistaken, it shatters six and so is not extremal: in addition to the five that you named, it shatters $\{1\}$: $\varnothing=\{1\}\cap\varnothing$, and $\{1\}=\{1\}\cap\{1,2\}$, for instance.
Comment: @GraphMathTutor: You're welcome. (That sort of thing happens occasionally to all of us.)
Comment: I am in disbelief that I mixed up my inequalities! Thank you for pointing this out, I really appreciate it despite how embarrassed I am.


Problemas ao usar string para recursos

Question: Estou criando um app quiz, o link é https://github.com/luisbalmant/QuickQuiz-Science.
Estou tentando usar o getString(R.string.nome) para migrar as strings da classe java e depois conseguir usar 2 idiomas.
Nos outros lugares eu consegui puxar as strings e está funcionando mostrando os textos quando rodo o app no celular, mas no momento que eu tento usar a string nas perguntas o app simplesmente passa a não abrir mais.
public class Questions {

        public String mQuestions[] = {

// Funciona
                "Pergunta número 1 xxxxxxx",

// NÃO FUNCIONA
                getString(R.string.Q1_function_insulin),

        };

=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/=//=/=/=/=/=/=/=/=
Atualização:
Fiz as seguintes alterações e não funcionou:
Minha MainActivity.java:

public class MainActivity extends AppCompatActivity {

    Button answer1, answer2, answer3;

    TextView score, question;

    private Questions mQuestions;

    private String mAnswer;
    private int mScore = 0;
    private int mQuestionsLength;

    Random r;

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

        mQuestions = new Questions(this);
        mQuestionsLength = mQuestions.mQuestions.length;

        r = new Random();

Meu outro arquivo Questions.java

import android.content.Context;

public class Questions extends MainActivity {

    Context context;
    public Questions(Context context)
    {
        this.context = context;
    }

    public String mQuestions[] = {

            "Pergunta número 1 xxxxxxx",
            context.getString(R.string.Q1_function_insulin),
            "Outra Pergunta número 2",

    };
Answer: Tente desta maneira:
public class Questions {

    private Context context;
    private Integer[] mQuestions = new Integer[]{R.string.Q1_function_insulin, R.string.Q2_any_name};

    public Questions(Context context) {

        this.context = context;
    }

    public String get(int q_number) {
        String question = null;
        try {
            question = context.getString(mQuestions[q_number - 1]);
        } catch (IndexOutOfBoundsException e) {
            Log.e("Question", "Invalid question number: " + q_number);
        }
        return question;
    }
}

Em OnCreate declare a classe Questions:
Questions mQuestions = new Questions(this);

Obtenha as questões:
String question1 = mQuestions.get(1); //obtém a questão 1 e assim por diante...

Answer: Na altura em que você está a usar o método getString() o context é nulo.
Repare que está a instanciar a classe Questions na altura da declaração.
public class MainActivity extends AppCompatActivity {

    Button answer1, answer2, answer3;

    TextView score, question;

    private Questions mQuestions = new Questions();

    private String mAnswer;

    ...

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

        r = new Random();
        ...
        ...
    }
    ...
    ...
}

Apesar da Activity indirectamente estender de Context, a implementação é delegada num Context que é passado ao construtor.
Como a inicialização é feita na declaração do campo,
private Questions mQuestions = new Questions();

ele é feita antes de o construtor ser executado, daí o Context ser nulo.
Para resolver crie a instância no método onCreate():
public class MainActivity extends AppCompatActivity {

    Button answer1, answer2, answer3;

    TextView score, question;

    private Questions mQuestions;

    private String mAnswer;

    ...

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

        mQuestions = new Questions();

        r = new Random();
        ...
        ...
    }
    ...
    ...
}

Comment: Olá, obrigado pela atenção. Eu tentei fazer as alterações "private Questions mQuestions;" e "mQuestions = new Questions();" Mas não obtive sucesso. Onde será que posso estar errando mais?
Comment: Se fez as alterações que eu indiquei tem de funcionar, a não ser que agora tenha um outro erro.
Answer: As respostas já contidas pode resolver o problema, mas veja abaixo uma explicação lógica em relação ao problema.
O getString() é um método que está contido na classe abstrata Context. O motivo de não estar funcionando, é porque você não estende essa classe no método Questions.
Por exemplo, se você criar sua classe public class Questions extends Activity, funcionará corretamente dentro do método onCreate. Veja abaixo o esquema:
Activity
    |
    +----> extends ContextThemeWrapper
                       |
                       +----> extends ContextWrapper
                                        |
                                        +----> extends Context

Como você mesmo disse, "Nos outros lugares eu consegui puxar as strings...", justamente porque esses "..outros lugares.." você está estendendo corretamente a classe que contém o método que estas a usar.
Agora a solução, existem várias, como você pode ver as respostas em sua pergunta.
Comment: Mesmo fazendo assim o problema continuará a existir se a classe Questions for instanciada na altura em que é declarada(como atributo), neste caso assim `private Questions mQuestions = new Questions(this);`. O problema é que nessa altura o context é nulo. A única solução é instanciá-la  no `onCreate()` ou em outro local após ele.
Comment: @ramaral por isso eu disse "dentro do método onCreate". =D
Comment: Sim mas nesse caso não necessita de passar o contex. A classe Questions, como é uma *inner class*(não static) da activity, tem acesso aos método do context/activity. Toda a sua explicação não se aplica nesse contexto.
Comment: @ramaral A explicação é focando porque não funcionada o método getString. Você acha desnecessário demostrar isso para o usuário?! Vou deixar a parte da solução desabilitada e depois edito numa forma mais clara.
Comment: A razão, neste caso, porque o getString() não "funciona" é porque o Context é nulo. Não é porque a classe não estender de Context ou porque não é passado um ao construtor.
Comment: @ramaral acho que as duas coisas né?!
Comment: Não não é. Veja a resposta do jefferson, é passado um context e mesmo assim não vai funcionar.
Comment: Olá ramaral e @acklay. Primeiro obrigado por todas as explicações. Eu estou iniciando o aprendizado agora e pelo que entendi aqui e lendo em alguns materiais vi que uma possível solução é instanciá-la no onCreate(), mas eu não sei como fazer isso. Tentei diversas coisas, mas como eu estou aprendendo eu leio e vou no código e "chuto" e continua dando errado. Será que não existe outra alternativa mais simples de eu de repente realocar ou refazer meu **public String mQuestions[] = {...** ?
Comment: @LuísBalmant Eu testei a classe Questions e ela funciona fazendo as alterações que mencionei na minha resposta, que mais não é do que instanciá-la no `onCreate()`. Se não funciona é porque tem agora outro erro(não testei o seu código todo). Adicione um comentário com o erro.
Comment: @ramaral, obrigado pela atenção e paciência. Não tenho certeza se consegui achar o erro mas acho que é o seguinte: *Error running Questions: The activity 'Questions' is not declared in AndroidManifest.xml*
Comment: Adicionei em AndroidManifest.xml o seguinte: ** e aparece uma mensagem que não tem um construtor padrão
Comment: @LuísBalmant eu acho que acabei confundindo você e bagunçando totalmente sua cabeça. É difícil até explicar por aqui. A resposta do Ramaral é a mais adequada para seu caso. Dei apenas um exemplo de como poderia funcionar estendendo a classe Activity na sua classe Questions; Tenta fazer com calma, ler um pouco mais e entender o ciclo de vida de como funcionada uma activity; conhece o conceito de  Abstração, Encapsulamento e Herança?! Tente ler um pouco mais para entender melhor. Acho que ganhará mais tempo em vez de tentar ir chutando. Daqui a pouco você vai rir das suas próprias perguntas. he
Comment: @acklay. Obrigado, vou fazer o que você recomendou. O pior foi que peguei uma outra dica e agora meu código está todo bagunçado... Tenho que entregar isso no curso que estou fazendo e tentei usar strings para poder dar suporte a 2 idiomas... Mas do jeito que está é melhor eu fazer sem strings e depois fazer isso sem chutar. Vou seguir seu conselho e ler os conceitos, pois não sei como funciona. Obrigado pela ajuda. É muito bom saber que a "galera" de programação se ajuda tanto assim. Valeu, abraço. Quando eu resolver volto aqui e posto a solução.

Problemas ao usar string para recursos


How to add a table as a header?

Question: I am working with iTextSharp trying to add an header and a footer to my generated PDF but, if I try to add an header that have width of 100% of my page I have some problem.
So I have do the following things:
1) I have create a class named PdfHeaderFooter that extends the iTextSharp PdfPageEventHelper class
2) Into PdfHeaderFooter I have implemented the OnStartPage() method that generate the header:
    // write on start of each page
    public override void OnStartPage(PdfWriter writer, Document document)
    {
        base.OnStartPage(writer, document);
        PdfPTable tabHead = new PdfPTable(new float[] { 1F });
        PdfPCell cell;
        //tabHead.TotalWidth = 300F;
        tabHead.WidthPercentage = 100;

        cell = new PdfPCell(new Phrase("Header"));
        tabHead.AddCell(cell);
        tabHead.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);
    }

If I use sometning like tabHead.TotalWidth = 300F; insted tabHead.WidthPercentage = 100; it work well but if I try to set as 100% the width of the tabHead table (as I do in the previous example) when it call the tabHead.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent) method it throw the following exception:

The table width must be greater than zero.

Why? What is the problem? How is it possible that the table have 0 size if I am setting it to 100%?
Someone can help me to solve this issue?
Tnx
Comment: Think about what a percentage *is*.  You are setting the width percentage to 100% of nothing.  I believe you still have to set the `TotalWidth`.
Answer: When using writeSelectedRows(), it doesn't make sense to set the width percentage to 100%. Setting the width percentage is meant for when you add a document using document.add() (which is a method you can't use in a page event). When using document.add(), iText calculates the width of the table based on the page size and the margins.
You are using writeSelectedRows(), which means you are responsible to define the size and the coordinates of the table.
If you want the table to span the complete width of the page, you need:
table.TotalWidth = document.Right - document.Left;

You're also using the wrong X-coordinate: you should use document.Left instead of 150.
Additional info:

The first two parameters define the start row and the end row. In your case, you start with row 0 which is the first row, and you don't define an end row (that's what -1 means) in which case all rows are drawn.
You omitted the parameters for the columns (there's a variation of the writeSelectedRows() that expects 7 parameters).
Next you have the X and Y value of start coordinate for the table.
Finally, you pass a PdfContentByte instance. This is the canvas on which you're drawing the table.
Comment: can you explain me wath exactly mean the meaning of the 5 WriteSelectedRows() paramethers?

How to add a table as a header?


.MP4 is not playing in IOS

Question: I have a ".mp4" video on my web page within video tag as below.
<code>    <video class="video-content" controls="controls" poster="/poster.jpg" width="840" tabindex="-1" >
        <source src="/ket.mp4" type="video/mp4"></source>
        <track kind="subtitles" label="English subtitles" src="/ket.vtt" srclang="en"></track>
        Your browser doesn't support HTML5 video tag.
    </video>
</code>
This is working well in all the browser and devices EXCEPT IOS (safari, iPhone, iPad)
In Safari developer tools, under the "Network" tab, when I check the details for the "ket.mp4":
Under the "Preview" tab:
An error occurred trying to load the resource
Under the "Headers" tab:
Summary:
Status: 200 OK
Source: Network
Request
Range: bytes=0-1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4)
AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1 Safari/605.1.15
Accept: /
Connection: Keep-Alive
Accept-Encoding: identity
Referer: https://www.example.com/ket.htm
X-Playback-Session-Id: 9C7F2AF7-9747-4AAD-B82D-A3D133FE4B20
Response
Content-Type: video/mp4
Content-Length: 17142979
Date: Thu, 31 May 2018 10:55:38 GMT
Last-Modified: Thu, 10 May 2018 17:32:50 GMT
X-XSS-Protection: 1; mode=block
Cache-Control: public, max-age=633
When I see the status, request, and response. I understand the server is responding to the request with the status 200. so, there should not be an issue on the server front. Because, i see the "content-length" under the "response" tab with its value as well.
when I check the forums, I see some discussion going around the "controls" attribute to set "true" or "false" or "controls". in my case I am setting controls attribute value as controls only.
Note: when I hit the ".mp4" URL directly in the browser, the video not playing and getting the same request/response in the developer tools.
Does anyone have any idea on this? how to make it this video works in Safari/iPhone/IPad. Do I need to understand this issue is on ".mp4" file itself? or Browser specific? or anything inside the "IIS Server".
Thanks in Advance
Answer: I am not necessarily sure if it would be the issue, but it does fit the bill. Make sure that the audio codec is compatible with iOS. I faced a similar issue where I was receiving videos that had HECV as the audio codec, switching them to H.264 fixed the issue.

.MP4 is not playing in IOS


Sin wave with double trough length?

Question: I'm not the best at maths but i'm working in 3D and need to create a formula for a spline object that is similar to the sin formula I already have (1).
50*Sin(t*PI)
but I need the trough to be double the length of the crest (2), I have done it manually for the image below
sin wave double trough reference
Any ideas much appreciated, thank you!
Answer: One period-$1$ option is $\sin\min\left\{\tfrac{3\{x\}}{2},\,\tfrac{1+3\{x\}}{4}\right\}$, where $\{x\}:=x-\lfloor x\rfloor$. For a period $P>0$, replace $x$ throughout with $x/P$.
Comment: thanks a lot for your answer, struggling to get my head around it.

any idea how I could input it into this field? the list of operators and functions I have available are to the left

https://imgur.com/a/no4FJiY
Comment: @JamalBennett You get $\{x\}$ as `x-floor(x)`. Call that $y$; you get the rest with `sin(min(3*y/2, (1+3*y)/4))`. By the way, which programming language is this?
Comment: awesome thank you, and I know internally cinema 4d runs on python, as for the language inside of the formula object I don't know

Sin wave with double trough length?


What is $x$ if $\sqrt{x+4+2\sqrt{x+3}}=\frac{x+8}{3}$?

Question: I need to find $x$, given that
$$\sqrt{x+4+2\sqrt{x+3}}=\frac{x+8}{3}$$
I simplified this to $x^4+14x^3+105x^2+68x-188=0$. According to Symbolab, that is not correct. That's why I'm goint to write out my attempt so you can point out where my mistake is.

My attempt
$$\sqrt{x+4+2\sqrt{x+3}}=\frac{x+8}{3}$$
$$\left(\sqrt{x+4+2\sqrt{x+3}}\right)^2=\left(\frac{x+8}{3}\right)^2$$
$$x+4+2\sqrt{x+3}=\frac{x^2+16x+64}{9}$$
$$9x+36+18\sqrt{x+3}=x^2+16x+64$$
$$-x^2-7x-28=-18\sqrt{x+3}$$
$$x^2+7x+28=18\sqrt{x+3}$$
$$(x^2+7x+28)^2=(18\sqrt{x+3})^2$$
$$x^4+7x^3+28x^2+7x^3+49x^2+196x+28x^2+196x+784=324x+972$$
$$x^4+14x^3+105x^2+68x-188=0$$
Where is my mistake? Even if this were true, I still wouldn't be able to solve it without a calculator (I can't use Rational Root Theorem on such a big numbers!).

By the way, the solution should be (again, according to Symbolab) $x \in \{1,-2\}$.
Comment: You *can* use the rational root theorem, which suggests that you check (among others, so why not first?) $\pm1$ and $\pm2$. Checking that $1+14+105+68-188=0$ and $16-112+420-136-188=0$ is straigtforward, so you find $1$ and $-2$ as roots. After that, you are left with a quadratic
Comment: To find all possible solutions, take a look at the quartic equation problem in here: https://en.wikipedia.org/wiki/Quartic_function .
Answer: It's $$\sqrt{1+2\sqrt{x+3}+x+3}=\frac{x+8}{3}$$ or
$$\sqrt{\left(1+\sqrt{x+3}\right)^2}=\frac{x+8}{3}$$
$$1+\sqrt{x+3}=\frac{x+8}{3}$$ or
$$\sqrt{x+3}=\frac{x+5}{3}$$ and since $x\geq-3$, it's
$$9(x+3)=(x+5)^2,$$
which gives $x=1$ or $x=-2.$.
Comment: +1 Nice trick! :)
Comment: I don't get it. How did you go from the original equation to any of the derived ones?
Comment: @Hanlon I used $x+4=1+x+3$, $(\sqrt{x+3})^2=x+3$ and $(a+b)^2=a^2+2ab+b^2.$ I added something. See now.
Answer: What you did is fine. Now, you can use the rational root theorem in order to find the roots $1$ and $-2$. Since your polynomial is $(x-1)(x+2)(x^2+13x+94)$, there are no more real roots. Note however that you still must check whether or not $-2$ and $1$ are solutions of the original equation.
Answer: You can brutally use Ferrari formula but no need here.
Search for obvious Roots , here 1 is clearly an obvious Roots then factorise by :
$$X-1$$
And try again with obvious roots. $0;1;2;-1,i,-i$
Comment: No mistake ! Just plug 1 in your équation and verify ! As I suggest in general try obvious roots to factorize
Comment: But where is my mistake? Or is Symbolab wrong?
Comment: What kind of formula is "Ferrari formula"? I can't find anything about it.
Comment: Think it is better known in France just look at formula there https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Ferrari
Comment: I translate the original idea for cultural knowledge: you replace $z^4$ by $ (z^2+y^2)^2-2yz^2-y^2 $ where $y$ is a parameter to fix further then you factorize  your original equation (like the expression above) and identify y.
Answer: Your question was how to determine the value of $x$ in the given equation:
$$
\sqrt{x+4+2\sqrt{x+3}}=\frac{x+8}{3}
$$
1.)
$
x+4+2 \sqrt{x+3} = \bigg( \frac{x+8}{3} \bigg)^2
$
2.)
$
x+4+2 \sqrt{x+3} =  \frac{x^2+8^2}{3^2}
$
3.)
$
9(x+4+2 \sqrt{x+3}) =  (x+8)^2
$
4.)
$
9x+36+18 \sqrt{x+3} =  (x+8)(x+8)
$
5.)
$
18 \sqrt{x+3}) =  (x^2+16x+64)-9x-36
$
6.)
$
\sqrt{x+3}) =  \frac{x^2+7x+28}{18}
$
7.)
$
x+3 =  \bigg( \frac{(x^2+7x+28)({x^2+7x+28})}{18 \times 18} \bigg)
$
8.)
$
x+3 =  \frac{x^4+14x^3+105x^2+392x+784}{324}
$
9.)
$
324x+972 =  x^4+14x^3+105x^2+392x+784
$
10.)
$
x^4+14x^3+105x^2+68x=188
$

The outcome of the equation is that it is a $4^ \text{th}$ degree polynomial of the form
$
a_1x^4+a_2x^3+a_3x^2+a_4x+a_4=0
$
$$
x^4+14x^3+105x^2+68x-188=0
$$
The solution given by my calcuator is:
$
x_1=1,
x_2=-2
$
To find out how that comes about, refer to Quartic polynomial solutions
Comment: You reproduced the same OP calculations. There is nothing new in your answer.
Comment: Then that proves the OP was correct but I went further to prove it using my own work that the answer was correct and added a reference to improve the OP's understanding of why which is exactly what was asked.


How to insert a View in a Panel?

Question: I want to create a page with a panel (using the Panels module). Then want to put a view in it. But I don't see anything in the content section, this is how it looks like:

I saw the question about "How to add Views into a Panels page", but in my Views display there is no panel pane display.
Where is my problem, do I need some additional module?
Answer: Welcome to Drupal, you had just one step more to do that, go to your module list in admin/modules and in Panels package enable Views content panes module then all views exists for using in panels. also it provide a news dispaly in views.

Also you can see this video for more getting involve with views pane
Answer: Can't add this as a comment :(  But, oh well...
Views content panes (views_content) is in Chaos tool suite [Chaos tools (ctools)] not Panels (panels).
# drush pmi views_content
 Extension     :  views_content
 Project       :  ctools
 Type          :  module
 Title         :  Views content panes
 Description   :  Allows Views content to be used in
                  Panels, Dashboard and other modules
                  which use the
                  CTools Content API.
 Version       :  7.x-1.12
 Package       :  Chaos tool suite
 Core          :  7.x

 Files         :  plugins/views/views_content_plugin_display_ctools_context.inc,
                  plugins/views/views_content_plugin_display_panel_pane.inc,
                  plugins/views/views_content_plugin_style_ctools_context.inc
 Requires      :  ctools, views
 Required by   :  none

How to insert a View in a Panel?


Como fazer buscas avançadas no GitHub?

Question: É possível construir operadores/queries personalizados na busca do GitHub?
O GitHub fornece a busca avançada através de um GUI, mas alem disso, como existem as buscas avançadas do Google (site:, cache:, etc...), é possivel fazer o mesmo buscando arquivos e diretórios específicos?
Isso com certeza pode ser útil para qualquer desenvolvedor, tomando como exemplo códigos de terceiros de acordo com sua busca personalizada.
Comment: https://github.com/search/advanced aqui você vai encontrar todas as opções de pesquisa disponíveis.
Comment: Sim, porem não através da busca por parâmetros. Estou vendo como fica mais rápido efetivar buscas através dos "operadores".
Comment: Na real, tenta digitar qualquer coisa em qualquer campo desse link que eu te passei que vai aparecer o que você quer no campo da pesquisa ;)
Comment: Sim, ele adiciona os operadores comuns, mas não os avançados como `filename:` e `filepath:`.
Answer: Depois de alguma pesquisa encontrei como isso pode ser feito.
É possível buscar por arquivos específicos, datas, diretórios, entre diversas outras formas de busca. Veja abaixo alguns exemplos:
filepath:app/models filename:user.rb

O filepath irá buscar pelo caminho exato em todos os projetos hospedados publicamente no GitHub. E o filename pelo nome do arquivo.
Encontre mais informações sobre buscas avançadas search-syntax e searching-code.
Answer: Todas pesquisas inline que você pode fazer:

user
repo
created
language
stars
forks
size
pushed
fork
extension
size
path
state
comments
label
author
mentions
assignee
updated
fullname
location
followers
repos
updated
fork

Como fazer buscas avançadas no GitHub?


How can I mock a higher order function in Jest

Question: I would like to a mock a function what looks like:
<code>export default (name, onRegComponentSize, debug=false) => event => {
    if(debug)
        console.warn(`${name} -> ${event.nativeEvent.layout.height}`)

    onRegComponentSize( name, {
        width: event.nativeEvent.layout.width,
        height: event.nativeEvent.layout.height
    })
}
</code>
But got no idea how could I do it. :/
Answer: I would argue to unit test the function itself, and then have the mock basically be a hard-coded version of the actual function. The idea is that once you've unit tested the function you can assume that it is working as intended everywhere else.
Comment: That make sense! It's really pointless to mock this function. I should just unit test the function once, and I can assume its working everywhere.
Comment: I would still argue to mock it, but to have a very simple mock. The reason is that you should never leave non-library imports unmocked so you can limit the functionality that you are testing.

Essentially, have custom mock functions based on the expected result.


Add Okta user to Okta group Python sdk

Question: Is there a method to add a user to an Okta group?  I see update_group, but nothing specific on how to add a user to an Okta group.
Answer: The latest updates to the SDK have add_user_to_group(group, user) and add_user_to_group_by_id(gid, uid) methods on UserGroupsClient.
from okta import UserGroupsClient
from okta.models.usergroup import UserGroup
from okta import UsersClient
from okta.models.user import User

groups_client = UserGroupsClient('your_url', 'your_key')
users_client = UsersClient('your_url', 'your_key')

# Create group
group = UserGroup(name='sample_name',
                  description='sample description')
group = groups_client.create_group(group)

# Create user
user = User(firstname.lastname@example.com',
            firstname.lastname@example.com',
            firstName='Joe',
            lastName='Schmoe')
user = users_client.create_user(user, activate=False)

groups_client.add_user_to_group(group, user)
# or
groups_client.add_user_to_group_by_id(group.id, user.id)

To get the latest:
pip install git+git://github.com/okta/oktasdk-python@master

Add Okta user to Okta group Python sdk


Optimization with continuous and discrete variables

Question: I am trying to maximize the following problem:
$$
\sum_{t=1}^T{z_t g_t + (1-z_t) h_t(x_t) }
$$
with respect to $z_t$ which is a vector of 0 and 1 only and $x_t$ which is a vector of $\mathbb{R}^T$. $h_t$ is a known vector of concave function and $g_t$ is a known vector. The initial state ($t=0$) is perfectly known.
In words, I would like to find the path for $x_t$ but allowing for discrete choice, i.e. if I choose $z_t = 1$, then I do not update the value of $x_t$ and $x_t = x_{t-1}$ but if I choose $z_t=0$ I maximize with respect to $x_t$.
What is the best method to do this? I have found solutions for a full discrete choice model but not for a model that mixes a continuous and discrete variable.
Thanks
T.
Answer: Introduce a new variable $y_t$ to represent the summand so that the objective is to maximize $\sum_t y_t$.  We want to enforce
$$y_t=\begin{cases}g_t &\text{if $z_t=1$}\\h_t(x_t) &\text{if $z_t=0$}\end{cases}$$
You can do this via the following big-M constraints:
\begin{equation}
(\ell_t-g_t)(1-z_t) \le y_t - g_t \le (u_t-g_t)(1-z_t)\\
(g_t - u_t) z_t \le y_t - h_t(x_t) \le (g_t - \ell_t)z_t,\\
\end{equation}
where $\ell_t$ and $u_t$ are (constant) lower and upper bounds on $h_t(x_t)$:
$$\ell_t \le h_t(x_t) \le u_t.$$
Now the objective and some constraints are linear.  If all $h_t$ are linear functions, then you can solve the whole problem with a MILP solver.  Otherwise, use a MINLP solver.
Comment: Thanks, how come the objective is now linear?
Comment: It is just a sum of the variables $y_t$.


How do I figure out whether my guitar tuning machine heads are failing on me?

Question: What are the symptoms of low quality guitar machine heads? I know it can be the nut that's causing the problem, but besides that, how can I know whether changing the machine heads will help my guitar stay in tune longer?
In my particular case, they seem to be O.K. but I am not sure. They feel just a little bit loose while tuning the guitar (compared to the other more expensive guitar I have), but I am unsure if something changes while playing or is it just the nut. Btw., the nut was changed once already some time ago because I wanted to put thicker strings and it did make a huge difference.
Comment: Suppose you tuned the guitar, left it alone for a day or two, and then picked it up again---is it still in tune? If not, that can't be the nut's fault, because you haven't played it. This isn't a definitive test, of course, but it might be suggestive.
Comment: @AlexBasson it usually stays in tune after that. one or two strings maybe go just a tiny little bit out of tune, but I consider that to be normal.
Answer: It's unlikely that all your machine heads would fail at exactly the same time.
So, if you think there's a problem with a particular string, you could try swapping the machine heads for the "bad" string with the machine head for a "good" string.
If the problem moves with the machine head, you've got some evidence that it's worth buying a new set of machine heads.
Answer: I would suggest partially removing the strings.  See how they are functioning on their own.
Comment: what do you mean by partially removing the strings?
Comment: I think he means only remove one or two of the strings; to see how those machine heads are functioning while not under a load.


Hex operations in C#

Question: Any hints on parsing / converting / operating on hex values in c# ?
In particular I want to cast a decimal int to hex and then output as a string...
Answer: <code>Int32 decValue = 42;
string hexValue = decValue.ToString("X");

Int32 decValue2 = Int32.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
</code>
See this post:
How to convert numbers between hexadecimal and decimal in C#?

Hex operations in C#


How can I make a node template that works on any url I specify?

Question: At the moment I can make a template for a specific node based on the node id.
However I want to make the same template work off of the url or title of the node so I can use it on multiple sites for the same node which doesn't have the same node id on each of the sites.
How can I do this?
Answer: Probably best to add a template suggestion rule to hook_preprocess_node, to control which templates are looked for.
e.g, in template.php
<code>/**
 * Implements hook_preprocess_node
 */
function mytheme_preprocess_node(&$variables) {
  if ($variables['node']->type == 'article') {
    // Regex replace anything not alphanumeric with underscore _ in node title
    $title = preg_replace('/[^a-z0-9]/', '_', drupal_strtolower($variables['node']->title));
    $vars['theme_hook_suggestions'][] = 'node__'. $title; // Use title in template suggestion
  }

}
</code>
Then you could use a template like
<code>node--my-node-title.tpl.php
</code>
Comment: This worked once I wrapped the node title with a string replace to sub - for _ but now I don't have any form vars coming through. I can get the form vars from $content['webform']['#form'] but it won't post.
Comment: OK, I'll update with a str_replace for that. What do you mean by form vars?
Comment: Webform is a different issue from node tpl question
Comment: The default webform template has "print drupal_render($form['submitted']);" and "print drupal_render_children($form);" to build the form in the template. These no longer work in the new template though?
Comment: Ah ok, can I adapt this approach for a webform? It appears that if I grab the form from the $content var and render it that there is no  it's just inputs in divs.
Comment: I ended up adding form alter and a theme hook to get my template working and form is processing now. Thanks for your help.


Why aren't g elements behaving as expected when D3 data is updated?

Question: I'm having trouble with D3's general update pattern not appending and updating as expected; I have provided 2 codepens that compare the binding of data using .data(data, d => d) and .data(data, d => d[input]), which is the only differing factor between the two - please refer to the codepens for a complete visual reference.
Codepen 1
Codepen 2
For context, the chart itself contains spin cycle class data per seat, sorted by ascending seat number. The DOM elements the data are bound to is structured as follows:
<svg>
> g.seat_0
>> rect.bar
>> text.measurement

> g.seat_1
>> rect.bar
>> text.measurement

.
.
.

> g.seat_n
>> rect.bar
>> text.measurement
</svg>

Each group represents a seat and contains a rect and text element. The initial data reads for d.total_power, but the dropdown allows you to select a metric of interest corresponding to a key, with the updated value reflected in the width of the rect.bar and text.measurement upon selection.
Both do not behave as expected:

In the case of (1) data(d => d), the first bar itself is updated with the rest being entered and appended, which is the expected behaviour.
In the case of (2) data(d => d[input]), namely  for Total power and Total calories options, there are a handful seats being entered and appended versus all transitioning to their updated value, which is the expected behaviour.
These issues aren't observed in Average speed or Total distance and selecting either in the dropdown demonstrates the expected behaviour of the chart.

You can refer to both the fill and the seat number appended on the lefthand side to narrow down the anomolies. Newly appended elements are filled with orange and updated elements are filled with red. I've also noticed it's the same seats that are acting up.

For case (1), the very first seat.
For case (2) in d.total_power seats 31, 43, 44, 47, 51; d.total_calories seats 29, 35, 51.

Essentially my questions are:

Why are some of these bars not behaving (appending + entering, updating) as expected? I went over the data and it looks consistent, so it isn't an issue with the object.
I understand that .data(d => d) joins the entire object to the group. Why is it that when we join using this method do all elements are entered and appended on a new dropdown selection vs being updated when we specify the join using .data(d => d[input])?
Answer: The problem here is just a misunderstanding regarding what's the correct returned value from a key function. Here's what the documentation says, emphasis mine:

A key function may be specified to control which datum is assigned to which element, replacing the default join-by-index, by computing a string identifier for each datum and element.

You have to return a string, and a string which uniquely identifies each element.
That said, let's see what's happening:

When you do d => d you're using '[object Object]' as the unique identifier, which is obviously wrong.
When you do d => d[input], let's say total_calories, you're using the total calories value for each element as their unique identifier, and obviously that's not unique.

Therefore, as each bar represents a seat, the correct key function seems to be just this:
.data(data, d => d.seat);

Comment: Thank you! Based on your answer if I am understanding correctly, because we are binding data to existing elements in the update process, we want to specify a unique identifier in the key function so that each element remains constant throughout the update process? In other words, we would be telling D3 where to bind updated data to the same elements (i.e.: seats) as differentiated by the unique identifier (i.e.: in this case the string for the seat number)?
Comment: @freudiandrip yes, that's correct.


How to start java application on boot

Question: I have a server with Centos 6. I've installed an configured everything so my server application runs smoothly, however if there is any unexpected reboots I have to manually start an SSH session and start the java program that runs it.
I've looked into several ways to start the software with the server but none of them have been able to run the software. Generally I start the software by running this command: nohup java -jar "/etc/software.exe" -name "Test New York Server". This works when I add it to a script and run it from terminal but not if I add it to /etc/rc.d/rc.local in anyway which is what was recommended in other threads. I issued touch commands to create a test file and those were executed so I'm obviously going at this the wrong way.
Answer: Boot scripts executing differently at boot vs on the terminal are usually a result of the script relying on something in the environment. Have your script execute 'env' and write that to a file, and compare that to 'env' when you run it in your shell. The most common issue is with the PATH variable.
Answer: Compare with your favorite open source (Java) software that is well packaged, to get ideas.
Mine is Graylog. There is a full init script wrapping their jar archive, so it behaves like any other service.

How to start java application on boot


What is the best way to parse a .c file?

Question: I am looking for ideas and examples about how to parse a ".C" file.
Apparently there is no easy way to do this. My goal is to parse a file, find a line and replace the wording of that line.
Any ideas? Thank you in advance!
Comment: What is a `.C` file?
Answer: You shouldn't need to parse a file to replace some text in it. A utility like sed can do it easily with either a literal string or a regular expression.
Otherwise any decent text editor will do it
Comment: I am trying to do a quick app for users without script knowledge, easier for them, and yes that's exactly the goal, do what "sed" does using a gui instead.....


If multiple pages are using the same css file,does it load again and again?

Question: This is a general question but i didn't found any satisfactory answer of this.I am creating a website with 7-8 pages.I have a common css which is being used in all the pages.When i go to my homepage this css gets loaded.Now when i go to some other page,would this css get loaded again from server or from browser local cache?
I read somewhere that you have to make some changes in server's .htaccess file for enabling the browser cache.Does browser itself doesn't use the cached files? I would be hosting the website first time so i have no idea of this stuff.Please guide so that i can make a site with better performance.
Answer: It depends on the caching policy enforced by the web server/ Most goods ones will only deliver it once and that may be over multiple visits to your site. Perhaps look at the HTTP headers to find out. Firebug can do this for you
Answer: I think this depends on the browser settings.  I do notice in chrome I sometimes need to empty the cache. You can also specify it to cache. I am not exactly sure how, but you can look up application caching.
Comment: The server can instructed to cache a file for X days/houts/etc/. Post is not cached but CSS uses Get. Of course a browser can dump stuff and therefore it has to be reloaded. It is best in the development environment to configure the server to instruct that no pages are cached


Write down a system of three equations in three unknowns with exactly three solutions

Question:
Write down a system of three equations in three unknowns with exactly three solutions.

I have absolutely no idea how to go about answering this question. Can someone please explain it to me?
Comment: What have you tried so far? This question has a lot of answers, so perhaps you have made ground on one of them?
Comment: I don't  even know how exactly to start.
Comment: Um... what don't you understand.  A system of three equations is clear.  three unknowns means three variables.  Call them x, y  and z.  Three solutions means that (x,y,z)=(a,b,c) and (x,y,z)= (d,e,f) and (x,y,z) = (g,h,i) are simultaneous solutions to the three equations.  My advice: make up the solutions first.  Come up with the exations second.
Comment: I doubt now about your question. tell please if you want to have exactly three solutions, $x,y,z$ or three solutions $(x_1,y_1,z_1), (x_2,y_2,z_2),(x_3,y_3,z_3)$.
Comment: Why don't you start with $2+1+3=6, 1+1-1=1, 7-1-6=0$. Then maybe turn these facts into a system of equations.
Answer: The first thing you should realize is that it cannot be a linear system of equations, because a linear system has either one unique solution, no solution, or infinitely many solutions.
Answer: Consider the following system (assuming not every equation needs to have all of the three variables in it):
$$
(x-1)(x-2)(x-3)=0 \\
y=0 \\
z=0
$$
This system has exactly three solutions: $(1,0,0),(2,0,0),(3,0,0)$.
Comment: Ooh wait I think I get it. So let's say they asked for 2 equations, two unknowns and 3 solutions then would the following be correct : x^3 +2x^2 -x=0 and y=0 ? With solutions (1,0),(-1,0) and (0,0). Or is that stil wrong
Comment: Your idea is correct, but your example is not. The three zeros of $x^3+2x^2-x$ are $x_1=0$, $x_2=-1-\sqrt{2}$ and $x_3=-1+\sqrt{2}$.
Answer: If someone said "two equations, two solutions", I'd probably draw a circle and a line cutting through it.  Say, $x^2+y^2 = 1$ and $x=0$.  Or maybe a parabola with a line cutting it, say, $y=x^2$ and $y=1$.  So my advice is "think geometrically."
Comment: Three unknowns are needed.
Comment: You don't need three unknowns to think geometrically, which was, I think, B. Goddard's point. And besides, your third equation can always be $z = 0$, as in Janik's solution.


Propensity score matching using R

Question: I have 50 control subjects and I would like to get 150 treatment subjects (i.e., a 1:3 ratio between the control and treatment groups) using propensity score matching and a few covariates. After performing the matching I would like to get indices of matched subjects (i.e., indices for both control and treatment groups) - this is my main goal.
I would like to do this in R. I see that R has the Matchit and Matching packages. However, I  am not sure what the difference is between the two and which one is more appropriate for my purpose.
I am also not sure about the code and what output I need to be looking at to get indices of the matched control and treatment subjects.
Also, could I use the match() command without the outcome (i.e., Y) variable? The experiment is not yet complete and thus I do not have the outcome variable. Would it be appropriate to use match(Y=NULL, Tr=.....)?
Comment: I know that `Match` in the `Matching` package does not require you to supply a `Y` variable.
Answer: Have a look at an overview here: http://www.biostat.jhsph.edu/~estuart/propensityscoresoftware.html
Match package does, as Charlie mentioned, let you exclude the outcome variable and will provide you with matching only then.

Propensity score matching using R


Validating json with pydantic (fastapi)

Question: So I have a request that looks like this
<code>[
    {
        "Code": "EVR-T-0dsfdsdf532",
        "Agent": "pacman",
        "Kilometrage": "60000",
        "Operation": "Vidange",
        "Piece_Consomable": "filtre à air",
        "Quantité": 1,
        "UnitPrice": "200.00",
        "Montant": 200,
        "Mainoeuvre": 100
    },
    {
        "Code": "EVR-T-ddsdf53dfds2",
        "Agent": "pacman",
        "Kilometrage": "60000",
        "Operation": "Pneumatique",
        "Piece_Consomable": "(Autre) Uiop",
        "Quantité": 1,
        "UnitPrice": "200.00"
    }
]
</code>
and my code looks like this
<code>@app.post("/utilities/Entretien/submit", status_code=status.HTTP_200_OK)
async def create_item(item: Request, db: Session = Depends(get_db)):
    operations = await item.json()
    for i in operations:
        i : EntretienModel
        new_operation = TableEntretien(**i)
        db.add(new_operation)
        db.commit()
        db.refresh(new_operation)
    return {"ping": "pong"}
</code>
I'm basically looping through the array then inserting every object in the database,
I'm looking for a solution that can validate every object with a pydantic model like this one:
<code>class EntretienModel(BaseModel):
    Code: str
    Agent: str
    Kilometrage: int
    Operation: str
    Piece_Consomable: str
    Quantité: int
    UnitPrice: float
    Montant: int
    Mainoeuvre: Union[int, None] = None
</code>
Or another solution better than mine, Thanks.
Answer: In a FastAPI operation you can use a Pydantic model directly as a parameter. According to the FastAPI tutorial:

To declare a request body, you use Pydantic models with all their power and benefits.
[...]
With just that Python type declaration, FastAPI will:

Read the body of the request as JSON.
Convert the corresponding types (if needed).
Validate the data
[...]

Example:
<code>@app.post("/utilities/Entretien/submit", status_code=status.HTTP_200_OK)
async def create_item(operations: List[EntretienModel], db: Session = Depends(get_db)):
    ...
</code>

Validating json with pydantic (fastapi)


HP Printer Malfunction (Virus?)

Question: i'm having serious problems with several HP Printers.
The issue is the following: my printer (different models) prints random ASCII character on the first line of a paper ( image sample: http://tinyurl.com/d2744sk ) and prints several papers ( 50+ )
And here another screenshot of the print queue: http://tinyurl.com/cvxeo6n the first 2 are the ascii "print".
The problem is presenting himself on different printer models (but only HP) and in different organization with some personal in common but no connection between the two. The building are miles away. I suspect some user spread the virus via USB keys.
I run a full system scan with several antivirus with no result. I'm updating printers firmware, if avaiable, as we speak.
Consider that:
<code>- All models seems to be vulnerable: Laser and InkJet
- Antivirus can't find anything
- Driver and firmware are updated to the latest version
- The printer function properly but every 1 or 2 prints starts printing ascii character
- The client are Windows XP 32Bit and Windows 7 64Bit
- Printers are all in the same Subnet and VLAN there's direct connectivity from clients to printer with stable ping. I ruled out network issues
</code>
Some of printer models affected HP P2055dn, HP2015dn
My organization has 15+ Printers and 80+ Client i need a deployable solution if applicable.
What could i do?
Thank you in advance!
Comment: Right now i'm in the process of upgrading all HP Firmware (newer is present at least for P2055dn) and disabling SNMP (while is not used in my organization for printers)

Seems to mitigate the problem but not resolving it.
Answer: i've seen this exact problem when using the HP Universal Printer Driver. apparently, this is a known issue with it. the issue is caused by settings from different versions of the driver not being compatible.
for example:

printerA from server1 is installed on client computers using HP universal version 5.3
printerA is used by the clients
some time later, printerB from server2 is installed on those same computers using HP universal version 5.4, upgrading the drivers for all and causing these clients to now use version 5.4 for printerA
printerA now prints gibberish because the version 5.4 driver doesn't understand some settings that the 5.3 driver stored

in our case, even just upgrading the printer driver on a single server caused this problem, too. but the above scenario was how we discovered the problem to begin with.
solution:
make sure the HP Universal Print Driver used is consistent across the organization.
in my case, to clear up the lingering errors, i had to delete and re-create the printers on the print servers to eliminate the old settings that were causing problems. these settings then were pushed down to the clients, mostly eliminating the problem. a few problem children were fixed by deleting and re-adding the printers on those clients.
Comment: Thnaks for your reply. Printers are installed directed on the client (TCP/IP) port not shared by server. However driver are "consistent" every machine connected with a specific printer has the same driver. However i'll check for peace of mind.
Answer: This isn't a virus this is driver corruption.

Uninstall the printer.
Remove all traces of the driver
Reinstall the printer and the correct driver.
TEST.

This should resolve your issue.
Comment: Windows update could have killed it. A virus defition in your Antivirus may have killed it. If you have 80+ machines why are you not using print queues?
Comment: First of all thank for your reply.

Is it possibile that different drivers on different machines (80+) corrupts in a blink of an eye all the sudden? I don't believe so.

However reinstalling the drivers didn't resolve the issue (already tried).
Comment: We're using network printers every office with 10 client has 1 printer and 1 multifunction copier (not affected by this problem).

We use WSUS and we approved no update in the last week (the problem presented yesterday) in thoery microsoft use pacth tuesday policy.

Our antivirus is Symantec Endpoint Protection consider printers are installed by more than 1 year.

However thank you i'll look into it and i'll let you know.
Answer: I'd say corrupt driver / spools due to update.  But then I just read this on SANS:

There have been several reports now of PCs on the network printing what looks like an executable to a large number of printers.  Several scanning tools will cause this kind of behaviour, but in the instances I know of these tools were not being used on the network at the time.  The various AV products aren't great at picking this up, yet.
If you have this happen in your network use your logs to determine the sending machine (will be in the print logs) and take it offline for investigation and re-imaging. If you happen to have the actual malware upload it via the contact form and make our malware guys and gals happy.
Mark
Comment: Thanks for your reply. Monday i'll try to identify the machine (i already have a suspect) and i'll get back to you.
Answer: So far I found these reports, in addition to the SANS ISC Diary post:
http://community.spiceworks.com/topic/232157-printer-prints-virus-string-until-out-of-paper?page=2

See post from "kinggeorge" on Jun 08, 2012 at 07:01 AM page 2:
" ... Only on the Windows 7, we found a (hidden) scheduled task, that used rundll32.exe with a randomly generated dll-file in c:\windows\system32 ..."

https://community.mcafee.com/thread/45989?start=10&tstart=0

Post #14 from "mrussell77" on Jun 8, 2012 8:02 AM confirms registry keys reported in the SANS diary comments.
Post #15 from "scorpy" on Jun 8, 2012 7:58 AM mentions the scheduled task.

HP Printer Malfunction (Virus?)


Nivo jQuery error. It won't work at all

Question: Thanks for your time.
I follow the tutorial, and then the video, but I can not get it to work.
My head looks like this
<link rel="stylesheet" href="nivo-slider.css" type="text/css" media="screen" />

And in my body is

    This is an example of a HTML caption with a link.

And at the bottom of the body, right before it closes, is

I literally copy and pasted everything... I have no idea what is wrong. Any insight is greatly appreciated.
Thanks so much
Comment: How doesn't it work? Do you get any error messages in your JS console?
Comment: there are a bunch of errors...this is one of them..
Uncaught TypeError: Object [object Object] has no method 'nivoSlider' Index.htm:255
(anonymous function) Index.htm:255
f.event.dispatch jquery.min.js:3
h.handle.i
Comment: and some more like this..
Failed to load resource: the server responded with a status of 404 (Not Found) http://redvaultproductions.com/css/screen.css
Failed to load resource: the server responded with a status of 404 (Not Found) http://redvaultproductions.com/jquery.nivo.slider.pack.js
Failed to load resource: the server responded with a status of 404 (Not Found) http://redvaultproductions.com/nivo-slider.css
Failed to load resource: the server responded with a status of 404 (Not Found) http://redvaultproductions.com/images/nemo.jpg
Comment: Judging by your errors - are you sure you are linking to the css and js files in the correct locations? Are they located in your root directory along with this page? I also use Nivo and mine is set up the same as yours but is working fine. Also check to make sure you are not loading jQuery twice (I had that issue before).
Comment: @Shannon I was not linking it to the right spot! Thanks so much! I would so click yours as the answer right now, and if I were allowed to I would upvote it.
Comment: Added as an answer if you'd like to accept.
Answer: You are not pointing to the correct location for your js and/or css files. Based on your code they should be in the root directory along with this page.
Comment: YOU DID IT. thank you. in light of this I changed it to a new /nivo folder.

Nivo jQuery error. It won't work at all


Sobrescrita de método vale para toda hierarquia de classes?

Question: Quando tem vários extends (como no exemplo abaixo) todos os métodos são sobrescritos até o último extends? Se não, qual método que vai ser utilizado?
class D extends C {
  void x() {
    System.out.println(1);
  }

}
class C extends B {
  void x() {
    System.out.println(2);
  }

}
class B {
  void x() {
    System.out.println(3);
  }
  void y(B b) {
    b.x();

  }
  void y(C c) {
    c.x();

  }
  void y(D d) {
    d.x();

  }

}
class A {
  public static void main(String[] args) {
    new B().y(new C());

  }

}

Answer: Não sei se entendi o que quer saber, mas já adianto que nenhuma classe é sobrescrita, esta não é uma qualidade que classes possuem. Métodos podem ser sobrescritos.
E sim, todos os métodos tradicionais em Java que são virtuais são sobrescritos não importa a profundidade da hierarquia e eles substituem o método das classes mães, portanto este código irá imprimir 2.
E portanto a classe que será usada é aquela que for instanciada em determinado local, a escolha de classes é feita pelo programador. Em nenhum momento neste código ocorre polimorfismo, por isso neste caso também não há escolha de métodos, é usado o método da classes sendo usado de forma pura e simples.
E as sobrescritas idealmente deveriam usar a anotação @Override.
Comment: Vlw amigo, ficou bem claro, escrevi errado era métodos mesmo. Para eu ter certeza se entendi, se por ventura eu escrevesse "new B().x()" ao invés de "new B().y(new C())" executaria o polimorfismo e retornaria "1"?
Comment: Este código não tem polimorfismo em parte alguma, muito menos nesta parte, mas resultaria em 1 de forma simples e direta.
Comment: não tem sobrescrita?
Comment: Não tem polimorfismo.
Comment: Blz vlw por tudo, me ajudou bastante, preciso procurar entender melhor o termo polimorfismo.
Comment: Por isso eu coloquei um link na resposta.


Ruby não acrescenta no final do arquivo

Question: Preciso adicionar o conteúdo de um array no final de um arquivo, nomeadamente frames.mcfunction, porém não é acrescentado no final do arquivo e sim no começo. Como faço para acrescentar no final do arquivo?
frames.mcfunction:
execute if score frame frames matches 0..0 run function frames/frame_0
execute if score frame frames matches 1..1 run function frames/frame_1
[...]
execute if score frame frames matches 2179..2179 run function frames/frame_2179
execute if score frame frames matches 2180..2180 run function frames/frame_2180

código:
# DEFINE NEW LINES
commands = [
  "function end",
  "tellraw @a {\"rawtext\":[{\"text\":\"§b#{'='*20}§r\"}]}",
  "tellraw @a {\"rawtext\":[{\"text\":\"§b=§l§f#{'FINISHED'.center(18)}§r§b=§r\"}]}",
  "tellraw @a {\"rawtext\":[{\"text\":\"§b#{'='*20}§r\"}]}",
  "tellraw @a {\"rawtext\":[{\"text\":\"§f#{'Total:'.ljust(10)}§e#{2181.to_s.rjust(10)}§r\"}]}\n"
]

# APPEND NEW LINES
commands.length.times do |i|
  File.open("frames.mcfunction","a") {|l| l.puts commands[i]}
end

Output: (arquivo frames.mcfunction)
function end
tellraw @a {"rawtext":[{"text":"§b====================§r"}]}
tellraw @a {"rawtext":[{"text":"§b=§l§f     FINISHED     §r§b=§r"}]}
tellraw @a {"rawtext":[{"text":"§b====================§r"}]}
tellraw @a {"rawtext":[{"text":"§fTotal:    §e      2181§r"}]}
execute if score frame frames matches 0..0 run function frames/frame_0
execute if score frame frames matches 1..1 run function frames/frame_1
[...]
execute if score frame frames matches 2179..2179 run function frames/frame_2179
execute if score frame frames matches 2180..2180 run function frames/frame_2180

Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Para adicionar o conteúdo de um array no final de um arquivo, você pode usar o método File.open() com o modo de abertura "a" (append). Isso permitirá que você adicione novas linhas no final do arquivo, em vez de sobrescrever o conteúdo existente.
# Define as novas linhas que serão adicionadas ao arquivo
commands = [
  "function end",
  "tellraw @a {\"rawtext\":[{\"text\":\"§b#{'='*20}§r\"}]}",
  "tellraw @a {\"rawtext\":[{\"text\":\"§b=§l§f#{'FINISHED'.center(18)}§r§b=§r\"}]}",
  "tellraw @a {\"rawtext\":[{\"text\":\"§b#{'='*20}§r\"}]}",
  "tellraw @a {\"rawtext\":[{\"text\":\"§f#{'Total:'.ljust(10)}§e#{2181.to_s.rjust(10)}§r\"}]}\n"
]

# Abre o arquivo em modo de anexo
File.open("frames.mcfunction","a") do |file|
  # Adiciona cada linha do array ao final do arquivo
  commands.each do |line|
    file.puts line
  end
end

Espero ter ajudado!
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Ruby não acrescenta no final do arquivo


Dkim DNS Setup: dig +trace finds the key, dig notrace doesn't

Question: i'm setting up DKIM for my domain to sign outgoing mails.
I've got some issues on DNS configuration, because DNS configuration is mixed between external DNS (hosting) and a cloud server, which sends the emails.
Cloud server IP: 220.127.116.11 (fake)
External DNS
@   A   126.96.36.199
www A   188.8.131.52
_domainkey  NS  22.214.171.124

I've added the _domainkey as NS record to resolve it with the server DNS zone.
The zone foo.it in the cloud server
$ttl 600

foo.it. IN  SOA vm1613.cs17.providername.it. support.foo.it. (
            1369844294
            600
            600
            600
            600 )
foo.it. IN  NS  vm1613.cs17.providername.it.

201305._domainkey   IN  TXT "v=DKIM1; k=rsa; t=y; p=[long key]"   ; ----- DKIM key 201305 for foo.it

(changed from 201305._domainkey.deebate.it. to 201305._domainkey thanks to @Gnouc)
Now, when i dig with +trace i get:
root@vm1613:~# dig 201305._domainkey.foo.it txt +short +trace
NS a.root-servers.net. from server 126.96.36.199 in 30 ms.
NS b.root-servers.net. from server 220.127.116.11 in 30 ms.
NS c.root-servers.net. from server 184.108.40.206 in 30 ms.
NS d.root-servers.net. from server 188.8.131.52 in 30 ms.
NS e.root-servers.net. from server 126.96.36.199 in 30 ms.
NS f.root-servers.net. from server 184.108.40.206 in 30 ms.
NS g.root-servers.net. from server 220.127.116.11 in 30 ms.
NS h.root-servers.net. from server 220.127.116.11 in 30 ms.
NS i.root-servers.net. from server 184.108.40.206 in 30 ms.
NS j.root-servers.net. from server 22.214.171.124 in 30 ms.
NS k.root-servers.net. from server 22.214.171.124 in 30 ms.
NS l.root-servers.net. from server 220.127.116.11 in 30 ms.
NS m.root-servers.net. from server 220.127.116.11 in 30 ms.
TXT "v=DKIM1\; k=rsa\; t=y\; p=[long key]" from server 18.104.22.168 in 0 ms.
root@vm1613:~#

If i don't +trace, there aren't results (SERVFAIL).
When i test the key, i get:
root@vm1613:~# opendkim-testkey -d foo.it -s 201305 -k /etc/opendkim/201305.private -vvv
opendkim-testkey: key loaded from /etc/opendkim/201305.private
opendkim-testkey: checking key '201305._domainkey.foo.it'
opendkim-testkey: '201305._domainkey.foo.it' unexpected reply class/type (-1/-1)
[Exit 69]
root@vm1613:~#

because (i think) it doesn't resolve as TXT but as A record.
Why this difference with +trace?
I was thinking about DNS cache so i let pass three days, but the result is always this.
Comment: i've resolved putting the TXT DKIM record directly into the hosting DNS panel
Answer: 201305._domainkey.foo.it. is valid, so long as it has that trailing dot.  redundant info perhaps, but not invalid.
Could it be that your DNS has not propagated fully yet?  Or that some of the DNS servers for your domain are serving different info to others?  Try running dig against each of the ns servers for your domain in turn, looking at both the SPF record and the SOA record.
It's good practice to have both an SPF record and a TXT record with the same content.
Comment: i think that the _domainkey NS record didn't work properly


covariance of a structural equation model

Question: I'm trying to create a Bayesian structural equation model where I can specify directional paths between observations, latent variables, and indicators.
I use the term observations to refer to data with potential associated errors. For example, suppose I'm trying to model the classic data from Holzinger and Swineford (1939) where children from two different schools completed the same set of tests. Here, observations would be test scores.
Latent variables are unobserved variables that potentially influence the observations and one another For example, one might be general intelligence.
Finally, indicators are observations that have no error. For example, one indicator might be the school.
So far, I have figured out how to create paths from latent variables to items, and from one latent variable to another. I assume that observations are multivariate normal,
$$\boldsymbol{Y}\sim\mathrm{Normal}\left(\boldsymbol{\mu},\boldsymbol{\Sigma}\right)$$
where $\boldsymbol{\mu}$ is a $p$-length vector of means and $\boldsymbol{\Sigma}$ is an $n \times p$ covariance matrix. For former is given by
$$
\boldsymbol{\mu}=\boldsymbol{\nu}+\boldsymbol{\Lambda}\boldsymbol{\alpha}
$$
where $\boldsymbol{\nu}$ is $p$-length vector of observation intercepts, $\boldsymbol{\Lambda}$ is a sparse $p \times m$ matrix of paths from latent variables to observations, and $\boldsymbol{\alpha}$ is a $m$-length vector of latent intercepts.
The covariance matrix $\boldsymbol{\Sigma}$ is given by
$$
\boldsymbol{\Sigma}=\boldsymbol{\Lambda}(\boldsymbol{I}-\boldsymbol{B})^{-1}\boldsymbol{\Psi}(\boldsymbol{I}-\boldsymbol{B}^\mathrm{T})^{-1}\boldsymbol{\Lambda}^\mathrm{T}+\boldsymbol{\Theta}
$$
where $\boldsymbol{B}$ is a sparse matrix of paths from latent variables to latent variables, $\boldsymbol{\Psi}$ is an $m \times m$ diagonal matrix of latent variances, and $\boldsymbol{\Theta}$ is a $p \times p$ diagonal residual variance matrix.
I want to modify this model so that I can specify paths between indicators (let's say they are stored in matrix $\boldsymbol{X}$) and latent variables. Let's call this matrix $\boldsymbol{A}$.
I think I must modify $\boldsymbol{\Theta}$ to something like $\boldsymbol{A}$$\boldsymbol{\Theta}$$\boldsymbol{A}^\mathrm{T}$ but not sure where $\boldsymbol{X}$ should go.
Answer: You can't do this directly with the approach that you are using.
Instead, you can hack your way around it. For the indicator of interest, create it's own latent variable, for that element, the value of $\Lambda$ is 1.00, and the error variance is 0.00. Now the latent variable and the measured variable are interchangeable, and you can add the appropriate path to $B$.
Comment: I deleted my previous comment because I was being stupid. I understand now.
Comment: Oh, I didn't see it. :)


How do I get WebStorm's JavaScript Library support using DefinitelyTyped interface definitions to work?

Question: I'm trying to get WebStorm's JavaScript Library support using DefinitelyTyped TypeScript interface definitions to work as expected (hopefully as intended) in JavaScript.
I've added the library definitions using the Download feature...

I made sure it's in the global scope, too.
Yet I can't seem to reference THREE or any of the other DefinitelyTyped library module definitions.

It's not just undefined inside of JSDoc references, it's undefined everywhere. I know I should have "@type" here instead of "@param", I was just trying to elicit a different result; the results are the same.
What am I doing wrong?
Do I need to create a <code>_references.js</code> as one would for Visual Studio or something?
Answer: Restart WebStorm at least twice (possibly four times) after having added the interface definitions.

This solution applies to WebStorm 2016.2.1