How to configure Spring Boot HikariPool for use with AWS' RDS Proxy?

Question: I've been trying to get our microservice setup to use the AWS RDS Proxy rather than connecting straight to the cluster for failover reasons. It connects just fine, but after it has been running for a while, there are errors that surface that end up having bad effects on any ongoing calls that happen at the time.
The error messages are:

HikariPool-1 - Failed to validate connection org.postgresql.jdbc.PgConnection@11bc3390 (This connection has been closed.). Possibly consider using a shorter maxLifetime value.
DataSource health check failed

The extra config properties I have setup in our application.properties file (besides username, password, url) are:
<code>spring.datasource.hikari.maximum-pool-size=50
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.max-lifetime=600000
spring.datasource.hikari.idle-timeout=180000
</code>
I have the RDS Proxy setup with pretty much the default settings for it.
Any ideas how to resolve these errors so that the connections from our microservice don't produce errors and cause any instability?
Comment: Duplicate? [https://stackoverflow.com/questions/60301008/failed-to-validate-connection-this-connection-has-been-closed-possibly-consi?rq=1](https://stackoverflow.com/questions/60301008/failed-to-validate-connection-this-connection-has-been-closed-possibly-consi?rq=1)
Answer: I don't have a fix. I guess you would need DEBUG logs or a debugger session to get to the core of this particular problem.
But I'm questioning the general architecture. Let's look at the docs:

Amazon RDS Proxy is a fully managed, highly available database proxy for Amazon Relational Database Service (RDS) that makes applications more scalable, more resilient to database failures, and more secure.

Your Amazon RDS Proxy instance maintains a pool of established connections to your RDS database instances, reducing the stress on database compute and memory resources that typically occurs when new connections are established.

https://aws.amazon.com/de/rds/proxy/
So the RDS Proxy is highly available and maintains a connection pool. This makes me wonder, why you also want a connection pool (Hikari) on the microservice itself.
It seems redundant. You have effectively two fail-over mechanisms in your setup.
I could imagine that this is the root of the problems you are describing.
I would suggest just using a simpler single-connection DataSource implementation to connect to the RDS Proxy.


1- #5- 8 Chord naming convention

Question: In the song Ordinary World from Duran Duran, the progression for the chorus is as follow (as shown by Carl Brown of guitarlessons365), B5 - F#m - Dsus2 - some C# chord - E5.
The chord between Dsus2 and E5 consist of the 3 notes C#, A and C#. It is obvious to me that the chord is build as follow, root (C#)  - #5 (A) - octave (C#).
My question is, how do we properly name this chord. I know it is some kind of augmented chord due to the #5, but with the absense of a 2nd, 3rd and 4th (or any chord tone), is this one of the very few times where the (no 3) notation is used, so can we call it a C#aug (no3) chord. Please bear with me here as I have no formal training in music theory. I got hammered the other day for calling it a powerchord.
Comment: I recommend some form of Occam's Razor when trying to analyze music. In this case, you seem to have assumed that an interval is an augmented-fifth when it could also be interpreted as a minor-sixth; since the harmonic analysis (per endorph's answer) is much simpler when the interval is treated as a minor-sixth, that's probably what you should have assumed.
Comment: ....in fact, you were already part-way there--note that your proposed spelling of C# - A actually *is* a sixth rather than a fifth. D-flat to A-natural, or (...if Duran Duran were a prog band) C# to G-double-sharp, would be an augmented fifth.
Answer: Given the rest of the progression, I'd be inclined to interpret it as an A/C#, missing the fifth (E). So your progression is B5 - F#m - Dsus2 - A/C# - E5. You could try and notate the missing fifth in the chord symbol, but I'm not sure it's necessary in this case. From my cursory listen, the missing fifth is not a crucial detail for this song.
It's not a power chord, because we use that term to mean a chord with only a first and a fifth (possibly doubled/tripled/whatever). This particular chord has a first and a third, but no fifth, so we can't call it a power chord.
Comment: The bass is certainly playing C# at that point.
Comment: endorph, it's probably worth emphasizing that the C# to A interval should be spelled as a minor-sixth rather than an augmented-fifth as the question incorrectly assumes. I think that seems to be the primary point of confusion.
Comment: @Tim Hence `/C#`, as this answer says (twice!). Maybe you need more coffee....?
Comment: @KyleStrand - the reason I said that comment was because I *listened* to the piece, to confirm what was being played. Why should I blindly (deafly?) take anyone's word for what's there. I've been caught out too often! Internet stuff is full of inexactitudes...
Comment: @Tim I think you may be missing my point, which is that I'm not sure how your comment is relevant to endorph's answer. "A/C#" does in fact mean that the bass is playing C#. Since endorph doesn't express any uncertainty on this point, and you are in agreement with them, I'm not sure what your comment was adding...?
Comment: @KyleStrand - it was merely pointing out my agreement, as you spotted. Emphasising the fact that the chord quoted *actually* was correct, naming the bass note as the C# *actually* played.  And, yes, my diagnosis is probably inaccurate. Sometimes, one just has to prove that one is human after all...
Comment: @Tim Ah, got it!
Answer: For a laugh I'd call in a '5+' or '+5' chord. Seem to remember Jimi using similar in Purple Haze. Incidentally, the aug 5 will be called Gx or G##, to keep it in key
Comment: Never thought I'd give you a downvote! But it seems ridiculous to assume that the enharmonic spelling of the chord given in the question is accurate, since A-natural is a perfectly reasonable non-augmented note given the rest of the chordal context.
Comment: ...or, rather, the spelling is fine (since it's given as a sixth), but the interpretation as an augmented sixth is a weird thing to assume is correct.
Comment: @KyleStrand - thanks for being man enough to downvote *and* give a reason! I actually called it an aug 5 rather than your quoted aug 6, though.
Comment: ....right. I need more coffee too. :P The point is that it's diatonic.

1- #5- 8 Chord naming convention


First 30 solutions of Pell's equation.

Question: $k^2 - 5z^2 = 1 (1)$
The equation (1) is a Pell equation where $D = 5$ and the first solution $\{k, z\} =\{9, 4\} = \{p, q\} (2)$
$k_n = \dfrac{(p + q\sqrt{D})^n + (p - q\sqrt{D})^n}{2} ;
 z_n = \dfrac{(p + q\sqrt{D})^n - (p - q\sqrt{D})^n}{2\sqrt{D}} (3)$
Where n is index of a solution. Replace p and q in (2) with (3)
$k_n = \dfrac{(9 + 4\sqrt{5})^n + (9 - 4\sqrt{5})^n}{2} ;
 z_n = \dfrac{(9 + 4\sqrt{5})^n - (9 - 4\sqrt{5})^n}{2\sqrt{5}} (4)$
Equations (35,36) from Pell's equation on Wolfram
I wrote a small Python program to calculate 30 solutions. However, the first 12 solutions are correct then all others are incorrect.
import math
def pell(u,v,D,nMaxUpperBound=30):
    lstResult = []
    a = u + v*math.sqrt(D)
    b = u - v*math.sqrt(D)
    for i in range (1, nMaxUpperBound, 1) :
        k = int(round((math.pow(a, i) + math.pow(b, i))/2))
        z = int(round((math.pow(a, i) - math.pow(b, i))/(2 * math.sqrt(D))))
        if k**2 - D*z**2 == 1:
            lstResult.append((k,z))
        else:
            print("failed. i = ", i, "k,z => (%d,%d)" % (k,z))
    return lstResult
lstResult = pell(9, 4, 5)
print(lstResult)

What should I do to improve the program or use a different approach to calculate all 30 solutions?
Answer: Floating point precision is not sufficient for the larger solutions.  You should probably look at using a recursive definition for the $k_n$ and $z_n$.  They should satisfy $a_{n+2}=18a_{n+1}-a_{n}$ (derived from the minimum polynomial of $9\pm4\sqrt{5}$).  Try to find a tail recursive solution, and you shouldn't run into problems until you overflow the ints.
Comment: Python converts from normal ints to arbitrary precision ints when required, so overflow is not a problem.  One can keep going this way until running out of time or memory.
Comment: Let $\alpha = 9+4\sqrt{5}$ then it's "conjugate" is $\tilde \alpha = 9-4\sqrt{5}$  They are roots of the equation with coefficient of the middle term equal to $-(\alpha + \tilde \alpha) = -18$ and constant term equal to $\alpha \cdot \tilde \alpha = 1$, so $x^2-18x+1$  This comes from multiplying out $(x-r_1)(x-r_2)$.
Comment: @RossMillikan thanks for the tip.
Comment: How to explain why minimum polynomial of $9+/-4\sqrt{5}$ equals 18?
Comment: Or, Cayley Hamilton, where $18$ is the trace of $$ \left( \begin{array}{cc} 9 & 20 \\ 4 & 9\end{array} \right) $$
Answer: One problem is that round-off error will gradually wreak havoc on any floating-point computation using $\sqrt{D}$. A surer way to generate solutions is to use Python's arbitrarily-long integers and do integer arithemetic, looking at the integer-coefficient recursion for the (integer!) coefficients of powers $(a+b\sqrt{D})^n$.
Comment: @AlexGawkins, but that does not overcome the general problem, namely, that things like $\sqrt{D}$ have no exact _finite_ decimal expression. That is, _any_ choice of finite decimal expansion will eventually have blow-up of error. There's just no numerical way to make computations with irrational numbers precise. Symbolic, yes. Or, often, the easier way is to convert the issues to (infinite-precision, but always finite, at every particular moment!) _integer_ arithmetic.
Comment: I used [Decimal Python package](https://docs.python.org/3.6/library/decimal.html). Results are the same. It failed after 12th solution.
Answer: Any formula of the form $a_n=cx^{n}+dy^{n}$ can be computed recursively as:
$$a_{n+1}=(x+y)a_n - xya_{n-1}$$ if you know $a_0,a_1$.
In your case, you've got $x,y=9\pm 4\sqrt{5}$, and $x+y=18$, $xy=1$.
So you have $k_0=1,k_1=9,z_0=0,z_1=4$:
$$k_{n+1}=18k_n-k_{n-1}\\z_{n+1}=18z_n-z_{n-1}$$
If you only want to compute one pair, $(k_n,z_n)$ you can compute this in $O(\log n)$ time by computing:
$$\begin{pmatrix}0&1\\
-1&18
\end{pmatrix}^{n-1}\begin{pmatrix}1&0\\
9&4\end{pmatrix}=\begin{pmatrix}k_{n-1}&z_{n-1}\\k_{n}&z_{n}\end{pmatrix}$$
The reason this is an $O(\log n)$ operation is that you can apply exponentiation by squaring. to raise the matrix to the $n$th power.
But if you need all values $k_1,\dots,k_n$ and $z_1,\dots,z_n$, you'll of course require $O(n)$ time (you can't compute a list of $2n$ values in less than $O(n)$ time, after all.)

Another matrix approach, probably more direct, is to note that $$k_{n+1}+z_{n+1}\sqrt{5}=(k_n+z_n\sqrt5)(9+4\sqrt{5})=(9k_n+20z_n)+(4k_n+9z_n)\sqrt{5}$$
So we can write:
$$\begin{pmatrix}k_n\\z_n\end{pmatrix}=\begin{pmatrix}9&20\\4&9\end{pmatrix}^n\begin{pmatrix}1\\0\end{pmatrix}$$
Again, exponentiation by squaring allows $O(\log n)$ time calculation. (It might be closer to $O(\log^2 n)$ in both cases because of the number of bits in the integer multiplications, but still much better than $O(n)$.)
Answer: I also found recursive solution at Additional solutions from the fundamental solution
$\displaystyle x_{k}+y_{k}{\sqrt {D}}=(x_{1}+y_{1}{\sqrt {D}})^{k}(1)$
that led them to $ \displaystyle x_{k+1}=x_{1}x_{k}+Dy_{1}y_{k} (2)$
and $\displaystyle y_{k+1}=x_{1}y_{k}+y_{1}x_{k} (3)$
First of all let's proof (1)
To do this I shall use equation from my question
$k_n = \dfrac{(p + q\sqrt{D})^n + (p - q\sqrt{D})^n}{2} ;
 z_n = \dfrac{(p + q\sqrt{D})^n - (p - q\sqrt{D})^n}{2\sqrt{D}} (3)$
Equations (35,36) from Pell's equation on Wolfram or see (31,32) on the same page in Wolfram.
Calculate $k_n+z_n\sqrt{D} = \dfrac{(p + q\sqrt{D})^n + (p - q\sqrt{D})^n}{2} + \dfrac{(p + q\sqrt{D})^n - (p - q\sqrt{D})^n}{2\sqrt{D}}\sqrt{D}=
\dfrac{(p + q\sqrt{D})^n + (p - q\sqrt{D})^n}{2} + \dfrac{(p + q\sqrt{D})^n - (p - q\sqrt{D})^n}{2} = \dfrac{(p + q\sqrt{D})^n + (p - q\sqrt{D})^n + (p + q\sqrt{D})^n - (p - q\sqrt{D})^n}{2} = \dfrac{2(p + q\sqrt{D})^n}{2} = (p + q\sqrt{D})^n$
What was required to prove !
Here's the proof:
From (1) for $k+1$ solutions
$\displaystyle x_{k+1}+y_{k+1}{\sqrt {D}}=(x_{1}+y_{1}{\sqrt {D}})^{k+1}=(x_{1}+y_{1}{\sqrt {D}})^{k}*(x_{1}+y_{1}{\sqrt {D}}) (4)$
First parentheses in (4) represents $k$-th solution , so (4) can be rewritten as
$\displaystyle x_{k+1}+y_{k+1}{\sqrt {D}}=(x_{k}+y_{k}{\sqrt {D}})*(x_{1}+y_{1}{\sqrt {D}}) (5)$.
Then open parentheses
$x_{k+1}+y_{k+1}{\sqrt {D}} = x_kx_1+ x_ky_1\sqrt {D}+y_kx_1\sqrt {D}+y_ky_1D(6)$
Combine similar terms
$x_{k+1}+y_{k+1}{\sqrt {D}} = (x_kx_1+y_ky_1D) + \sqrt {D}(x_ky_1+y_kx_1) (7)$
Now it is easy to see that
$ \displaystyle x_{k+1}=x_{1}x_{k}+Dy_{1}y_{k} (2)$
and
$\displaystyle y_{k+1}=x_{1}y_{k}+y_{1}x_{k} (3)$
are true.
Let's find formula expressing $x_{k+2}$ by using equations (2) and (3)
from (2) $x_{k+2}=x_{1}x_{k+1}+Dy_{1}y_{k+1} (8)$
substitute $y_{k+1}$ from (3) in (8)
$x_{k+2}=x_{1}x_{k+1}+Dy_{1}(x_{1}y_{k}+y_{1}x_{k}) (9)$
simplify (9)
$x_{k+2}=x_{1}x_{k+1}+Dy_{1}x_{1}y_{k}+Dy_{1}^2x_{k} (10)$
$x_{k+2}=x_{1}(x_{k+1}+Dy_{1}y_{k})+Dy_{1}^2x_{k} (11)$
use (2) to simplify
$x_{k+2}=x_{1}(x_{k+1}+x_{k+1}-x_{1}x_{k})+Dy_{1}^2x_{k} (12)$
$x_{k+2}=x_{1}(2x_{k+1}-x_{1}x_{k})+Dy_{1}^2x_{k} (13)$
$x_{k+2}=2x_{1}x_{k+1}-x_{1}^2x_{k}+Dy_{1}^2x_{k} (14)$
$x_{k+2}=2x_{1}x_{k+1}-x_{k}(x_{1}^2-Dy_{1}^2) (15)$
You can see that in parentheses $x_{1}^2-Dy_{1}^2$ is original Pell's equation , and it equals to 1, so
$x_{k+2}=2x_{1}x_{k+1}-x_{k} (16)$
Formula (16) for $k^2-5z^2=1$ with the first solution $\{k,z\}=\{9,4\}=\{x_1,y_1\}$ gives us a recursive family of solutions $x_{k+2}=2*9*x_{k+1}-x_{k}$
or $x_{k+2}=18x_{k+1}-x_{k}$
Let's find formula expressing $y_{k+2}$ by using equations (2) and (3)
$\text{from (3)  } y_{k+2}=x_{1}y_{k+1}+y_{1}x_{k+1} (17)$
substitute $x_{k+1}$ from (2)
$y_{k+2}=x_{1}y_{k+1}+y_{1}(x_{1}x_{k}+Dy_{1}y_{k}) (17)$
simplify
$y_{k+2}=x_{1}y_{k+1}+y_{1}x_{1}x_{k}+Dy_{1}^2y_{k} (18)$
get $x_k$ from (3) and apply it to (18)
$x_k=\frac{y_{k+1} - x_1y_k}{y_1} (19)$
$y_{k+2}=x_{1}y_{k+1}+y_{1}x_{1}(\frac{y_{k+1} - x_1y_k}{y_1})+Dy_{1}^2y_{k} (20)$
simplify (20)
$y_{k+2}=x_{1}y_{k+1}+x_{1}y_{k+1} - x_1^2y_k+Dy_{1}^2y_{k} (21)$
or
$y_{k+2}=2x_{1}y_{k+1} - y_k(x_1^2-Dy_{1}^2) (22)$
Again, you can see that in parentheses $x_{1}^2-Dy_{1}^2$ is original Pell's equation , and it equals to 1, so
$y_{k+2}=2x_{1}y_{k+1} - y_k (23)$
The updated program looks like this based on formulas (2) and (3)
def pell2(u,v,D,nMaxUpperBound=30):
    lstResult = []
    x1 = u
    y1 = v
    lstResult.append((x1,y1))
    for i in range (1, nMaxUpperBound, 1) :
        x2 = u*x1 + D*v*y1
        y2 = u*y1 + v * x1
        lstResult.append((x2,y2))
        x1 = x2
        y1 = y2
    return lstResult
lstResult = pell2(9, 4, 5)
for j in range(0, len(lstResult)):
    print(j+1, ' => ', lstResult[j])

Results:
1  =>  (9, 4)
2  =>  (161, 72)
3  =>  (2889, 1292)
4  =>  (51841, 23184)
5  =>  (930249, 416020)
6  =>  (16692641, 7465176)
7  =>  (299537289, 133957148)
8  =>  (5374978561, 2403763488)
9  =>  (96450076809, 43133785636)
10  =>  (1730726404001, 774004377960)
11  =>  (31056625195209, 13888945017644)
12  =>  (557288527109761, 249227005939632)
13  =>  (10000136862780489, 4472197161895732)
14  =>  (179445175002939041, 80250321908183544)
15  =>  (3220013013190122249, 1440033597185408060)
16  =>  (57780789062419261441, 25840354427429161536)
17  =>  (1036834190110356583689, 463686346096539499588)
18  =>  (18605234632923999244961, 8320513875310281831048)
19  =>  (333857389202521629825609, 149305563409488533459276)
20  =>  (5990827771012465337616001, 2679179627495483320435920)
21  =>  (107501042489021854447262409, 48075927731509211234387284)
22  =>  (1929027937031380914713107361, 862687519539670318898535192)
23  =>  (34615001824075834610388670089, 15480299423982556528939246172)
24  =>  (621141004896333642072282954241, 277782702112146347202007895904)
25  =>  (11145923086309929722690704506249, 4984608338594651693107202880100)
26  =>  (200005474548682401366360398158241, 89445167392591584128727643945896)
27  =>  (3588952618789973294871796462342089, 1605028404728053862623990388146028)
28  =>  (64401141663670836906325975923999361, 28801066117712377943103099342682608)
29  =>  (1155631597327285091018995770169646409, 516814161714094749113231797780140916)
30  =>  (20736967610227460801435597887129636001, 9273853844735993106095069260699853880)

Questions?
Comment: Proof is simply by definition of the $k$-th power. Are you sure you can't get it by yourself? =)

First 30 solutions of Pell's equation.


Alterar value de um select no CakePHP

Question: Estou fazendo um sistema, e tem uma parte dele que precisava de um select. Os nomes dentro do select estão sendo exibidos, mas os dados gravados no banco (mysql) são relativos ao campo 'id', e preciso que seja gravado os do campo 'nome' da tabela 'ops' no campo 'operacao' da tabela 'fichas'.
Relacionamentos:
public $hasMany = array(
    'Op' => array(
        'className' => 'Op',
        'foreignKey' => 'ficha_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => 'operacao',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''

public $belongsTo = array(
    'Ficha' => array(
        'className' => 'Ficha',
        'foreignKey' => 'ficha_id',
        'conditions' => '',
        'fields' => 'operacao',
        'order' => ''

Procurei e até agora não encontrei como alterar os 'values' gerado pelo CakePHP.
Estrutura das tabelas:
fichas: id, funcionario, ordem_servico, operacao, inicio, final, contagem, ops_id
ops: id, nome, sigla, ficha_id, operacao
(o campo 'operacao' em 'ops' tive que criar em função da relação entre as tabelas).
Comment: Lendo a documentação acredito que pode ser feito isso:

$options = array("one" => 'one', "two" => 'two);
$this->Form->select('Model.field', $options));

No indice do array você define o value que você deseja, espero que seja isso, nunca utilizei o cakephp
Answer: Dentro do seu model ops, atribua a seguinte variável:
public $displayField = 'nome';

E o próprio cake vai ajustar para o select exibir os nomes corretamente...
Fonte: http://book.cakephp.org/2.0/en/models/model-attributes.html#displayfield
Update:
É necessário efetuar os relacionamentos corretamente para o método find() buscar as associações a apresentá-las corretamente.
Para o Model buscar seus associados corretamente, também é necessário setar o nível de recursão da operação de busca através do atributo de models $recursive.
http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
Neste caso sugiro utilizar o nível 0, por padrão o cake utiliza -1.
Obs: Quanto maior o nível de recursão, mais dados o cake vai trazer do bd, e consequentemente, mais lento o processo.
Recursão para todos os Models, declarado no escopo da classe AppModel(Não recomendado):
public $recursive = 0;

Setando apenas no escopo do método(recomendado) que deseja a recursão, ou para o model Ficha, declarando no escopo da classe:
public $this->Ficha->recursive = 0;

Após definir a recursão desejada, você vai efetuar o find:
$resultado = $this->Ficha->find('all');

O find vai trazer para você além dos dados do model 'Ops', também os dados dos associados definidos como $hasOne, $belongsTo, $hasMany e HABTM.
Para exibir os resultados do método, passe a variável resultado para sua View:
$this->set(compact('resultado'));

ou
$this->set('resultado', $resultado);

Você vai obter um array indexado na sua view.
Para verificar a estrutura do array, faça um debug do array dentro da view, e mostrará todos os dados que o find trouxe, do model Ficha e do model Associado Op.
<?php
    pr($resultado);

A partir disto, você separa todos os campos, como estão exibidos no array, como neste exemplo:
echo $resultado['Op']['nome'];

Comment: Não sei o que estou fazendo errado, mas tá dando erro no campo que deveria ser mostrado: Notice (8): Undefined index: Op [APP/View/Fichas/index.ctp
Comment: Você fez o `pr($resultado)`? Ele mostra a estrutura do array, e aí você checa se os índices estão corretos, também remova os campos ´fields´ dentro dos relacionamentos, ele vai restringir a busca somente aos campos que você definir alí.
Comment: Você chegou a fazer o tutorial do cakephp? Ele aborda todas estas questões, fica mais fácil compreender como funciona a lógica do cakephp.
Comment: O campo operação (que é o problemático) continua aparecendo o id. Sobre o tutorial, cai meio que de paraquedas no cakephp e fiz o suficiente para começar a minha aplicação, já que meu prazo não é muito longo para finalizar
Comment: Posta na sua pergunta, a estrutura das tabelas, acho que está com problemas na modelagem também. O cakePHP é bem chato quanto a isto, precisa seguir as convenções, e se você não concluir o tutorial, é bem complicado de terminar esta aplicação.
Comment: Eu fiz o tutorial do blog, mas já tentando adaptar para a minha aplicação.
Answer: Opa, demorei porque tinha largado essa parte, mas voltei e consegui. Na verdade, minhas relações estavam invertidas, o que eu demorei pra entender.
public $hasOne = array(
    'Ficha' => array(
        'className' => 'Ficha',
        'foreignKey' => 'operacao',
        'conditions' => '',
        'fields' => 'operacao',
        'order' => ''
    )
);
public $belongsTo = array(
    'Op' => array(
        'className' => 'Op',
        'foreignKey' => 'operacao',
        'dependent' => false,
        'conditions' => '',
        'fields' => 'nome',
        'valueField' => 'nome',
        'order' => '',
        'limit' => '',

    )
);

E a view ficou:
<?php echo h($ficha['Op']['nome']); ?>

Alterei o campo 'forenigKey' para 'operacao', pois era o campo que me interessava ser exibido.
Na verdade, não alterei o valor do select, que continua sendo gravado no banco o campo 'id'. Porém, a saída na view mostra o nome da operação e era essa a informação que precisava.
Mas enfim, está resolvido e funcionando. Obrigado pelas dicas.
Comment: Que bom cara, o que houve com sua conta?
Comment: Você é o autor da pergunta? De qlqr forma, poderia explicar o que quis dizer com "as relações estavam invertidas"? Não ficou claro para mim.
Comment: Bom dia. Sendo mais claro sobre como resolvi, as minhas relações entre tabelas estavam invertidas.
public $hasOne = array(
  'Ficha' => array(
   'className' => 'Ficha',
   'foreignKey' => 'operacao',
   'conditions' => '',
   'fields' => 'operacao',
   'order' => ''
  )
 );
public $belongsTo = array(
  'Op' => array(
   'className' => 'Op',
   'foreignKey' => 'operacao',
   'dependent' => false,
   'conditions' => '',
   'fields' => 'nome',
                        'valueField' => 'nome',
   'order' => '',
   'limit' => '',

  )
 );
e a view ficou:
Comment: Aterei o campo 'forenigKey' para operação, pois era o campo que me interessava ser exibido.
Na verdade, não alterei o valor do select, que continua sendo gravado no banco o campo 'id'. Porém, a saída na view mostra o nome da operação e era essa a informação que precisava.
Sobre a minha conta, não sei o que aconteceu. A senha não entrava, solicitei para alterar e acredito que tenha sido criada uma conta nova.
Comment: Foi criada uma conta nova porque o seu outro usuário [não era registrado](http://meta.pt.stackoverflow.com/questions/1463/o-que-significa-usu%C3%A1rio-n%C3%A3o-registrado). Solicitei ao nosso gerente de comunidade que mescle suas duas contas ok?
Comment: Obrigado @bfavaretto

Alterar value de um select no CakePHP


Let $a,b \in {\mathbb{Z_+}}$ such that $a|b^2, b^3|a^4, a^5|b^6, b^7|a^8 \cdots$, Prove $a=b$

Question: Let $a,b \in {\mathbb{Z_+}}$ such that $$a|b^2,  b^3|a^4, a^5|b^6, b^7|a^8 \cdots$$
Prove $a=b$
Comment: Show that if $aa^{n+1}$ for large values of $n$.
Answer: consider the prime factorisations of $a = \prod_p p^{\nu_p(a)}$ and $b = \prod_p p^{\nu_p(b)}$. Your assumptions yield

$\nu_p(a) \le \nu_p(b^2) = 2\nu_p(b)$ for each $p$
$3\nu_p(b) \le 4\nu_p(a)$
$\ldots$
$(4n+1)\nu_p(a) \le (4n+2)\nu_p(b)$ for each $p$, $n$
$(4n+3)\nu_p(b) \le (4n + 4)\nu_p(a)$, each $p$, $n$

So we have for each $p$, $n$
$$
  \frac{4n + 3}{4n+4} \cdot \nu_p(b) \le \nu_p(a) \le \frac{4n+2}{4n+1}\nu_p(b)
$$
letting $n\to \infty$ yields $\nu_p(a) = \nu_p(b)$ for each $p$, so $a = b$.
AB,
Answer: If $a > b$ then $\frac{a}{b}>1$ and hence there is an $n$ such that $\left(\frac{a}{b}\right)^n > b$, thus $a^n > b^{n+1}$. This contradicts $a^{4k+1} | b^{4k+2}$. The case $a<b$ works in just the same way.
Comment: I like that this solution makes it clear that divisibility is a red herring---the problem would work just as well with the much weaker hypothesis that $a \leq b^2$, $b^3 \leq a^4$, etc., for real values of $a$ and $b$.
Comment: @Dan Divisibility isn't necessarily a red herring, since the proof I gave employs divisibility, and it works in rings where the (archimedean) order-based proofs do not apply, e.g. the Gaussian integers $\mathbb Z[i]$ or the ring of integers of any (complex) algebraic number field.
Answer: Let $p$ be a prime, and suppose $p^7$ divides $a$, but $p^8$ doesn't. Then from $a^9\mid b^{10}$ you can deduce $p^7\mid b$ (why?). Now if $p^8\mid b$, then from $b^{11}\mid a^{12}$ you would get $p^8\mid a$ (why?), contradiction. So same power of $p$ divides $a$ and $b$.
Can you see how to generalize this argument?
Answer: Hint $\rm \ \forall n\in\mathbb N:\ \ a\:\!\left(\dfrac{a}b\right)^{4n+3}\!\in\mathbb Z,\:\ b\:\!\left(\dfrac{b}a\right)^{4n+1}\!\in \mathbb Z\ \ \Rightarrow\  \dfrac{a}b,\:\dfrac{b}a\in\mathbb Z\ \ \Rightarrow\ \ a = \pm b\ \ \ $ QED
Remark $\ $ This is true far more generally. Suppose $\rm\:D\:$ is any Noetherian integrally closed domain, e.g. any PID. Suppose that $\rm\:w\:$ is a fraction over $\rm\:D\:$ such that some unbounded sequence of powers of $\rm\:w\:$ has a common denominator $\rm\:0 \ne d\in D,\:$ i.e. $\rm\:d\!\:w^{n_i}\in D\:$ for all $\rm\:n_i.\:$ Then $\rm\:w\in D.$
Proof $\ $ By ACC the sequence of ideals $\rm (d, dw^{n_1}, dw^{n_2},\ldots)$ eventually stabilizes, which implies that for some $\rm\:k\:$ we have $\rm\: dw^{n_k}\in (dw^{n_{k-1}},\ldots, dw^{n_1}, d),\:$ which implies
$$\rm d\: w^{n_k} + c_{n_{k-1}} d\: w^{n_{k-1}} +\:\! \cdots +\: c_{n_1} d\: w^{n_1} + d\: =\: 0$$
Cancelling $\rm\:d\:$ yields $\rm\:w\:$ is integral over $\rm\:D,\:$ hence $\rm\:w\in D,\:$ since $\rm\:D\:$ is integrally closed. $\ $ QED
Fractions whose powers have such a common denominator are called almost integral. It is clear that integral elements are almost integral. By above  the converse is true in Noetherian domains.


How can you add the ID to the content type fields?

Question: All I see are classes, and from my understanding seems that there is nothing in the variables.
Answer: By default template_preprocess_field doesn't initialize the attributes array, so you don't see it when viewing the variables with the Devel module. You can achieve this and any other attributes by adding it in a template_preprocess_field() from your themes template.php file. When added it will get output to the field in template_process_field(). Here's a generic example of adding an attribute to a field. Swap all caps items for your use case...
<code>/**
 * Implements hook_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
  $content_type = $variables['element']['#bundle'];
  $view_mode = $variables['element']['#view_mode'];
  $field_name = $variables['element']['#field_name'];

  switch ($field_name) {
    // We make sure it only effects the correct field ...
    case 'FIELD_MACHINE_NAME':

      // ... and, assuming you want to limit the where an id is used, we only add on a certain content type's full node page.
      if ($view_mode === 'full' && $content_type === 'CONTENT_TYPE_MACHINE_NAME') {
          $variables['attributes_array']['id'] = 'my-id';
      }
      break;
  }
}
</code>
Comment: Thank you. Am I right in understanding I have to do the switch/break cycle for all my fields? Any way to address all fields in the specific content type at once? No problem in doing as you suggested, but I have 30+ fields to address. I'll try this tomorrow, please be patient for I'll report back.
Comment: Great, I had no doubts about it working, just repeated the case/break snip for all my fields.
Comment: You could change the switch to test for the `$content_type` variable, change the case to the content type machine name and remove the content type check within the case statement. That would allow this code to run on every field at once. In that case you would want a more programatic way of assigning an ID, like using the field's css name...           `$variables['attributes_array']['id'] = $variables['field_name_css'];`
... A couple huge notes on this. One, if a field shows up twice on a page you'll have invalid html. Two, ID's are for javascript hooks. Use the class for styling.
Comment: Thank you. I am using the IDs for anchors inside the page. I have done most of the fields with the single switch, but I'll try your second suggestion for learning. I'm sorry I can't upvote you as I don't have enough points.


Interpretation of Adjusted Odds Ratios

Question: Hello can anyone kindly guide me about the correct way to interpret adjusted odds ratios.
I am working on a project (in SPSS) on women's autonomy and domestic violence. When I take the (simple) odds ratios then women's non-participation in health decisions, mobility and household decisions is significantly related to experiencing domestic violence. (women's age, education level and wealth quintile are also significantly related to domestic violence)
Yet, when I control for women's age, education level and wealth quintile, only the non participation in household decisions is now significantly related to experiencing domestic violence. How do I interpret the change in results since the other two types of decision  are now no longer significantly related to experiencing domestic violence?
Comment: This is a FAQ (or a combination of FAQs). For the interpretation of odds ratios, see [here](http://stats.stackexchange.com/a/34638/7290); for how p-values change when you add variables (ie become non-sig), see eg [here](http://stats.stackexchange.com/q/14500/7290); for more on the underlying issue, see [here](http://stats.stackexchange.com/a/58712/7290) & [here](http://stats.stackexchange.com/a/78830/7290).
Answer: First, don't emphasize the difference between significant and not-significant.  Look at effect sizes.
Second, the simple odds ratio is (like it says) a ratio of odds. So, the odds of a woman participating in health decisions is significantly different for women who experience domestic violence and those who do not.
The adjusted odds ratio is the same thing, only it holds the other variables (age, education, wealth quintile) constant.
Comment: Thank you for the answer. In terms of effect sizes, the (simple) odds ratios for experiencing domestic violence are 1.192, 1.269 and 1.277 for non-participation in the three types of decision making. Are these moderate or weak effects?
Comment: Whether they are weak or strong depends on the field and its standards.  What have other people found for similar questions?

Interpretation of Adjusted Odds Ratios


Is $S{(x)}$ will uniformly convergent on $[-1,1]$ ? True/false .

Question: Is $S(x) = \sum_{n=1}^{\infty} x^2 (1-x^2)^{n-1}$  will  uniformly convergent on $[-1,1]$ ?  True/false .
My attempt  : Yes ,  $S_n$ will uniformly convergent on $[-1,1]$ if i put $x = \frac{1}{\sqrt n}$ then by $M_n$ Test $||f||_{ \infty}=  \lim_{n\rightarrow \infty}\frac{1}{n} (\frac{ n-1}{n})^{n-1}= \lim_{\rightarrow \infty} \frac{1}{n} \frac{1}{e}=0$
Is its True ?
Any hints/solution will be appreciated
thanks u
Comment: While the answer below settles the issue, computing the series by hand is trivial and gives a discontinuous function at $0$ so obviously we cannot have uniform convergence on any interval containing it
Comment: But $\sum_n 1/\sqrt n$ doesn't converge...
Comment: Perhaps you meant to write $S(x) = \sum_{n = 1}^\infty x^2(1 - x^2)^{n-1}$? Or $S_k(x) = \sum_{n = 1}^k x^2(1 - x^2)^{n-1}$?
Comment: Are you sure you quoted the question correctly? It makes little sense to write $S_n$ for a sum that doesn't depend on $n$ (because you're summing over all $n$) but does depend on $x$. Also, I don't see what your attempt (plugging in an arbitrary-looking value of $x$ that depends on $n$ and is therefore different for every term in the sum) has to do with the question, nor do I see what either @Math1000's comment or your comment has to do with your attempt.
Comment: Hint: The sum is a geometric series, so you can explicitly evaluate it in closed form. Note though that you have to treat $x=0$ differently from all the non-zero $x$'s.
Comment: @Math1000  but  domain is  $[-1,1]$
Comment: @kobe u gots  the  logic     as  I was writing $S(x)$
Comment: @AndreasBlass  i have  edited
Answer: Note that
$$\sup_{x \in [-1,1]}\left|\sum_{k=n+1}^\infty x^2(1-x^2)^{k-1}\right| \geqslant \sup_{x \in [-1,1]}\sum_{k=n+1}^{2n} x^2(1-x^2)^{k-1} \geqslant \sup_{x \in [-1,1]}nx^2(1-x^2)^{2n} $$
Take $x^2 = 1/(2n)$, that is $x = \pm1/\sqrt{2n} \in [-1,1]$, and it follows that
$$\sup_{x \in [-1,1]}\left|\sum_{k=n+1}^\infty x^2(1-x^2)^{k-1}\right| \geqslant \frac{1}{2}\left(1 - \frac{1}{2n}\right)^{2n}$$
Since the limit of the RHS as $n \to \infty$ is $e^{-1}/2 \neq 0$ the convergence is not uniform on $[-1,1]$.
Comment: @jasmine:  Suppose the series is pointwise convergent as $\sum_{k=1}^\infty f_k(x) = S(x)$ for $x \in I$.  That means for each fixed $x$, $S_n(x) = \sum_{k=1}^n f_k(x)  \to S(x)$ as $n \to \infty$.  For uniform convergence we must have $\sup_{x}|S_n(x) - S(x)| \to 0$ as $n \to \infty$.  But $|S_n(x) - S(x)] = \sum_{k= n+1}^\infty f_k(x)$ -- which is the tail of the series.
Comment: @jasmine: You're welcome.
Comment: thanks @RRL but im not  getting why  u take $k= n+1 $?  as  according to the  question  its is given that $ k = 1$ to $\infty$
Comment: thanks  u @RRL got its


How to access file system using Intel XDK app?

Question: I am creating an app using Intel XDK, in HTML5 and javascript, and write some of the data fed by user to the local file system. How can I do this?
Comment: Can you please elaborate more on what actually you trying to to.
Answer: The Intel XDK supports Cordova 2.9.0 at the time of this writing. See this thread on the XDK forum for a link and a few hints:
https://forums.html5dev-software.intel.com/viewtopic.php?f=34&t=4892&p=18121&hilit=local+filesystem#p18121
Comment: An example of how to do that would be nice
Answer: You may have solved the problem. this is for people who are new and run into this thread. you can use cordova-plugin-file to manage with file system.


can someone advice a simple documentation on how to configure email server

Question: I'm new to all this stuff.
There's some documents on my server. A user send email on e.g firstname.lastname@example.com and one of document's must be changed(the way it's to be changed is specified in the email). So, first I need is to rise up a email server. Can someone advice me a simple manual on how to configure a email server? For now I don't need something extra-cool, just email-server(as simple as possible) which will be able to recieve email, and there must be an oppotunity e.g. launch .sh script to change documents when a email recieved.
Answer: shortest possible [for debian-ish distributions]
install postfix
apt-get install postfix

in /etc/postfix/main.cf include:
mydestination=your.domain.com

in /etc/aliases:
accountName: "|/some/command/that/will/receive/email/on/stdin.sh"

Comment: thanks for answering. where recieved emails will be stored?
Comment: @Eugeny89 wherever you decide to store them - in such case your script needs to take care of that.
Answer: There is no 'simple' way to setup an email server.
Assuming you already have a functioning email system that the your server could potentially connect to and your server is not yet configured to route/fetch emails via the existing service - that's a different question - and it only needs an email client - not a server.
You've not provided any information about the constraints and objectives. e.g. what OS is on the server you are trying to send emails from? What languages do you have available? Why do you need an email server rather than just a client?
Depending on the answers to these the answer might be as simple as fetchmail+procmail or a PHP/Perl script.


domToPdf is blank

Question: I am using the dom-to-pdf library, repository here: https://github.com/ovvn/dom-to-pdf
I have the following method that:

Hits the server for data
Dynamically builds a variable based on that data
Call domToPdf to print the DOM

The component's HTML layer uses *ngFor to dynamically populate the DOM based on the variable is step 2.
This is my method:
generateReport(): void {
  let bloodPressureFilter = `${this.bloodPressure.readDateFrom ? `ReadDate_GreaterEqual=${encodeURIComponent(this.datePipe.transform(this.bloodPressure.readDateFrom, 'YYYY-MM-dd'))}` : ''}`;
  bloodPressureFilter = `${bloodPressureFilter ? '&' : ''}${this.bloodPressure.readDateTo ? `ReadDate_LessEqual=${encodeURIComponent(this.datePipe.transform(this.bloodPressure.readDateTo, 'YYYY-MM-dd'))}` : ''}`;
  let sugarFilter = `${this.sugar.readDateFrom ? `ReadDate_GreaterEqual=${encodeURIComponent(this.datePipe.transform(this.sugar.readDateFrom, 'YYYY-MM-dd'))}` : ''}`;
  sugarFilter = `${sugarFilter ? '&' : ''}${this.sugar.readDateTo ? `ReadDate_LessEqual=${encodeURIComponent(this.datePipe.transform(this.sugar.readDateTo, 'YYYY-MM-dd'))}` : ''}`;
  let weightFilter = `${this.weight.readDateFrom ? `ReadDate_GreaterEqual=${encodeURIComponent(this.datePipe.transform(this.weight.readDateFrom, 'YYYY-MM-dd'))}` : ''}`;
  weightFilter = `${weightFilter ? '&' : ''}${this.weight.readDateTo ? `ReadDate_LessEqual=${encodeURIComponent(this.datePipe.transform(this.weight.readDateTo, 'YYYY-MM-dd'))}` : ''}`;
  forkJoin({
    bloodPressures: this.bloodPressureService.query(bloodPressureFilter),
    sugars: this.sugarService.query(sugarFilter),
    weight: this.weightService.query(weightFilter)
  }).subscribe(results => {
    this.records = [];
    const bloodPressures = this.bloodPressure.visible ? results.bloodPressures : [];
    const sugars = this.sugar.visible ? results.sugars : [];
    const weights = this.weight.visible ? results.weight : [];

    bloodPressures.forEach(bloodPressure => {
      const grouppedObject = this.records.find(record => record.entryDate === bloodPressure.ReadDate);
      if (!grouppedObject) {
        this.records.push({
          entryDate: bloodPressure.ReadDate,
          bloodPressures: [ bloodPressure ]
        });
      } else {
        grouppedObject.bloodPressures = grouppedObject.bloodPressures ?? [];
        grouppedObject.bloodPressures.push(bloodPressure);
      }
    });
    sugars.forEach(sugar => {
      const grouppedObject = this.records.find(record => record.entryDate === sugar.ReadDate);
      if (!grouppedObject) {
        this.records.push({
          entryDate: sugar.ReadDate,
          sugars: [ sugar ]
        });
      } else {
        grouppedObject.sugars = grouppedObject.sugars ?? [];
        grouppedObject.sugars.push(sugar);
      }
    });
    weights.forEach(weight => {
      const grouppedObject = this.records.find(record => record.entryDate === weight.ReadDate);
      if (!grouppedObject) {
        this.records.push({
          entryDate: weight.ReadDate,
          weights: [ weight ]
        });
      } else {
        grouppedObject.weights = grouppedObject.weights ?? [];
        grouppedObject.weights.push(weight);
      }
    });
    const today = new Date();
    const element = document.getElementById('report');
    const options = {
      filename: `${this.datePipe.transform(today, 'yMMdhhmmssa')}.pdf`
    };
    domToPdf(element, options, () => {
      console.log('PDF exported');
      this.records = [];
    });
  });
}

And this is my component:

  <ion-card *ngFor="let record of records">
    <ion-card-header>
      <ion-card-title>{{record.entryDate | date:'MMMM d, y'}}</ion-card-title>
    </ion-card-header>
    <ion-card-content>

At {{sugar.ReadTime | date:'h:mm a'}}, I had a blood sugar reading of {{sugar.Reading}}.

At {{bloodPressure.ReadTime | date:'h:mm a'}}, I had a blood pressure reading of {{bloodPressure.Systolic}}/{{bloodPressure.Diastolic}}.

At {{weight.ReadTime | date:'h:mm a'}}, I weighed {{weight.Weight}}.

    </ion-card-content>
  </ion-card>

The issue (I think) is that because it is taking the document too long to dynamically generate the HTML it is downloading a blank PDF. The reason I say this is because if I remove the code above where I set the options and call domToPdf and replace my HTML with
TEST
 then a PDF is exported with the content.
Is there a work around so that the massaged data gets exported?
Answer: Since you are executing domToPDF immediately after the view updates, chances are the element is still blank, there are couple of options to solve this issue:

Either user Intersection Observer to check when the element you want to export to pdf is available in the dom

Try executing the domToPDF in the next tick by using setTimeout:
 setTimeout( ()=> {
    domToPdf(element, options, () => {
       console.log('PDF exported');
       this.records = [];
     });
 }, 0);

domToPdf is blank


interop.word, find and replace, erro:" O parâmetro da cadeia é muito longo."

Question: Estou usando um template para criar um documento, eu abro um documento que seria um template e uso find and replace para localizar e substituir palavras chaves que esta neste documento e logo depois salvo na minha área de trabalho como outro documento, tudo ocorre perfeitamente, mas quando eu vou tentar colocar um texto superior a 255 caracteres me deparo com este erro " O parâmetro da cadeia é muito longo." o que posso fazer? Sou um pouco leigo, se puderem postar um código que resolva meu problema eu agradeceria muito , obg desde já
private void FindAndReplace(Microsoft.Office.Interop.Word.Application wordApp, object findText, object replaceWithText)
    {

        object missing = Type.Missing;

        object matchCase = true;
        object matchWholeWord = true;
        object matchWildCards = false;
        object matchSoundLike = false;
        object nmatchAllForms = false;
        object forward = true;
        object format = false;
        object matchKashida = false;
        object matchDiactitics = false;
        object matchAlefHamza = false;
        object matchControl = false;
        object read_only = false;
        object visible = true;
        object replace = 2;
        object wrap = 1;

        object replaceText = true;

                wordApp.Selection.Find.Execute(ref findText,
                        ref matchCase, ref matchWholeWord,
                        ref matchWildCards, ref matchSoundLike,
                        ref nmatchAllForms, ref forward,
                        ref wrap, ref format, ref replaceWithText,
                        ref replace, ref matchKashida,
                        ref matchDiactitics, ref matchAlefHamza,
                        ref matchControl);

    }

    private void CreateWordDocument(object filename, object savaAs)
    {
        List<int> processesbeforegen = getRunningProcesses();
        object missing = Missing.Value;

        Word.Application wordApp = new Word.Application();

        Word.Document aDoc = null;

        if (File.Exists((string)filename))
        {
            DateTime today = DateTime.Now;

            object readOnly = false;
            object isVisible = false;

            wordApp.Visible = false;

            aDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                        ref missing, ref missing, ref missing,
                                        ref missing, ref missing, ref missing,
                                        ref missing, ref missing, ref missing,
                                        ref missing, ref missing, ref missing, ref missing);

            aDoc.Activate();

            this.FindAndReplace(wordApp, "<n>", tbPlanoNmr.Text);
            this.FindAndReplace(wordApp, "<k>", tbPortaria.Text);
            this.FindAndReplace(wordApp, "<data>", tbData.Text);
            this.FindAndReplace(wordApp, "PPPPP", tbNomeEtec.Text);
            this.FindAndReplace(wordApp, "<codigo>", tbCodigoEtec.Text);
            this.FindAndReplace(wordApp, "<municipio>", tbMunicipioEtec.Text);
            this.FindAndReplace(wordApp, "<eixo>", tbEixo.Text);
            this.FindAndReplace(wordApp, "<habilitacao>", tbHabilitacao.Text);
            this.FindAndReplace(wordApp, "<qualificacao>", tbQualificacao.Text);
            this.FindAndReplace(wordApp, "<serie>", tbModulo.Text);
            this.FindAndReplace(wordApp, "<componente>", tbMateria.Text);
            this.FindAndReplace(wordApp, "<ch>", tbCHS.Text);
            this.FindAndReplace(wordApp, "<professor>", tbNomeProf.Text);
            this.FindAndReplace(wordApp, "<modulo>", Session["modulo"].ToString());

            this.FindAndReplace(wordApp, "<VI>", txtVI.InnerText);
            this.FindAndReplace(wordApp, "<VII>", txtVII.InnerText);
            this.FindAndReplace(wordApp, "<X>", txtX.InnerText);

            foreach (GridViewRow row in GridView1.Rows)
            {
                txtDidatico.Text += ((TextBox)row.FindControl("txtProcedimento")).Text;
            }

            this.FindAndReplace(wordApp, "<procedimento>", txtDidatico.Text);

            this.FindAndReplace(wordApp, "<instrumentos>", txtInstrumentos.InnerText);
            this.FindAndReplace(wordApp, "<criterios>", txtCriterios.InnerText);

            this.FindAndReplace(wordApp, "<mes1>", mes1.InnerText);
            this.FindAndReplace(wordApp, "<mes2>", mes2.InnerText);
            this.FindAndReplace(wordApp, "<mes3>", mes3.InnerText);
            this.FindAndReplace(wordApp, "<mes4>", mes4.InnerText);
            this.FindAndReplace(wordApp, "<mes5>", mes5.InnerText);
            this.FindAndReplace(wordApp, "<mes6>", mes6.InnerText);

            this.FindAndReplace(wordApp, "<1.1>", c11.InnerText);
            this.FindAndReplace(wordApp, "<1.2>", c12.InnerText);
            this.FindAndReplace(wordApp, "<1.3>", c13.InnerText);
            this.FindAndReplace(wordApp, "<1.4>", c14.InnerText);
            this.FindAndReplace(wordApp, "<1.5>", c15.InnerText);
            this.FindAndReplace(wordApp, "<1.6>", c16.InnerText);
            this.FindAndReplace(wordApp, "<2.1>", c21.InnerText);
            this.FindAndReplace(wordApp, "<2.2>", c22.InnerText);
            this.FindAndReplace(wordApp, "<2.3>", c23.InnerText);
            this.FindAndReplace(wordApp, "<2.4>", c24.InnerText);
            this.FindAndReplace(wordApp, "<2.5>", c25.InnerText);
            this.FindAndReplace(wordApp, "<2.6>", c26.InnerText);
            this.FindAndReplace(wordApp, "<3.1>", c31.InnerText);
            this.FindAndReplace(wordApp, "<3.2>", c32.InnerText);
            this.FindAndReplace(wordApp, "<3.3>", c33.InnerText);
            this.FindAndReplace(wordApp, "<3.4>", c34.InnerText);
            this.FindAndReplace(wordApp, "<3.5>", c35.InnerText);
            this.FindAndReplace(wordApp, "<3.6>", c36.InnerText);
            this.FindAndReplace(wordApp, "<4.1>", c41.InnerText);
            this.FindAndReplace(wordApp, "<4.2>", c42.InnerText);
            this.FindAndReplace(wordApp, "<4.3>", c43.InnerText);
            this.FindAndReplace(wordApp, "<4.4>", c44.InnerText);
            this.FindAndReplace(wordApp, "<4.5>", c45.InnerText);
            this.FindAndReplace(wordApp, "<4.6>", c46.InnerText);
            this.FindAndReplace(wordApp, "<5.1>", c51.InnerText);
            this.FindAndReplace(wordApp, "<5.2>", c52.InnerText);
            this.FindAndReplace(wordApp, "<5.3>", c53.InnerText);
            this.FindAndReplace(wordApp, "<5.4>", c54.InnerText);
            this.FindAndReplace(wordApp, "<5.5>", c55.InnerText);
            this.FindAndReplace(wordApp, "<5.6>", c56.InnerText);
            this.FindAndReplace(wordApp, "<atribuicoes>", taAtribuicoes.InnerText);

            this.FindAndReplace(wordApp, "<atividades>", taAtividades.Text);
            this.FindAndReplace(wordApp, "<competencia_extenso>", txtCompetenciaExtenso.InnerText);
            this.FindAndReplace(wordApp, "<evidencias>", txtEvidencia.InnerText);
            this.FindAndReplace(wordApp, "<habilidades>", txtHabilidade.InnerText);
            this.FindAndReplace(wordApp, "<competencia>", txtCompetencia.InnerText);
            this.FindAndReplace(wordApp, "<base>", txtBase.InnerText);

            foreach (GridViewRow row in GridView1.Rows)
            {
                txtHabilidadeP33.Text += ((TextBox)row.FindControl("txtHabilidadeP3")).Text;
            }
            foreach (GridViewRow row in GridView1.Rows)
            {
                txtBaseP33.Text += ((TextBox)row.FindControl("txtBaseP3")).Text;
            }

            this.FindAndReplace(wordApp, "<basenum>", txtHabilidadeP33.Text);
            this.FindAndReplace(wordApp, "<habilidadesnum>", txtBaseP33.Text);

            this.FindAndReplace(wordApp, "#", "^l");

            //this.FindAndReplace(wordApp, "$$Date$$"     DateTime.Now.ToShortDateString());

        }
        else
        {
            //Exibir mensagem: "a dose do arquivo não existe"

            return;
        }

        aDoc.SaveAs2(ref savaAs, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing);

        aDoc.Close(ref missing, ref missing, ref missing);

        List<int> processesaftergen = getRunningProcesses();
        killProcesses(processesbeforegen, processesaftergen);
    }

    public List<int> getRunningProcesses()
    {
        List<int> ProcessIDs = new List<int>();

        foreach (Process clsProcess in Process.GetProcesses())
        {
            if (Process.GetCurrentProcess().Id == clsProcess.Id)
                continue;
            if (clsProcess.ProcessName.Contains("WINWORD"))
            {
                ProcessIDs.Add(clsProcess.Id);
            }
        }
        return ProcessIDs;
    }

    private void killProcesses(List<int> processesbeforegen, List<int> processesaftergen)
    {
        foreach (int pidafter in processesaftergen)
        {
            bool processfound = false;
            foreach (int pidbefore in processesbeforegen)
            {
                if (pidafter == pidbefore)
                {
                    processfound = true;
                }
            }

            if (processfound == false)
            {
                Process clsProcess = Process.GetProcessById(pidafter);
                clsProcess.Kill();
            }
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void tEnabled(bool state)
    {
        tbNomeProf.Enabled = state;

    }

    protected void btnGerarPDF_Click(object sender, EventArgs e)
    {
        var Template = "C:/Users/Bird/Desktop/temppp.doc";

        var NovoDocumento = "C:/Users/Bird/Desktop/PTD.doc";
        tEnabled(true);

        CreateWordDocument(Template, NovoDocumento);
        tEnabled(false);

    }
}

Comment: https://social.msdn.microsoft.com/Forums/pt-BR/09c58208-d709-42ec-adab-4b933c62a002/replacementtext-o-parmetro-de-sequncia-de-caracteres-muito-longo-?forum=clientept
Comment: Obg, consegui resolver meu problema
Comment: Coloque sua resolução como resposta, assim poderá ajudar outra pessoar que buscar pelo mesmo problema =]
Answer: eu estava usando find and replace desta forma
this.FindAndReplace(wordApp, "<texto>", texto.Text);

porem dava erro, pois a cadeia de caracteres era muito longa, então mudei para:
foreach (Word.Range tmpRange in aDoc.StoryRanges)
            {
                object findText = "<texto>";
                object replaceText = texto.Text;

                if (tmpRange.Find.Execute(ref findText, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing))
                {
                    tmpRange.Select();
                    wordApp.Selection.Text = replaceText.ToString();
                }
            }


Variance of number of heads

Question: Given two coins with chance of heads $p=0.6$ for a coin $X$, and $p=0.7$ for a coin $Y$. Pick one coin uniformly at random. Toss the coin 10 times. Find the variance $Z$ of the number of heads. I am thinking of just using the definition of variance.
$E[Z]^2 = \sum_{n=0}^{10}\frac{n}{2}\left(\operatorname{nCr}\left(10,\ n\right)\cdot\left(\frac{6}{10}\right)^{n}\left(\frac{4}{10}\right)^{10-n}+\operatorname{nCr}\left(10,\ n\right)\cdot\left(\frac{7}{10}\right)^{n}\left(\frac{3}{10}\right)^{10-n}\right) = 42.25$
$E[Z^2] = \sum_{n=0}^{10}\frac{n^{2}}{2}\left(\operatorname{nCr}\left(10,\ n\right)\cdot\left(\frac{6}{10}\right)^{n}\left(\frac{4}{10}\right)^{10-n}+\operatorname{nCr}\left(10,\ n\right)\cdot\left(\frac{7}{10}\right)^{n}\left(\frac{3}{10}\right)^{10-n}\right) = 44.75$
$Var[Z] = 2.5$
But is there a faster, cleaner way without all this computation?
Answer: your calculations are correct!. To use a shortcut, observe that
Z probability function, using total probability theorem, is the following
$$\mathbb{P}[Z=z]=\frac{1}{2}\mathbb{P}[Z=z|p=0.6]+\frac{1}{2}\mathbb{P}[Z=z|p=0.7]$$
Now observe that the second simple moment for a binomial $B(n;p)=np(1-p)+(np)^2$
Thus the variance is
$$\mathbb{V}[Z]=\mathbb{E}[Z^2]-\mathbb{E}^2[Z]=0.5[(2.4+6^2)+(2.1+7^2)]-[0.5(6+7)]^2=2.5$$
Answer: You can use the law of total variance.  Let $C$ be a random variable which equals $0$ if coin $X$ is chosen and equals $1$ if coin $Y$ is chosen.  Then $Z|C=0$ has the distribution Bin$(10,0.6)$ and $Z|C=1$ has the distribution Bin$(10,0.7)$.  So the random variable $\mathbb{E}[Z|C]$ takes the values $10 \cdot 0.6 = 6$ and $10 \cdot 0.7 = 7$ with probability $1/2$ each, and the random variable $\operatorname{var}(Z|C)$ takes the values $10 \cdot 0.6 \cdot 0.4$ and $10 \cdot 0.7 \cdot 0.3$ with probability $1/2$ each.
Therefore we can calculate
$$
\operatorname{var}(Z) = \mathbb{E}[\operatorname{var}(Z|C)] + \operatorname{var}(\mathbb{E}[Z|C]) = \frac12( 10 \cdot 0.6 \cdot 0.4 + 10 \cdot 0.7 \cdot 0.3) + \frac14 = 2.5
$$

Variance of number of heads


Android Eclipse Hanging

Question: I'm trying to get the ADT working in Eclipse, but I'm getting random hangs where eclipse just locks for no apparent reason, usually requiring a 'killall java' to properly clean it out of the memory.
I'm on Ubuntu 10.4 (64bit)
Here's the details of my eclipse/android install:
eclipse Version: 3.5.2
Build id: M20100211-1343
Android Development Tools 0.9.8.v201008281755-53891 com.android.ide.eclipse.adt.feature.group
Android DDMS 0.9.8.v201008281755-53891 com.android.ide.eclipse.ddms.feature.group
Here's the output from java -version :
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)
I often don't get anything in the workspace logs, but here's an example of what appeared after Eclipse hung just now :
!ENTRY org.eclipse.core.resources 8 2 2010-09-21 10:22:27.407
!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.core.resources".
!STACK 1
org.eclipse.core.runtime.CoreException: Project target not resolved yet.
 at com.android.ide.eclipse.adt.internal.build.BaseBuilder.stopBuild(Unknown Source)
 at com.android.ide.eclipse.adt.internal.build.BaseBuilder.abortOnBadSetup(Unknown Source)
 at com.android.ide.eclipse.adt.internal.build.PreCompilerBuilder.build(Unknown Source)
 at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:627)
 at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
 at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:170)
 at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:201)
 at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:253)
 at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
 at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:256)
 at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:309)
 at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:341)
 at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:140)
 at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:238)
 at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
!SUBENTRY 1 com.android.ide.eclipse.adt 8 0 2010-09-21 10:22:27.407
!MESSAGE Project target not resolved yet.
!SUBENTRY 1 com.android.ide.eclipse.adt 8 0 2010-09-21 10:22:27.407
!MESSAGE Project target not resolved yet.
There were two of these entries - identical except for the timestamps.
I've tried just about every version of eclipse I can download, I've tried tying adt to sdk 1.6 r1, r2 and r3.
Anyone got any ideas?  I'm at my wits end here.  Eclipse is fairly solid for me using other plugins - C/C++, PyDev, PHP, Web stuff all work fine, but as soon as I try using the android plugin I start hanging. I've disabled code completion, in case it was that, but nope, whatever I seem to do, I get a couple of lines typed then everything goes grey.
Answer: I've had this happen due to a corrupt Eclipse workbench.  In particular, I've seen Eclipse hang while loading com.android.ide.eclipse.adt configuration.
First, I tried deleting com.android.ide.eclipse.adt from my workspace/.metadata/.plugins, but that did not do the trick.
However, deleting org.eclipse.ui.workbench from workspace/.metadata/.plugins seems to have done the trick.
Seems like the workbench configuration is getting corrupted somehow.  So, try this guys:
rm /path_to_workspaces/workspace/.metadata/.plugins/org.eclipse.ui.workbench
-fr
Seems to have fixed the problem for me now, and I believe this was the same solution I came up with when I had the same problem 2 years ago ( but just now found this question on SO)
Answer: I prefer one eclipse installation for each programming language/language pack. Java + Android, Php + Web (HTML, JS...), Python... Maybe ADT isn't really compatible to one of your installed plugins. Try to use a separate eclipse installation/instance
Comment: Actually that's where I've ended up due to this problem.  A separate eclipse with it's own workspace for each language/client.  It's a much better state of affairs than the mess I had before.  Didn't solve the android hang though :-(
Comment: Sorry for not closing this question sooner - work got in the way of play!  I ended up re-visiting this recently, on a new OS and the problem is no longer there.  Unfortunately I didn't manage to discover why I was crashing, so no help for anyone else suffering a similar problem... Sorry!
Answer: Recently this problem keeps cropping up too.  I usually solve it by
1. Renaming org.eclipse.core.resources(in your *currently active workspace folder*/.metadata/plugins folder)  to something like org.eclipse.core.resources.old
2. Kill eclipse task if it is still hung in memory
3. Start eclipse, it should start fine and create org.eclipse.core.resources again
4. Close eclipse
5. Delete the newly created org.eclipse.core.resources folder and rename org.eclipse.core.resources.old to org.eclipse.core.resources
6. Start eclipse again.

This has worked for me

Android Eclipse Hanging


Evento "append" no carregamento da página

Question: Nesse trecho de código, a div1 é posicionada na div2 quando se clica nela, mas eu queria que isso fosse feita de forma automática no carregamento da página sem que seja necessário clicar nela.
Já tentei substituit o evento .click por .load ou .ready mas não dá.
jQuery(function ($) {

    $('#DIV1').click(function () {

        $('#DIV2').append(this);

    });
});

Answer: Deve fazer assim:
jQuery(function ($) {
    $('#DIV2').append($('#DIV1'));
});

No código que tinha, this era um ponteiro para o elemento clicado, ou seja $('#DIV1'). E quando o clic surgia a div2 recebia por append o this.
Comment: Cara, muito obrigado. Quebrei tanto a cabeça com isso já. Funcionando certinho!


VPC for a three-level logistic regression

Question: I am building a mixed effects logistic regression model to explore whether or not someone is diagnosed late with a specific infectious disease. My outcome is late diagnosis (yes/no). My data includes a number of patient-level predictors (e.g., age, sex, route of transmission, etc.) as well as data on the clinic where they were diagnosed (level 2) and the local authority (similar to US county) which funds the clinic (level 3).
In addition to my fixed patient-level effects, I would like to determine whether there is any explanatory power added by including clinic and/or local authority as random effects. I am aware of LR tests and AIC/BIC but would also like to look at VPC.
Does anyone know if the latent variable approach proposed here would also work for a three-level logistic regression model?
That is, if I included both clinic and local authority as random effects, could I then assess the VPC of level 3 as: level 3 variance / (lvl 3 variance + lvl 2 variance + 3.29)?
Answer:
Does anyone know if the latent variable approach proposed here would also work for a three-level logistic regression model?

Yes, that should work. For clinics (level 2):
$$
VPC_{\text{clinic}} = \frac{\sigma^2_{\text{clinic}}}{\sigma^2_{\text{clinic}} + \sigma^2_{\text{authority}} + \frac{\pi^2}{3}}
$$
while for local authorities (level 3):
$$
VPC_{\text{authority}} = \frac{\sigma^2_{\text{authority}}}{\sigma^2_{\text{clinic}} + \sigma^2_{\text{authority}} + \frac{\pi^2}{3}}
$$


Como fazer Borda da imagem abaixo?

Question:
essa é minha primera pergunta no stackoverflow, agradeço quem me ajudar :)
Comment: Acho que esse link resolve sua dúvida https://pt.stackoverflow.com/questions/213100/colocar-texto-na-borda-div
Comment: valeu meu sonegado
Answer: HTML 4 e 5 voce pode usar <legend>:

<form>
 <fieldset>
  <legend>Exemplo:</legend>
    <input type="radio" id="A" name="rdo">
    A

    <input type="radio" id="B" name="rdo">
    B

 </fieldset>
</form>

caso contrario voce pode usar dessa forma:

.fieldset-border {
  border: 1px groove #ddd !important;
  padding: 0 1.4em 1.4em 1.4em !important;
  margin: 0 0 1.5em 0 !important;
  -webkit-box-shadow: 0px 0px 0px 0px #000;
  box-shadow: 0px 0px 0px 0px #000;
}

.fieldset-border .legend-border {
  font-size: 1.2em !important;
  text-align: left !important;
  width: auto;
  padding: 0 10px;
  border-bottom: none;
}
<fieldset class="fieldset-border">
  <legend class="legend-border">Teste</legend>
</fieldset>

Fonte

Como fazer Borda da imagem abaixo?


Can I get an estimate of the survival function from the age distribution

Question: In an industrial example, I have an age distribution of a particular component. I know the ages of the items currently in service. From this information, can I deduce the average lifespan of a component?
Can I deduce the lifespan if I make certain assumptions about, say, constant rate of arrival of new components, or a particular form to the survival function?
Answer: No. First off, if this is a cross sectional sample, you haven't sampled any of the components that failed previously, so there would be infinite survivor bias in that case. If none of the components have actually failed, at best you could provide a lower bound for the survivor distribution. An example of doing that with median unbiased estimation is given below:
Suppose I have a factory with 10 of these components, and all of them have been in service for 10 years without fail. My best estimate of the probability that a component fails in 10 years is 0. An upper bound for this probability can be obtained by using the binomial sampling probability and solving a 95% CI upper bound:
$$\text{arg max } p : Pr(X=0)/2 + Pr(X > 0) > 0.975$$
This is obtained in $R$ by:
fp <- function(p) dbinom(0, 10, p)/2 + pbinom(1, 10, p, lower.tail=T) - 0.975
pupper <- uniroot(fp, c(0, 1))$root

Gives an upper bound for the probability of 0.09. Median unbiased estimates are invariant to monotonic transforms so this can be transformed to a number of person years exposure by multiplying top by the number of components (10) and the bottom by the number of component-years (100) to get a rate of: 0.9 failures per 100 component years. And transforming this to an exponential distribution we get a survivor curve along the lines of:
curve(pexp(x, 0.09, lower.tail=F), xlab='Time', ylab='95% lower bound of survivor curve\n from median unbiased estimation', xlim=c(0, 40))


Using Google Drive API to edit other user's files

Question: I am building an app that functions as a markdown editor, and have Google authentication / login functioning. I have users asking if they can choose to have their documents save to their google drive rather than to my servers, which seems to work fine via the Google Drive v3 API, saved to the app data folder.
However, users are also able to generate a collaborator link for others to visit and which allows them to edit the files as co-owners. I would like to maintain this sharing capability with the Google Drive files, but this (very old) answer suggests that sharing in this way may not possible with files in appdata, because:

Appdata content is supposed to be exclusive to the application.

Does this mean that, as long as my users all access these files exclusively via the app, sharing appdata between users is possible? Or is the appdata folder exclusive to the application and the user? If so, is it at least possible to share editor access to google drive files created by my app but outside the appdata folder?
I'm imagining this process:

User1 creates a file in my app and then my app saves it to his Google Drive (preferably in appdata)
User1 generates a collaborator link via my app, gives it to User2
User2 visits the link which opens User1's file within my app, edits it
User2's edits are saved, and my app updates the original User1's file via the API
Answer: Question:
"Or is the appdata folder exclusive to the application and the user?"
Answer:
Yes, it is exclusive for your app on their Drive.

Notes:

Use the AppData folder for Application Data, not User Data.
If the file is created by your app, and you want to store it in the user's Drive, you can use the https://www.googleapis.com/auth/drive.file scope. You app will always have access to that file because it was created by it.
Keep in mind that if your app requires restricted scopes you will have to go through verification.


How to use outside column in subquery

Question: I have following query-
select * from
Table1 t1 , table2 t2 ,
(select idCol from table3) t3

My question is - Can I use table t2 inside subquery?
like this
select * from
Table1 t1 , table2 t2 ,
(select idCol, t2.nameCol from table3) t3

Obviously this gives error invalid identifier t2.nameCol
But if I write as follows, it give unnecessaru extra rows
select * from
Table1 t1 , table2 t2 ,
(select idCol,  t2.nameCol from table3, table2 t2) t3

any other way to do this?
EDIT
Basically what I am trying to achieve is following
select * from
Table1 t1 , table2 t2 ,
(select
    case
    when t2.nameCol = 'ABC'  then 'ABC'
    else idCol
    end idCol from table3) t3

Comment: What exactly are you trying to achieve? You're already cross joining t1, t2 and the subquery, why do you need t2's columns inside the subquery too?
Comment: @Mureinik Please see my edits
Comment: This still doesn't make too much sense to me. Could you please post your table structures, some sample data and the result you're trying to achieve?
Comment: you can use t2 in a where clause, such as `select * from
Table1 t1 , table2 t2 ,
(select idCol from table3 where t3name = t2.nameCol) t3` since t2 is already in the outer statement. you cannot list is as a field in the select part, since it is not in the from part of the inner clause.
Comment: It looks like you want a subquery in your SELECT clause rather than in your FROM clause. Well, it's hard to tell with such a mutilated query (including an out-dated join syntax that was used in the 1980s, but shouldn't be used today).
Comment: The actual table structure is big and this is just a sample structure. What I want to achieve is while getting idCol from T3, if nameCol of t2 is 'ABC' just print 'ABC' else idCol of T3.
Answer: To join a table only when certain criteria is met is called an outer join. Here is how:
select *
from table1 t1
inner join table2 t2 on <join criteria here>
left outer join table3 t3 on t2.namecol <> 'ABC' and <join criteria here>;

It may suffice in your case, however, to move the subquery to your SELECT clause:
select
  t1.*,
  t2.*,
  case when t2.namecol = 'ABC' then
    'ABC'
  else
    (select idcol from table3 t3 where <join criteria here>)
  end
from table1 t1
inner join table2 t2 on <join criteria here>;

Comment: The only problem would be in case the query returns multiple results.
Comment: @Radu Gheorghiu: You are right. We know too little of the actual query and the tables, so I wrote "it  *may* suffice..." in order to show a possible alternative.
Comment: Is this the only possible way? As I really dont want to alter the actual query
Comment: You really provided much too little information for us to answer this. You want to change your query without changing it? Er, well, ... :-| If everything is already working and you only want to replace t3.idcol with 'ABC' in your results, then maybe to replace `idcol` with `case when t2.namecol = 'ABC' then 'ABC' else idcol end` in your *SELECT* clause already solves your problem.
Comment: @ThorstenKettner `case when t2.namecol = 'ABC' then 'ABC' else idcol end` gives error 'Invalid identifier
Comment: Sorry, you will have to check this out yourself. You should be able to read your query and understand such error message when you want to change it. If not, you should ask someone who can, in order to avoid introducing any flaws.
Answer: You can try below.  I am sure you have some kind of join between t1 and t2. IN such case, you can add same at the end of the statement.
SELECT t1.*,
   t2.*,
   ( SELECT CASE
            WHERE t2.nameco1 = 'ABC' THEN 'ABC'
             ELSE idcol
             END idcol
     FROM   table3) idcol
FROM   table1 t1,
       table2 t2

How to use outside column in subquery


['#attributes']['class'] variable is not being rendered on the page

Question: I'm working on an old Drupal 7 site.
In the template file paragraphs-item--user-block-paragraph.tpl.php the content is being rendered, but the class is not added to the element.
Here is the code:
<code>$content['#attributes']['class'][] = 'my-class';
print "<script>alert('".$content['#attributes']['class'][0]."');</script>"; // confirmed variable is set to my-class
print render($content); // confirmed correct file name
</code>
What variable in $content determines the classes of the element?
Answer: I don't know the structure of the template but it should be something like this:
<code>$content['field'][0]['#attributes']['class'][] = 'my-class';
</code>
or
<code>$content['field']['#attributes']['class'][] = 'your-class';
</code>


Finding 2 poisoned bottles of wine out of a 1000

Question: The problem is formulated here. And it is also discussed here (the chosen answer to which I don't understand). I've found a few other links on this site (e.g. this), but they don't provide any explicit procedure.
My question is: what is the testing procedure for hitting the lower bound of 43 servants/rats needed to discover two poisoned objects out of 1000?
Comment: Maybe if you wrote a detailed description of what you find confusing.  I found Ori Gurel-Gurevich's answer at MO easy to understand and, up to constants, it's tight.
Comment: @Louis I think the OP is interested in particular in optimal solutions.
Comment: @Louis Yup, as Listing said, I'd appreciate a concrete, step-by-step construction for a test which can discover the two objects with only 43 rats. Furthermore, I'm not a mathematician (I'm a hobbyist) so Gurevich's answer doesn't make much sense to me at a purely mathematical level, but that's a different issue. I can at least follow a step-by-step procedure.
Answer: Look again at the following url that you mentioned in your question. Now the post has been updated with explicit procedures. You can number the wines, run the tests as specified, check the results and determine the 2 poisons. Hope that helps.
Logic problem: Identifying poisoned wines out of a sample, minimizing test subjects with constraints
Also look at
Identifying 2 poisoned wines out of 2^n wines for a easier, guided explanation on how it can be solved using $6n$ tests given $2^n$ wines.
Answer: A054961 shows 27 rats are enough.
In the link there's a C code to search a result to use 27 rats to find out the 2 poisoned bottles out of 1090. The code tries to evolute to a better solution removing some candidate wines and redistribute them among rats randomly again.
Answer: Frankl and Füredi actually prove a stronger result than what they state in their theorem. They actually prove that if $f(n)$ is the number of wines that can be tested with $n$ rats, then $f(4n) \leq 2^n$. This means that only $40$ rats are needed to test $1024$ wines. I'll try to explain their construction in a more accessible way.
The $40$ rats are divided into $4$ groups of $10$ called $A$, $A'$, $B$, and $B'$. In each group, the rats are numbered from zero to nine. As with the single poison problem, the bottles of wine are each labled with a pattern of ten zeros and ones.
For the rats in group $A$, we proceed as in the single poison problem. Rat $a_i$ is fed wine $[w_0, \dots, w_9]$ if $w_i = 1$.
For the rats in group $A'$, we do the opposite. Rat $a_i'$ is fed wine $[w_0, \dots, w_9]$ if $w_i = 0$.
Let's examine what this gains us. Suppose the poison wines are $p = [p_0, \dots, p_9]$ and $q = [q_0, \dots, q_9]$. Rat $a_i$ dies if and only if $p_i = 1$ or $q_i = 1$. In other words, from the results in group $A$ we have learned the bitwise-or of $p$ and $q$. Similarly, rat $a_i'$ lives if and only if $p_i = 1$ and $q_i = 1$. So from the results in group $A'$ we have learned the bitwise-and of $p$ and $q$. We can put together the bitwise-or and the bitwise-and to get the bitwise-exlusive-or. Call this $a$.
This is a good piece of information, but it isn't enough to solve the whole problem. To get the other half of the information, some more advanced algebra is used. The wines are identified with a more complicated structure called $GF(2^{10})$, the finite field with $2^{10}$ elements. The importants parts of this structure are that is a field (a structure where we can add, subtract, divide and multiply) and that it can be represented by vectors of ten elements of the two-element field. (The two-element field is the same as the integers modulo 2 with $1 + 0 = 0 + 1 = 1$ and $1 + 1 = 0 + 0 = 0$.) (Also, note that the field multiplication doesn't come from any usual vector product -- one example will be given later.) This gives us a natural identification between our wines and $GF(2^{10})$ via the ten element vectors we have already used to label the wines.
So, considering our $p, q \in GF(2^{10})$, we have deduced $p + q = a$ from the first twenty rats, as the sum of vectors over the two-element field is the same as a bitwise-exclusive-or. But we need a second equation so we can solve for two unknowns. A natural choice turns out to be $p^3 + q^3 = b$ for some constant $b$ (which we will later caculate from the rats in $B$ and $B'$). We will be able to solve this system of equations in $GF(2^{10})$ as follows (using the fact that in $GF(2^{10})$ anything plus itself is zero):
$$
b = p^3 + q^3 = (p + q)(p^2 - pq + q^2) = (p + q)(p^2 + pq + q^2) = (p + q)(p^2 + 2pq + q^2 - pq) = (p + q)[(p + q)^2 - pq] = a(a^2 - pq)
$$
$$
pq = \frac{b}{a} - a^2
$$
There's not an explicit single formula for $p$ or $q$ due to symmetry, but given these explicit formulae for $p + q$ and $pq$, then we can find $p$ and $q$ as the two roots of $x^2 - (p + q)x + pq = x^2 - ax + \frac{b}{a} - a^2 = 0$.
We can find $p^3 + q^3$ the same way we found $p + q$ using the remaining twenty rats.
For the rats in group $B$, we feed rat $b_i$ wine $w$ if $(w^3)_i = 1$ and for rats in group $B'$, we feed rat $b_i'$ wine $w$ if $(w^3)_i = 0$. We can then similarly construct $b = p^3 + q^3$ as we did in the case with $A$ and $A'$.
For the sake of example, I'll give a concrete way of representing $GF(2^{10})$ as $GF(2)[x]/(x^{10}+x^3+1)$. $GF(2)$ is the finite field with two elements which is the same as the integers modulo $2$. $GF(2)[x]$ is the polynomials with coefficients in $GF(2)$. Dividing by that (irreducible) polynomial means that polynomials of degree $10$ or higher are going to get simplified by applying the equation $x^{10}+x^3+1 = 0$ (equivalent to $x^{10}=x^3+1$). (As an aside, this is sort of analogous to constructing the complex numbers by taking real polynomials and dividing out $x^2+1$.) Our vectors then represent the polynomials' coefficients so, for example, $p = p_9 x^9 + \dots + p_2 x^2 + p_1 x + p_0$.
Then, for example, we can calculate which rats will get wine $[0, 0, 1, 1, 0, 1, 0, 1, 1, 1]$. For group $A$, we match the ones to get rats $a_2, a_3, a_5, a_7, a_8, a_9$. For group $A'$, we match the zeroes and get $a_0', a_1', a_4', a_6'$. For the other two groups, we need to cube the wine. The corresponding polynomial is $x^9 + x^8 + x^7 + x^5 + x^3 + x^2$. Cubing, we get:
$$
(x^9 + x^8 + x^7 + x^5 + x^3 + x^2)^3 = x^{27} + x^{26} + x^{24} + x^{23} + x^{22} + x^{21} + x^{20} + x^{19} + x^{16} + x^{14} + x^{13} + x^8 + x^7 + x^6
= (x^3 + 1)^2(x^7 + x^6 + x^4 + x^3 + x^2 + x + 1) + (x^3 + 1)(x^9 + x^6 + x^4 + x^3) + x^8 + x^7 + x^6
= x^{13} + x^{10} + x^9 + x^6 + x^2 + x + 1
= (x^3 + 1)(x^3 + 1) + x^9 + x^6 + x^2 + 1
= x^9 + x^2
$$
From this we can see that in group $B$ the wine will go to $b_2, b_9$ and in group $B'$ it will go to $b_0', b_1', b_3', b_4', b_5', b_6', b_7', b_8'$.
Note that the proof only gives a lower bound of $1024$ wines testable with $40$ rats. It may be possible to test more wines with $40$ rats, or to test $1024$ wines with fewer rats.


how to use javascript with svg?

Question: I've tried to put JavaScript into SVG and all are in html file,
when I wrote  as showed in my code my SVG drawing disappear so what is the correct way to write JavaScript so that the SVG will be showed and the function can be applied to it.

       height(rx) : <input type="number" name="number" id = "ipheight"
    min ="0" max = "50">
    <input type="button" value="Resize" onclick="resize()">

        <input type="range" id="fthick" min="0" max="10" onchange="thickness()">

                   <input type="radio" name="copies" id="one">One

            <input type="radio" name="copies" id="two">Two

            <input type="radio" name="copies" id="Three">Three

            <input type="radio" name="copies" id="Four">Four

</svg>

Comment: You are doing `` try fix that.
Comment: Note that an XML declaration (the `` thing) only makes sense in XHTML and mustn't appear in the middle of the document. It may only appear at the very top (i.e. before `` and any ``).  As you're not using XHTML, simply don't use it.  However, this is not the cause of the problem you are asking about.
Answer: I have not fully tested the actual script code but if you move the javascript block after the <svg></svg> tags like I do in the following:
</svg>

You should see be able to see your image and test your function.

how to use javascript with svg?


How to repeatedly stop a program after x minutes and re run it changing one variable in python?

Question: I have a program written in python which goes as follows:
for i in range(4954):
    ........
    save("/Downloads/pos_" + str(i) + ".h5")

The fact is the program running time increases exponentially(we observed it using time.time())
So what I need is run the program for 10 min and then re run the program.
But I just need to change the i in for loop to the number at which it is stopped.
I can do a cron job, but what should I do to change i value?
Comment: What stops the program after x minutes?
Answer: You could use marshal.dump(https://docs.python.org/3/library/marshal.html) to save the value when stopping the program, and then loading it via marshal.load when starting.
Honestly, I think it would be a much better approach to fix the root cause of the problem, i.e. solving the exponential run time.
Answer: If each iteration (each i value) in the loop is independent with each other, you can parallelize it with ProcessPoolExecutor:
import concurrent.futures

def downloader(i):
    ...
    save("/Downloads/pos_" + str(i) + ".h5")

def main():
    i_range = list(range(4954))
    with concurrent.futures.ProcessPoolExecutor(10) as executor: # create 10 workers (subprocesses)
        for number, result in zip(i_range , executor.map(downloader, i_range)):
            print('File %d is scheduled to download!' % (number))

if __name__ == '__main__':
    main()

This requires Python3.
Answer: Consider using a generator:
import time

def gen(n):
    for i in range(n):
        yield n

g = gen(4954)

time_limit = 600

while some_condition:
# whatever condition required for you to continually restart this section

    start = time.time()
    while time.time() - start < time_limit:
        ... some code...
        try:
            save("/Downloads/pos_" + str(next(g)) + ".h5")
        except StopIteration:
            print('end of iterations')

Where g will remember the iteration it's on and continue the next time you call next(g).
Comment: Its better to assign `i=next(g)` and use `i` later because every invocation to `next` will increase the counter by 1. And make sure `next(g)` is placed inside the `try` structure.
Comment: In this instance I don't imagine there's any difference between `i=next(g)` vs just calling `next(g)` directly.  The last `i` would be released regardless and are incremented correctly.
Comment: I assume this program is used to download something from Internet. So `i` should be also used to construct the URL.
Comment: Another problem: the generator object `g` should be saved in a file to survive restarts.
Comment: Right, but I still don't see your point.  If the generator was a bit more complex and the yield might be affected, I might agree.  In this case i fail to see how it is any different.  Also, this script assumes everything is done *within* the script itself.  It does not attempt to be a solution that relies on external restart.
Comment: The PO said: "I can do a cron job ..."
Comment: That's just one solution though, the OP didn't say they *must* do a cron job.  If you can get away without an external dependency, why not do it all within the script? I guess the *real* question is, *why* is the processing time increasing exponentially in OP's script? That might eliminate the need to restart every 10 minutes altogether, but that part of details is not clear.
Comment: She/He also said "So what I need is run the program for 10 min and then *re run* the program." We have different understanding about how to "re run", by an external program like `cron` or within the python process. The PO should clarify that.
Answer: Here my solution:
import os
import time
import threading

class test_class(object):
    def __init__(self):
        self.iter_number = 0
        self.new_iter_number = 0

        self.iter_file_dir = "/tmp_file.txt" # tmp file where sto the new iteration number remaining

        self.end_iteration = False # Flag to stop the iteration

        self.delay = 1 # Seconds that means 10 minutes

        with open(self.iter_file_dir, "r") as file:
            self.iter_number = int(file.readline())

        self.run()

    def for_function(self):
        for i in range(self.iter_number):
            save("/Downloads/pos_" + str(i) + ".h5")
            if(self.end_iteration):
                self.new_iter_number = self.iter_number - i
                break

    def run(self):
        threading.Thread(name="Iteration_Thread", target=self.for_function).start()

        time_remaining = self.delay-time.time()%self.delay
        time.sleep(time_remaining)

        self.end_iteration = True

        # Save the file with the new value
        with open(self.iter_file_dir, 'w') as f:
            f.write(str(self.new_iter_number))
test_class()

The idea behind this code is simple:

Create a tmp_file.txt where you want, and write in them the number of iteration that you need in the for.
Create a timer that sleep for X minutes and after that set a flag that terminate the for loop.
After that save in the tmp_file.txt the new calculated iteration number

Each time that the cron run the program it will load the new iteration value. Obviously when the iteration are finished in the file the 0 is written, so no more iteration were performed.


If $G$ is a finite group and $a$ is an element of $G$ with $\mathrm{ord}(a) = r$., then $\mathrm{ord}(a^k) = \frac{r}{\gcd(r,k)}$

Question: Has anyone an idea how to prove this one??

If $G$ is a finite group and $a$ is an element of $G$ with $\mathrm{ord}(a) = r$., then $\mathrm{ord}(a^k) = \dfrac{r}{\gcd(r,k)}$.

Thank you in advance!
Comment: Have you tried anything?
Comment: Note that since you are looking for the order of $a^k$, you are essentially working in the cyclic subgroup of $G$ generated by $a$, which here is isomorphic to integers modulo $r$. So look at what happens in integers modulo $r$, this greatly helps for visualisation (you can even draw a perfectly accurate picture!).
Answer: Hint: Let $d:=\gcd(r,k)$. Then we can write $r=bd$ and $k=cd$, where $\gcd(b,c)=1$.
We are then asked to prove that $\text{ord}(a^k)=b$. Now,
$$
(a^k)^b=a^{bcd}=(a^{cd})^b=(a^r)^d=1,
$$
so that the order of $a^k$ must divide $b$.  Now, what's left is to show that there is no smaller number $\tilde{b}$ so that $(a^k)^{\tilde{b}}=1$. Can you see how to do that?  Try looking for a contradiction.


Finding $a$ such that $\tanh(x)-a\sin^2(x)=0$ has a double root

Question:
Given $f(x) = \tanh(x)-a\sin^2(x)$, what is the value of $a$ for which $f(x) = 0$ has a double root, and what is the value of that double root?

My Work :
Using MAPLE , I plotted a few graphs and estimated $a \approx 0.91$ , which gives $x \approx 1.46$ , however I need to be accurate to at least $8$ significant figures (hence MAPLE).
I am stuck... help?
Comment: Take a derivative to get a function with a single root, then the root is better defined.  You should be close enough that Newton's method will converge in a few iterations to that accuracy.
Comment: It seems to me that this should not have a unique solution.
Comment: Yes , @user317176 , I have listed 6 Solutions in my answer , though there are infinitely more.
Answer: For a multiple root you want $f(x) = 0$ and $f'(x) = 0$.  So in Maple you can try
e.g.
<code>f:= tanh(x) - a*sin(x)^2;
fsolve({f, diff(f,x)}, {x=1..2, a=0..1});
</code>
$$ \{a =  0.9087520662, x =  1.463860639\}$$
BTW there are infinitely many values of $a$  that produce double roots in different places.  You can try looking at different intervals to find other solutions.
Answer: You can consider that you are looking for the minimum value of
$$a=\frac{\tanh(x)}{\sin^2(x)}$$ As one could intuitively expect, the minimum is close to $x=\frac \pi 2$.
Expand the rhs as a series
$$\frac{\tanh(x)}{\sin^2(x)}=t+(1-t^2)\left(x-\frac{\pi }{2}\right)+t^3 \left(x-\frac{\pi }{2}\right)^2+$$ $$\frac 13\left(2+t^2-3t^4  \right)\left(x-\frac{\pi }{2}\right)^3+O\left(\left(x-\frac{\pi }{2}\right)^4\right)$$ where $t=\tanh \left(\frac{\pi }{2}\right)$.
Differentiate and use power series reversion. This would give, as an estimate
$$x=\frac{\pi }{2}-\frac{1-t^2}{2 t^3}+\frac{\left(1-t^2\right)^2 \left(3 t^4-t^2-2\right)}{8 t^9}$$ which, numerically, is $x=1.46292$ while the exact solution is $x=1.46386$.
Plug this value to obtain $a=0.908753$ while the exact solution is $a=0.908752$.
Edit
Making the initial series to $O\left(\left(x-\frac{\pi }{2}\right)^{11}\right)$, the same procedure leads to
$$x=\color{red}{1.46386063852}903$$
$$a=\color{red}{0.90875206615524003441871}352$$
Answer: Over-View :
I have given the Visualization , then I derived the necessary Equations in 2 ways , then I have got the Numerical Solutions to those Equations , targeting those 2 ways.
Visualization :
Consider the graphs for $\tanh(x)$ & $a \sin^2(x)$ where $a = 1.2,1.1,1.0,0.9,0.8$ :

We can see that the Blue Curve ($a = 1.2$) & Green Curve ($a = 1.1$) will have 2 Intersection Points in close Proximity within a Peak.
When we "shrink" (make $a$ smaller) the $\sin^2(x)$ Curve , the 2 Intersection Points will come closer , Eg the Orange Curve ($a = 1.0$) at the Second Peak & the Red Curve ($a = 0.9$) at the first Peak.
When we "shrink" more (make $a$ more smaller) , there will be no Intersection Points , Eg the Purple Curve ($a = 0.8$) will never have Intersection Points with Positive $x$ range.
That Visualization then gives us the Intuition that when the two roots are close & Coinciding , we must have the tangents of the 2 Curves Coinciding.
Equations :
The tangents will have Slopes $sech^2(x)$ & $a 2 \sin(x) \cos(x) = a \sin(2x)$
Thus , we have this Set of two Equations :
$$\tanh(x) = \frac{\sinh(x)}{\cosh(x)} = a \sin^2(x) \tag{1}$$
$$sech^2(x) = \frac{1}{\cosh^2(x)} = a \sin(2x) \tag{2}$$
Eliminating $a$ ( Dividing the Equations ) we get :
$$\frac{\sinh(x)\cosh^2(x)}{\cosh(x)} = \frac{\sin^2(x)}{2\sin(x)\cos(x)} \tag{3}$$
$$2\sinh(x)\cosh(x) = \tan(x) \tag{4}$$
$$\sinh(2x) = \tan(x) \tag{5}$$
SOLUTION 1 :
Solving that Set of two Equations (1) & (2) , we get :

I used wolfram online tool , where I had to use $A \equiv x$ & $B \equiv a$ to get those Numerical Solutions.
The Solution matches what OP got : $(x \approx 1.46386 , a \approx 0.908752)$ : though there are other Solutions too.
Plugging the Set of Equations into MAPLE should get you the Same , with the Desired Accuracy.
SOLUTION 2 :
Solving the Single Equation (5) , we get the $x$ values which we can use to get the corresponding $a$ values :
$x \approx \pm 1.46386063852807\cdots$

We get the Equivalent Solutions this way too.
Plugging that Single Equation into MAPLE should get you the Same , with the Desired Accuracy.
IMPORTANT : Images & Solutions were generated by wolfram online tool.
Answer: Make your equation linear in the hyperbolics. The roots and their multiplicity remain the same if you multiply with the positive factor $\cosh x$. Then for a double root you want
$$
0=\sinh(x)-a\sin^2(x)\cosh(x)\\
0=\cosh(x)-2a\sin(x)\cos(x)\cosh(x)-a\sin^2(x)\sinh(x)
$$
or as linear system
$$
0=\pmatrix{1&-a\sin^2x\\-a\sin^2x&1-2a\sin x\cos x}\pmatrix{\sinh x\\\cosh x}
$$
If that system has a solution, then the determinant of the system matrix has to be zero (but not in the other direction).
$$
0=(1-a\sin x\cos x)^2-a^2\sin x^2\\=(1-a\sin x(1+\cos x))(1-a\sin x(-1+\cos x))
$$
Now you can use each of these branches to eliminate $a$ from the system and reduce it to a scalar equation for $x$,
$$
\tanh(x)=\frac{\sin x}{\pm 1+\cos x}=\frac{\pm 1-\cos x}{\sin x}
=\frac{1-\cos(k\pi+x)}{\sin(k\pi+x)}=\tan\left(k\frac\pi2+\frac x2\right)
$$
where $k$ even and odd corresponds to the sign selection.
The left side is bounded, the right side has simple poles at regular distances, so the intermediate value theorem gives an infinity of solutions.
Now take the points where $x/2=\frac\pi4+m\frac\pi2$, $x=\frac\pi2+m\pi$, where the right side takes values $\pm 1$, to get intervals to start a bracketing method like bisection or Dekker,...