Can Ubercart be adapted to print a letter?

Question: When an order is received through Ubercart, the details can be viewed and printed, but can the print order option be expanded to do more? When I ship product, I like to include a personalised letter in addition to the standard order form.
Can I craft such a letter, so that it prints out after the order page, showing letterhead, date, customers address, and separate envelope?
Answer: Yes. In D7 there's a 2 step process to this.

Copy ubercart/uc_order/uc_order-invoice-page.tpl.php to your current theme directory and flush your cache; this will let you create your own custom version of the the order template.
Add this snippet to your new template after <?php print $content; ?>; this will add some markup/CSS that will be rendered as a new page when treated as a printable document.
<?php /* Print only from administration page*/ ?>
<?php if(preg_match('/admin\\/store\\/orders\\/\\d+\\/invoice\\/print/', current_path()) == 1): ?>

NEW PAGE

<?php endif; ?>

If you're running a D6 site, it's a little more of pain (D6 UC ignores some theming conventions).

You'll need to copy ubercart/uc_order/templates/uc_order-customer.tpl.php to ubercart/uc_order/templates/uc_order-custom.tpl.php
Have a module define a new custom template via hook_uc_invoice_templates(): function MYMODULE_uc_invoice_templates() { return array('custom'); }
Set the new invoice in order setting page (admin/store/settings/orders/edit/basic).
Use the code in the above D7 example inside uc_order-custom.tpl.php. You'll have to modify since I don't think current_path() exists in D6. However, the same frontend logic still exists (add some extra markup in the template with CSS to generate a 2nd page).

There might be a better way to do this, but I've not touched D6 UC templating in a long time.


Calcular média Geométrica em consulta SQL

Question: Exemplo de Tabela
Campo - Valor
A     - 30,21
B     - 15,03
C     -  5,06
B     - 10,20
B     - 12,89
C     -  1,12

Calculo média geométrica
A = (30,21)^1/1
B = (15,03*10,20*12,89)^1/3
C = (5,06*1,12)^1/2

Resultados
A = 30,21
B = 12,23
C =  2,37

Tentei algo assim
POWER(POWER(10.00,SUM(LOG10(CAST(ANSDET.VALOR AS DECIMAL(30,2))))), 1/(CAST(COUNT(ANSDET.CAMPO)AS DECIMAL(10,2)))) VALOR,

A tabela possui cerca de 4000 registros, estou recebendo a mensagem:

Ocorreu uma operação de ponto flutuante inválida.

Preciso da formula SQL que me retorne estes resultados das médias... Alguma ideia?
Answer: Que bom que eu não fui a única pessoa a passar pela necessidade do produtório em SQL por terras lusófonas.
Como o @Motta falou em sua confusa e pouco ilustrativa resposta, você pode usar o fato de que o log do produto é igual à soma dos logs e, então, transformar seu problema de produtório para somatório (com algumas adaptações que precisam ser anuladas posteriormente, claro).
Então, vamos mergulhar na terra dos logaritmos?

Essa resposta vai ser dividida em algumas seções, para ficar mais fácil seu manejo e poder segmentar a leitura. São eles:

de produtórios a somatórios e de volta de novo, com SQL
log do produto é a soma do log, mas por quê?
diga não a potência desnecessária: multiplicando log(x) por uma constante

NOTA: como os logaritmos só são bem definidos com imagem real para números > 0, essa resposta falha miseravelmente se o conjunto de dados tiver pelo menos um número nessa situação, precisará fazer uma adaptação.
Você pode conferir no SQLFiddle minha resposta para os dados informados na questão. Notou que a resposta para o caso B tá distinta da esperada? Pois bem, minha resposta é a média geométrica verdadeira, talvez tenha sido um erro de ponto flutuante/precisão na hora de escrever o resultado esperado.

De produtórios a somatórios e de volta de novo, com SQL
Você tem um problema que é o cálculo de um produtório. Um exemplo de produtório bem
básico é o seguinte, para quem não está acostumado:

O que isso quer dizer? Isso quer dizer que y = x0 * x1 * x2 ... * x10. O produto dos elementos do conjunto, um contraponto ao somatório que é a soma dos elementos do conjunto.

Note como é extremamente semelhante a um somatório:

No caso, o produtório é representado pela letra grega pi, cujo som lembra bastante o P do português e denota produto. Já o somatório é representado pela letra grega sigma, cujo som lembra bastante o S do português e denota soma.
O somatório, então, é a mesma ideia do produtório porém usando o operador de soma: y = x0 + x1 + x2 ... + x10

Assumindo como verdade que log(A*B) = log(A) + log(B), temos que log(x0 * x1 * x2 ... * xn) = log(x0) + log(x1 * x2 ... * xn) = log(x0) + log(x1) + log(x2) ... + log(xn). Então, conseguimos daqui fazer um somatório dos logaritmos, porém, para substituir completamente, precisamos anular o logaritmo da jogada.
Mas, como? Simples, pela sua definição.
Na definição de logaritmo, temos que e^x = n, com e e n conhecidos. O logaritmo é a operação usada para encontrar o x da questão, logo e^x = n <==> x = log(n).
A partir dessa definição, temos que e^(log(x0 * x1 * x2 ... * xn)) = x0 * x1 * x2 ... * xn. Justamente a definição de logaritmo. Porém, graças à propriedade log(A*B) = log(A) + log(B), podemos substituir o produtório por somatório sem perder semântica: e^(log(x0) + log(x1) + log(x2) ... + log(xn)) = x0 * x1 * x2 ... * xn.
Como representar isso no SQL? Usando o exponencial do somatório dos logaritmos de dada coluna:
SELECT
  campo,
  exp(sum(log(valor))) as produtorio
FROM
  dados
GROUP BY
  campo

Note que, como não é necessário explicitar a base, não estou usando nem LOG10 nem tampouco POWER(10, expoente), porém simples LOG e EXP

Log do produto é a soma do log, mas por quê?
Sejam A e B dois números reais positivos quaisquer. Nenhuma outra imposição a eles é feita. Isso significa que há algum a = log2(A) e b = log2(B) que são os logaritmos de A e B respectivamente na base 2.
Se, por acaso, eu multiplicar A*B vou obter um número C, também real e positivo. Como a = log2(A), isso significa que A = 2^a. Analogamente temos B = 2^b. Logo, A*B = C = 2^a * 2^b. Podemos simplificar a potência de 2 assim: C = 2^(a+b).
E como seria se eu tirasse o log2 de tudo?
Bem, sabendo que C = 2^(a+b), temos que log2(C) = a + b. Porém não podemos nos esquecer que C = A*B. Logo, log2(A*B) = a + b. Substituindo as fórmulas iniciais de a e b:
log2(A*B) = log2(A) + log2(B)

Os cálculos foram feitos na base 2 por ilustração, mas poderia ser qualquer base, até mesmo φ.
Diga não a potência desnecessária: multiplicando log(x) por uma constante
Mas você não quer simplesmente o produtório, mas sim a média geométrica. O produtório era apenas um meio para se chegar na média geométrica. A fórmula para média geométrica de um conjunto é dada pela seguinte fórmula:

Ou seja, é a exponenciação do produtório pelo inverso da quantidade de elementos no produtório.
Se for transportar exatamente isso para o SQL fica algo assim:
SELECT
  campo,
  power(exp(sum(log(valor))), 1/count(*)) as media_geo
FROM
  dados
GROUP BY
  campo

Porém fica mais estranho exponenciar 2 vezes seguidas, não acha? Além de aparentar muita demanda computacional à toa? E, sim, está certo: tem trabalho sendo feito desnecessariamente aqui.
Tem uma propriedade muito importante da exponenciação que vamos usá-la agora: ela é distributiva sobre a multiplicação:

E tem outra propriedade bacana dos logaritmos: log(a^b) = b * log(a). Daqui, podemos tranquilamente chegar nessa transformação:

Em SQL, ficaria assim:
SELECT
  campo,
  exp(sum(log(valor))/count(*)) as media_geo
FROM
  dados
GROUP BY
  campo

Comment: Utilizando estas formulas recebo o seguinte erro, "Ocorreu uma operação de ponto flutuante inválida."
Comment: Já obtive esse erro quando passava números negativos ou zerados para o log. Vou testar com mais calma a consulta contra a base de dados fornecida na sua pergunta.
Comment: A resposta do Quesado foi 10 , vou manter a minha como lembrete , jamais responda do tablet a preguiça te faz editar mal e porcamente .. esta solução via logaritmo e potenciação tem o problema de valores negativos ou muito grandes.
Comment: Nos valores fornecidos pela questão deu certo. O problema pode ser a presença de números nulos ou negativos, para os quais o _log_ não é definido nos reais. A propósito, a média geométrica do caso `B` é [12.5489...](https://www.wolframalpha.com/input/?i=(15.03*10.20*12.89)%5E1%2F3), conforme encontrei [na minha consulta](http://sqlfiddle.com/#!18/9eecb/40514)
Comment: @Motta, eu me acostumei a editar no smartphone... creio que no tablet seja ainda mais fácil. Obviamente esta resposta aqui não fora escrita a partir do smartphone, mas do notebook. Em compensação, [esta daqui](https://pt.stackoverflow.com/a/266198/64969) foi apenas smatphone, [esta outra](https://pt.stackoverflow.com/a/265805/64969) eu usei bastante o smartphone, mas não lembro se foi só pra criar as imagens ou se foi pra tudo mesmo
Comment: @henriquew qual o conjunto de dados usados?
Comment: Boa tarde, meu erro foi o seguinte, dentro os vários registros que tinham, havian números do tipo (0.1 , 0.8 , 0.59), na "fórumula exp(sum(log(valor))/count(*)) as media_geo" acontecia então o erro "Ocorreu uma operação de ponto flutuante inválida." Obrigado a todos!
Comment: @henriquew não tive problemas com esses dados na fórmula. Coloquei esses 3 valores. Testei com 15 valores desse naipe e não obtive problemas
Comment: Tente com os seguintes valores (167.00
68.00
1876.00
225.00
2732.00
3754.00
9999.00
231.00
340.00
946.00
163.00
3348.00
819.00
1426.00
148.00
618.00
5721.00
1753.00
1978.00
3828.00
1104.00) ou (0.57
0.88
1.63
1.38
0.32
0.57
1.32
1.38
2.22
0.79
3.85
0.46
0.63
0.86
0.88
0.86
2.19
1.47
0.32
0.82
2.40) na  formula "exp(sum(log(ANSDET.VALOR))/count(*)) as VALOR"
Comment: [Média de 882.011621537022, e média de 0.9984505031117724](http://sqlfiddle.com/#!18/9eecb/41027). Usei o agrupador `D` para o primeiro conjunto de números, e `E` para o segundo conjunto
Comment: Meus resultados não foram perfeitos, mas fiz o melhor que pude nas operações que o SQL Server fornece. Cada cálculo com ponto flutuante implica em perder precisão [1](https://pt.stackoverflow.com/a/286014/64969) [2](https://pt.stackoverflow.com/q/219211/64969) [3](https://pt.stackoverflow.com/a/272376/64969).
Comment: Veja o resultado para [`D`](https://www.wolframalpha.com/input/?i=geometric+mean(167.00,68.00,1876.00,225.00,2732.00,3754.00,9999.00,231.00,340.00,946.00,163.00,3348.00,819.00,1426.00,148.00,618.00,5721.00,1753.00,1978.00,3828.00,1104.00)), e para [`E`](https://www.wolframalpha.com/input/?i=geometric+mean(0.57,0.88,1.63,1.38,0.32,0.57,1.32,1.38,2.22,0.79,3.85,0.46,0.63,0.86,0.88,0.86,2.19,1.47,0.32,0.82,2.40)). Note que só perdi precisão em `D`, em `E` foi uma resposta satisfatória
Answer: --li ponderada e nao geometrica
--usando a propriedade dos logs se tem o produto
exp(sum(log(valor)))
--calcule a raiz
power(exp(sum(log(valor))),(1/(count(*)))
--isto deve resolver para números pequenos

Comment: Utilizando estas formulas recebo o seguinte erro, "Ocorreu uma operação de ponto flutuante inválida."


The expectation of a Dice game

Question: Let's assume there is a $n$ faces fair dice with face value as $1, 2,...,n-1, n$. Player return would be the value of throwing result, i.e. if player throw once and the result face is $m$, then player will get $m$ as return. If don't like the result of throw, player can give up the return of that throw and throw $1$ more time. Player will only choose re-throw when expect return would be greater than current result. Let's assume player could do such re-throw for up to $k$ times. Then what is player's expect return of this game?
I have been trying to do the backward induction but had hard time to come up with a generalized solution.
The expect return of $k^{th}$ throw is $\frac{(1+2+...+n-1+n)}{n}=\frac{(n+1)}{2}$. Player would only re-throw at $(k-1)^{th}$ if result $<\frac{n+1}{2}$. Then expect return at $({k-1})^{th}=\frac{(n+1)}{2}\frac{1}{n}(\frac{n+1}{2}-1+1)+\frac{(\frac{(n+1)}{2}+...+n)}{n}$
. Then use the same logic to calculate $(k-2)^{th}$ ...
So if the expect return at $t^{th}$ throw is $E_t$, then $E_{t-1}=\frac{E_t*\lfloor{E_t}\rfloor}{n}+\frac{(\lceil{E_t}\rceil+n)(n-\lceil{E_t}\rceil+1)}{2n}$
Does anybody have an idea?
Comment: Welcome to math.SE. [Here](https://math.meta.stackexchange.com/questions/5020/)'s a tutorial and reference for typesetting math on this site.
Comment: Let's assume you need more context and details, and plan to provide such, e.g., your efforts on solving this on your own; and/or clarification regarding why you feel stuck to do any work on this?  I shall wait.
Comment: How does the player ("you") decide whether to accept the result or to re-throw? This depends on the risk aversion of that player.
Comment: If the expectation return of throwing 1 more time is greater than current result, the player will re-throw it.
Comment: I edited the text of the question and hopefully it looks better.
Comment: When $n$ is even there is an equal probability of rolling above the expected value of $(n+1)/2$ as rolling below, so with each roll there is a 50% chance per roll that they will roll above expectation and therefore stop, Thus there is a $1-2^{-k}$ probability they  succeed and end up with an expected result for rolls above half, and a $2^{-k}$ probability with an expectation of the highest of $k$ rolls with results $\le \frac n2$,
Answer: Let $X_1,X_2,\dots$ be the face values for the individual throws, and let $Y_1,Y_2,\dots$ be the current returns after the throws.
Let $\overline x=E[X_1]=E[X_i]=\frac{1}{n}\binom{n+1}{2}=\frac{n+1}{2}$ be the expected face value, which is the expected return of a single throw.
Let's first consider fixed $k$ to get a feeling for what's going on.
For $k=0$, we can only throw once, so we have $Y_1=X_1$ and $E[Y_1]=\overline x$.
For $k=1$, the player rethrows if the expected return of the second throw is greater than the current return, i.e. if $\overline x=E[X_2]>Y_1$. So, the distribution of $Y_2$ is $P(Y_2=y)=P(Y_1=y)+P(Y_1<\overline x)P(X_2=y)=(1+P(X_1<\overline x))\frac{1}{n}$ for $y\ge\overline x$, obtained by not rethrowing or rethrowing, and $P(Y_2=y)=P(Y_1<\overline x)P(X_2=y)=P(X_1<\overline x)\frac{1}{n}$.
In particular, this gives $P(Y_2<\overline x)=P(X_1<\overline x)^2$ and, using the largest integer $x=\lceil\overline x\rceil-1=\max\mathbb Z_{<\overline x}$ below $\overline x$ ($\lceil a\rceil$ is $a$ rounded up) and $P(X_1\le x)=\frac{x}{n}$ further
\begin{align*}
E[Y_2]&=\sum_{y=1}^{x}\frac{1}{n}P(X_1\le x)y+\sum_{y=x+1}^n\frac{1}{n}(1+P(X_1\le x))y\\
&=\frac{x}{n^2}\binom{x+1}{2}+\left(\binom{n+1}{2}-\binom{x+1}{2}\right)\left(\frac{1}{n}+\frac{x}{n^2}\right).
\end{align*}
For $k=2$, we get $P(Y_3=y)=P(Y_2=y)+P(Y_2<y)P(X_3=y)=(1+P(X_1<\overline x)+P(X_1<\overline x)^2)\frac{1}{n}$ for $y\ge\overline x$, and $P(Y_3=y)=P(Y_2<\overline x)P(X_3=y)=P(X_1<\overline x)^2\frac{1}{n}$, so
$P(Y_3<\overline x)=P(X_1<\overline x)^3$.
So, for any $k$ rethrows we have $k+1$ throws and $P(Y_{k+1}=y)=\frac{1}{n}\sum_{i=0}^kP(X_1<\overline x)^i$ for $y\ge\overline x$, and $P(Y_{k+1}=y)=P(X_1<\overline x)^k\frac{1}{n}$ for $y<\overline x$.
As a sanity check, notice that
$$P(Y_{k+1}\ge\overline x)=P(X_1\ge\overline x)\sum_{i=0}^kP(X_1<\overline x)^i=(1-P(X_1<\overline x))\sum_{i=0}^kP(X_1<\overline x)^i=1-P(X_1<\overline x)^{k+1}$$
and that $P(Y_{k+1}<\overline x)=P(X_1<\overline x)^{k+1}$, so $P(Y_{k+1}<\overline x)+P(Y_{k+1}\ge\overline x)=1$ and this is, maybe surprisingly, indeed a probability distribution. So, now we cn write down the expectation
$$E[Y_{k+1}]=\sum_{y=1}^nP(Y_{k+1}=y)y=\sum_{y=1}^{x}\frac{1}{n}P(X_1\le x)^ky+\sum_{y=x+1}^n\frac{1}{n}\frac{1-P(X_1\le x)^{k+1}}{1-P(X_1\le x)}y,$$
where we used the geometric series $\sum_{i=0}^ka^i=\frac{1-a^{k+1}}{1-a}$. Computing the sums and using $P(X_1\le x)=\frac{x}{n}$ gives
\begin{align*}
E[Y_{k+1}]&=\frac{x^k}{n^{k+1}}\binom{x+1}{2}+\frac{1}{n^{k+1}}\frac{n^{k+1}-x^{k+1}}{n-x}\left(\binom{n+1}{2}-\binom{x+1}{2}\right).
\end{align*}

The expectation of a Dice game


Comparing quasibinomial glms in R

Question: I have some data that are proportions that I am trying to fit a glm to. As the data are proportions someone suggested that the quasibinomial is the correct family of glm to go for. I am now trying to do the model selection. However, as R does not give AIC scores for quasi models I'm at a bit of a loss as to what to do. Is there an alternative? I've read somewhere that likelihoods aren't good for quasi model, but are there any other options?
Comment: Some similar questions:  https://stats.stackexchange.com/questions/273580/inference-for-quasibinomial-glm-with-lasso-penalty-using-selectiveinference-pack    Here: for more information:  https://cran.r-project.org/web/packages/pscl/vignettes/countreg.pdf
Answer: If your response variable is produced by taking the fraction of $a \textrm{ and } b$, $\{a,b\} \in \mathbb{R} \mid \{a,b\} > 0$ (i.e $a$ and $b$ are non-zero, positive, continuous), then it is reasonable to model it as being distributed according to the Beta distribution. In such case you should perform a beta regression, implemented in the betareg package in R. You can then compare your models with stats::AIC.
If $a$ represents counts and $b$ trials, you should rather use a logistic regression which uses the binomial distribution as a model. Using the quasi-binomial distribution as a model is useful if your data exhibit more (or less) variance than that expected from a binomial model. If you choose to use a quasi-binomial model, the package AICcmodavg can provide you with the quasilikelihood counterpart of AIC. However you should proceed with caution as this metric may be too sensitive with departures from the model (Wang et al. 2015).

For more information on beta vs logistic regression see:  https://stats.stackexchange.com/a/29042/97671
For more discussion on when to use a quasi-binomial vs a binomial model see:
What is quasi-binomial distribution (in the context of GLM)?

Reference:
Wang, Y., Murphy, O., Turgeon, M., Wang, Z., Bhatnagar, S. R., Schulz, J., and Moodie, E. E. M. (2015)
The perils of quasi-likelihood information criteria. STAT, 4: 246–254. 10.1002/sta4.95

Comparing quasibinomial glms in R


Making Apache recognize MIME type of files without extension

Question: I have some old HTML files that were created elsewhere by someone else.  Many of them don't, for some reason, have the .html extension on them.  I don't want to have to change them if possible, but for some reason Apache can't seem to do any MIME magic to figure out their file type.  I have the mime_magic mod enabled, along with the following in the sites section:
    MimeMagicFile /etc/magic

I should note that I'm using Debian Linux on this machine.
Comment: Mind that mod_mime_magic only kicks in if mod_mime does not find a MIME type for a file. In case of no extension, mod_mime finds *many* MIME types from /etc/mime.types, causing mod_mime_magic to not ever being called, but also not *one* type being determined.
Comment: Is the file `/etc/magic` actually the right location on your system for the MIME magic file?
Answer: I tried the DefaultType workaround in my main conf file and it did not work for me. (My environment is an internal, thoroughly hacked-up version of Apache, so there may be a FileInfo directive or something overriding DefaultType and I can't find it. On standard installations it may work...)
What DID work: since all the extensionless files I'm dealing with are in one known directory, I added a Location block and used ForceType:
<Location "/directoryname">
ForceType text/plain
</Location>

You cannot use ForceType on a directory that should contain more than one type of file.
Answer: Assume all files not containing a period are PHP:
      <FilesMatch "^[^\.]+$">
              ForceType application/x-httpd-php
      </FilesMatch>

Answer: A simple warkaround, not really a solution maybe, would be to change the DefaultType as follows:

DefaultType text/html

This would assure every non recognized file will be treated as html.
This is not a true solution, I repeat, but it is simple and may have sense if your server serves mainly html contents
Answer: The magic file path is /usr/share/file/magic in Debian. Change the configuration statement to
MimeMagicFile /usr/share/file/magic

If you open /etc/magic with a text editor, you can see the comment explaining that file(1) should use that file for your local magic definitions only.
Comment: It seems like this should work, but Apache is still giving text/html for those files, and I just double checked to make sure the file is there.
Comment: oops, I mean text/plain
Comment: Actually, I think I take that back.  It might be something with Firefox because I just checked this with Chromium, and it seemed to work just fine.
Comment: And that only seems to be on some files.
Answer: It sounds to me that you are using the SYSTEM magic file when you want to be using the MIME magic file — as the name of the Apache configuration directive "MimeMagicFile" implies.  Try this:
MimeMagicFile /usr/share/mime/magic

Of course, make sure that is the right path for your system — I don't have a Debian system to test with, but I would expect it to be there.  Try locate mime/magic if you can't find it at the above location.


Can a batsmen ask umpire to check whether the fielder touches the rope

Question:
Can a batsman ask the umpire to check whether the fielder touches the rope?
Answer: The players may ask anything they like of the umpires, but few of those requests have bearing in the Laws or can  be forced.
The Playing Conditions for all international formats allow a Player Review in the Umpire Decision Review System for whether or not a batsman is out, but not for any other decision. Thus, if there has been no appeal by the fielding team for an out, and therefore no decision by the umpire, a review cannot take place. In this case the umpire must ignore the request for a review and it does not count towards the team's allocation for the innings.
However, it is unnecessary to ask anyway. The bowler's end umpire may ask for the advice of the third umpire if it is not clear whether a boundary has been scored, and the third umpire should advise the umpires if they believe a boundary line "infringement or incident" that has not been acted on. If there would be any reason for the batsman to ask, the umpires would already be checking.
Answer: The para 3.1.2 of Appendix D in ICC rules on ICC Men's Test Match Playing Conditions, effective from  28th September 2017 elaborates on this aspect. It reads "No other decisions made by the umpires are eligible for a Player Review with the exception of Fair
Catch/Bump Ball (even after the third umpire has been consulted and the decision communicated)."
Therefore, the batsman can make a request for the review. The outcome of this review can be 1. Out, 2. Not out, 3. Four runs or 4. Six runs.
Comment: The paragraph immediately preceding 3.1.2 states that players may request review of any umpire decision concerning whether or not a batsman is out. If no other decision can be reviewed, then no review may be conducted on whether or not a Boundary 4 (or 6) has been scored.
Comment: Further, the Cricket World Cup is played under its own playing conditions, and all international Test/ODI/T20 playing conditions now in force date from September 2018.


What is the area of the shaded region in the circle?

Question:
Kindly don't mind the pencil marks. Please also include the solution, thank you!
Comment: Why did you ask about a circle and tag it spherical trig?  Is this in 2D or 3D?  Please make it clear. In 2D you want to compare a [circular sector](https://en.wikipedia.org/wiki/Circular_sector) to a triangle.  In 3D you want a [spherical cap](https://en.wikipedia.org/wiki/Spherical_cap). -1
Comment: I apologize, I'm unfamiliar to this site. Anyway, it's a 2D figure.
Comment: The fact that the radius is $12$ cm says if you draw radii to the points where the chords intersect the circle you get equilateral triangles. Can you compute the area of those?  Can you compute the area of the sectors?  Where are you stuck?
Answer: To find the area of the shaded portion of the circle, we need to find the area of the 2 segments(they are equal) and subtract that area from the area of the circle
1) lets label the points (points of the intersection of the line with the circle) on the left A and B, and the center O. Since the diameter is 12cm, then the radius is 6cm, then triangle ABC is equilateral, then The angle AOB=pi/3
2) Find the area of the sector AOB. A(AOB)=pir^2((pi/3)/2pi)=6pi
3) Find the area of the triangle AOB. A=rrsin(pi/3)1/2 = 9sqrt(3)
4) The area of the segment is 6pi-9sqrt(3)
5) The area of the circle is pir^2 = 36pi
6) and finally, the area of the shaded portion is:
A = 36pi-2*(6pi-9sqrt(3)) = 36pi-12pi+18sqrt(3) = 24pi+18sqrt(3)
Hope this helps
Comment: Please use the inbuilt math typeset!


Centralizar a legenda de uma imagem figcaption

Question: Não consigo centralizar a legenda da imagem em relação a imagem. Já tentei com text-align: center; mas não deu certo. Segue o código:

 Miami Heat in a game opening

Comment: Pode fornecer o CSS usado também?
Answer: Os elementos na tag figcaption não são propriamente alinhados consoante a posição da imagem na tag img, são alinhados consoante a a tag figure, ou seja, quando você define uma propriedade css, text-align="center", o que fazes é alinhar o texto ao centro de figure e não de img.
Algo que podes fazer para corrigir isto, é definir um tamanho para a tag figure, e em seguida, atribuir uma propriedade width ao css de img com 100% do valor, que será igual ao tamanho total desse container (figure). Assim o texto ficará sempre alinhado ao centro da imagem, e do próprio container.
figure {
    width:500px;
    height:500px;
}
figure img {
    width:100%;
}
figcaption p, i {
    text-align:center;
}

NOTA: figcaption p, i repara na vírgula entre os 2 elementos (p, i), sem ela a referência seria ao elemento i dentro do elemento (p), com a vírgula a propriedade aplicada, seria para o elemento p e o elemento i dentro da tag figcaption.
Answer: Basta atribuir um display block no i:
figcaption p i {
  display: block;
  text-align: center
}


Get Force of long Touch on UIButton

Question: In my app I have a button that is controlled by the amount of force applied, but I can't seem to reliably get updates for the force value.
Right now, I am only registering touches through touchesBegan, touchesMoved, and touchesEnded, which works most of the time but not always.
It is possible to place your finger on the screen and apply pressure without triggering a touchesMoved event. If you press the screen hard (enough to max out the force value) and don't move your finger around, it only calls touchesBegan with the initial (~0) force and doesn't call touchesMoved until you wiggle your finger or release pressure so the force can change from max.
This means there is no way of telling that the user is currently pressing down hard. Does anyone know of a way to constantly poll for touches and read their force value? Is there some other way of reading touchscreen information besides the touch events?
This function purely relies on force touching, so I don't care about compatibility for users without 3D Touch, have it turned off, or accessibility accommodations. Thanks!
EDIT: I seem to have misidentified the problem. The touchesBegan (and beginTracking) events are not called when pressing down hard without moving until ~1 second after the press. When they are, the max force is shown (meaning the current, not beginning value) I have tested that this is true in other apps and it takes some practice to get right. Could this be the system anticipating some peek behavior and withholding the touch? Is there any way around it?
Answer: Do not use touchesBegan method with UIButton subclass. Instead of this simply override these two methods..
class Button: UIButton {
    override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
        //This is the alternate method of touchesBegan
        return true
    }
    override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
        //This is the alternate method of touchesMoved
        let force = touch.force
        return true
    }
}

Comment: This is very useful! Unfortunately, after implementing your suggestion, I realized my issue was slightly different than what I originally thought and this solution suffers from the same problem. See my edit to the question.

Get Force of long Touch on UIButton


Pearson correlation coefficent in slices of tissues

Question: I m a PhD student in the biomedical field. I have an issue about the use of Pearson correlation coefficent (PCC) in the context of my experimental procedure.
I have several slices of tissue where I measured the content, the localization and the intensity of two proteins. So I have obtained two images of the same tissues but on two different colour channels; the first is green and is related to the protein x and the second is the red channel and it is related to the protein y. Well, in order to evaluate the co-localization of the two proteins in the same tissue I used the PCC between the green and red channels of the images (considering the pixels of the image as the bins for the analysis). This shows, how much the two proteins co-localizate in the same slice of tissue.
I repeated the measurements on three similar tissues for 4 groups. So, I have 4x3 PCC.
The question is: to evaluate the difference among the groups, is it correct to take a mean and a SEM of each of the 4 groups and to use a t-test statistics (if the prerequisites for t-testing are met) to assess if there is a significant variation of PCC and thus of the co-localization of the two protein, among the 4 groups? Is this correct for evaluating three or more PCC?
Could it be better to do a regression of the points?
This below is an example to explain the starting dataset:
       r    pixel       var_r tissue timepoint(hours)
1  -0.06 480.4290 0.002070824 liver  0
2   0.19 545.2076 0.001707259 liver  0
3  -0.01 391.8333 0.002558124 liver  0
4   0.29 582.2123 0.001443316 liver  20
5   0.46 436.5935 0.001426960 liver  20
6   0.29 543.9229 0.001545105 liver  20
7   0.14 638.7524 0.001507143 liver  40
8   0.44 428.2363 0.001522064 liver  40
9   0.39 332.3729 0.002169563 liver  40
10  0.40 481.4496 0.001468625 liver  75

Comment: Based on your description it sounds as though you have a nested data structure, where your individual pixels are nested within tissue. It boils down to an issue of non-independence as it may not be defensible to assume that the error terms from pixel to pixel in a given subject's tissue are independent (which is an assumption of Pearson's correlation as well as OLS regression). You may want to consider a [mixed effects model](https://en.wikipedia.org/wiki/Mixed_model) that can account for your nested data structure.
Comment: Thanks for your answer. In bibliography pearson s and mander s coefficent have been already used for this problem. The difficult is when you want to evaluate the variation of the pcc across a condition (time or drug treatment)
Comment: This now sounds sort of like a meta-analytic problem, where you want to take several effect sizes (i.e., Pearson's correlations) that have already been reported, and determine whether other factors (i.e., treatment or time) moderate the size of Pearson's r. Is that sort of on target?
Comment: Yes! You went exactly to the point of the problem
Answer: I am actually in the midst of performing my own meta-analysis on a separate topic. However, the problem is generally similar in that I want to aggregate associations across a number of reports. For the sake of simplifying this example, I am going to try to provide some additional context to this problem.
Let's say you have 3 different tissues with ~25 correlations each for each pair of proteins you are interested in. So that is a total of 75 effect sizes. And for simplicity's sake, let's say that you are interested in just evaluating a single moderator for the time being (drug treatment A vs. drug treatment B). You would also need sample size (number of pixels that went into each correlation) and the variance term for each effect (which can be calculated using the formula here). Armed with this information you can get a data set that looks something like this (I simulated this data for illustration purposes):
> head(DF, n=10)
       r    pixel       var_r drug tissue
1  -0.06 480.4290 0.002070824    B kidney
2   0.19 545.2076 0.001707259    B kidney
3  -0.01 391.8333 0.002558124    B  liver
4   0.29 582.2123 0.001443316    A   lung
5   0.46 436.5935 0.001426960    B  liver
6   0.29 543.9229 0.001545105    A kidney
7   0.14 638.7524 0.001507143    B   lung
8   0.44 428.2363 0.001522064    A   lung
9   0.39 332.3729 0.002169563    A   lung
10  0.40 481.4496 0.001468625    A  liver

Next, I need to add a few binary predictors so I can include them in the final model.
#Need to recode predictors - so that they are included as binary predictors...
DF$drug_bin<-ifelse(DF$drug=="A", 1, 0)
DF$liver<-ifelse(DF$tissue=="liver", 1, 0)
DF$kidney<-ifelse(DF$tissue=="kidney",1,0)
DF$lung<-ifelse(DF$tissue=="lung", 1, 0)

The resulting dataframe looks something like this now:
> head(DF, n=10)
       r    pixel       var_r drug tissue drug_bin liver lung kidney
1  -0.06 480.4290 0.002070824    B kidney        0     0    0      1
2   0.19 545.2076 0.001707259    B kidney        0     0    0      1
3  -0.01 391.8333 0.002558124    B  liver        0     1    0      0
4   0.29 582.2123 0.001443316    A   lung        1     0    1      0
5   0.46 436.5935 0.001426960    B  liver        0     1    0      0
6   0.29 543.9229 0.001545105    A kidney        1     0    0      1
7   0.14 638.7524 0.001507143    B   lung        0     0    1      0
8   0.44 428.2363 0.001522064    A   lung        1     0    1      0
9   0.39 332.3729 0.002169563    A   lung        1     0    1      0
10  0.40 481.4496 0.001468625    A  liver        1     1    0      0

Now using the metaSEM library in R, it is pretty straightfoward to perform this analysis. The model will address whether the correlation between the two proteins differs as a function of drug treatment, controlling for tissue type (not sure if that is a sufficient simplification of one of your aims, but let's roll with it for illustrative purposes)
> fit<-meta(y=r, v=var_r, x=cbind(drug_bin, liver, kidney), data = DF)
> summary(fit)

Call:
meta(y = r, v = var_r, x = cbind(drug_bin, liver, kidney), data = DF)

95% confidence intervals: z statistic approximation
Coefficients:
             Estimate  Std.Error     lbound     ubound z value  Pr(>|z|)
Intercept1  0.1291222  0.0383024  0.0540509  0.2041935  3.3711 0.0007486 ***
Slope1_1    0.1127022  0.0389916  0.0362800  0.1891243  2.8904 0.0038473 **
Slope1_2    0.1060882  0.0454696  0.0169693  0.1952070  2.3332 0.0196395 *
Slope1_3   -0.0650920  0.0480204 -0.1592103  0.0290263 -1.3555 0.1752565
Tau2_1_1    0.0258275  0.0044716  0.0170634  0.0345917  5.7759 7.652e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Q statistic on the homogeneity of effect sizes: 1699.04
Degrees of freedom of the Q statistic: 74
P value of the Q statistic: 0

Explained variances (R2):
                           y1
Tau2 (no predictor)    0.0342
Tau2 (with predictors) 0.0258
R2                     0.2444

Number of studies (or clusters): 75
Number of observed statistics: 75
Number of estimated parameters: 5
Degrees of freedom: 70
-2 log likelihood: -56.98144
OpenMx status1: 0 ("0" or "1": The optimization is considered fine.
Other values may indicate problems.)

In this example, we are primarily concerned with the intercept, which is the average correlation between the two proteins when taking drug B (B was coded as 0 and A as 1 in the syntax above), and Slope_1, which is the difference in the average correlation between between drug A and drug B users. This model would suggest that on average, the correlation is higher for drug A users, controlling for tissue type.
This is a more simplified version of what you were interested in, but hopefully it helps generate some ideas about approaches you could take.
Comment: Wow your wonderful example is really similar to that one I would like to describe in my case. The difference is only at level of the drug treatment. In my case I haven't a drug treatment but I would like to evaluate the variation of colocalization in the liver across the time. Do you think that is matematically incorrect to mediate two or more PCC and to evaluate the variation at each time-point with a t-test? I will post a code to better describe my situation in a dataframe pandas.
Comment: You may instead then want to calculate the difference between two dependent non-overlapping correlations and the difference's variance based off of the formulas presented [here](http://psycnet.apa.org.proxy-um.researchport.umd.edu/journals/met/12/4/399/). Overall the article is fairly useful, but pay special attention to the formulas that extend from page 409 to 410. Then instead of r and its variance you would input change in r and the variance for the change in r into the data sets above.
Comment: I understand, but I can't open the link that you posted above. It's needed the authentication.
Comment: Here is the link in its complete form: http://psycnet.apa.org/journals/met/12/4/399/
Comment: It's a very interesting article! But, what do you think in regard the projection of r pearson's coefficient into a z-scale? It's seems to be quite similar to those proposed in the article, right?
Comment: As long as you are pooling the standard error correctly given that you have two dependent correlations for each tissue (Pre and Post) you should be fine to use a z-transformation. I am pretty sure that same article has the necessary formula in that case as well, and though that author makes a big push for the use of confidence intervals, what really matters is extracting the correct formula for the standard error of the difference of the two correlations.


Batch file process status

Question: Im trying to make the status set to true when the process is found but i keep getting an error saying '/nh is not availible at this time' Does anyone know how to fix?
@echo off
@color 02
@set Status=false

if ('tasklist /nh /fi "imagename eq RobloxPlayerBeta.exe"') (
    Status=true
    echo found!
) else (
    echo Returned.
    Status=false
)

pause

Answer: You can't use the output of commands as variables unless you're in a for /F loop. However, if you only want to see if a process is running, you can just pipe the output of tasklist to a find command.
tasklist|find "RobloxPlayerBeta.exe"
if %errorlevel% equ 0 (
    set status=True
    echo found!
) else (
    set status=False
    echo Returned.
)
pause

Batch file process status


ubuntu, folder perms, drwxrwx---, php user in group, can't create file

Question: i'm stuck & need help understanding file create permission for members of group.

in php, i want to fopen / create a file in a folder that is owned by mysql:mysql
(for importing data into mysql)
folder -ld
drwxrwx--- 2 mysql mysql 4096 Dec 14 14:33 /var/lib/mysql-files

php runs as user www-data
i added 'www-data' user into group 'mysql'
sudo usermod -a -G groupName userName

verified
sudo groups www-data
    www-data : www-data mysql

it appears my php user account 'www-data' has write permissions to the folder through group membership, but I get an error 13 'permission denied'.

while typing this question, a similar question (https://serverfault.com/a/534000/65092)
had an answer that the parent folders (/var and /var/lib) need to have 'x' permissions for the user or group, I understand that to mean:
php user 'www-data' needs to be able to look inside /var , to read /lib , to read /mysql-files .
/var = drwxr-xr-x 16 root root
/var/lib = drwxr-xr-x 62 root root

and it appears this is already enabled.

any suggestions or comments?
thanks.
Comment: Check http://serverfault.com/questions/477877/unix-overwriting-a-file-written-by-another-user-in-same-group
Comment: MySQL only needs to be able to read the file, for a `LOAD DATA INFILE` bulk load. You do not need to write it in a directory that MySQL owns; `/tmp` would suffice.
Comment: @MikeVelazco thanks, i used setgid, but it did not solve the issue, however reading more about umask, led me to setfacl, and ultimately to a solution, which i will explain in my answer below.
Comment: @MichaelHampton mysql has --secure-file-priv option ON, therefore I must write the "data-to-be-imported" file in that specific folder.
Answer: Solution:
I applied Mike's suggested link solution of
sudo chmod g+s /var/li/mysql-files

(which is supposed to set the group id of any new created files equal to the group of it's parent folder), but I was still unable to create a file in that folder using php.
Upon further reading, I learned that permissions are applied after login (duh, of course), but since user www-data did not have a password and cannot login, I needed to reboot the server, to see if the new permissions would take affect.
Next I tested the file creation thru php from a terminal, but it still did not work. I soon realized the cli of php was launched from my user account on the terminal, therefore it was not running as user www-data, therefore permission denied. I launched php from the terminal to run under user www-data by sudo -u www-data php -a and Viola! the file was created.
checking the file permissions after creation, the owner was www-data, the group was properly set to the group of it's parent folder, however the write permission was not set. Further reading about umask led me to use  sudo setfacl -d -m group:mysql:rwx /var/lib/mysql-files
(to setup an access control list to enable write permission for the group for new files created in the folder. it appeared the write permission of the folder was already enabled for groups, so I'm not sure why this extra step was needed.)
A further test from the command line running php as user 'www-data' passed.
A test using the full php script passed.
Thanks!


Unable to connect to the mongodb instance running in a docker container from outside

Question: The following code snippet is a part of my "docker compose" file and as you see, the internal port of 27017 was mapped to 37017 to prevent colliding with the MongoDB instance running on the host development machine:
version: '3.4'

services:
  mongo:
    image: mongo
    container_name: mongodb
    restart: always
    ports:
      - 27017:37017

I use Compass when trying to connect to this mongo instance in docker and the following connection string, but Compass fails to connect to the database:
mongodb://host.docker.internal:37017

What is missing in this configuration keeping me from connecting to the mongodb in docker?
Comment: Your `ports:` are backwards: you're mapping port 27017 on the host (...which should have a conflict?) to port 37017 inside the container, but there's nothing listening there.  If the client is also in a container, you might attach it to the same network (or run it in the same Compose file) and use `mongodb://mongo:27017` to connect; this doesn't need or use `ports:` and won't conflict with a non-container MongoDB.
Answer: The credit to this answer goes to David Maze. Switching the port numbers addressed the problem. The correct yaml looks like below:
version: '3.4'

services:
  mongo:
    image: mongo
    container_name: mongodb
    restart: always
    ports:
      - 37017:27017


Symbolic Logic Proof of Associativity

Question: I am currently a math student in cal $b$. I know a super intelligent person that is trying to teach me symbolic logic. We've been doing okay until we've hit associativity. My "teacher" (the intelligent one) said it wasn't proved in his class and he's never seen a proof for it (that doesn't use demorgans laws). I'd love to see a proof without using DeMorgan's laws.
So If anyone knows it here's what I'd like to see.
Prove $pv(qvr)\Rightarrow(pvq)vr$
I have most of the basic theorems and such including commutivity and the contrapositive proved, but no DeMorgan's.
Thanks guys, Have fun!!
Comment: Isn't associativity an axiom of propositional logic?
Comment: A truth table will clinch it. Boring, but not too hard (only 8 rows), and guaranteed to work.
Comment: It would be interesting to see a proof tree for this.
Comment: I have no idea why you would think DeMorgan would even help with this ... Anyway, a basic truth-table will do the trick.
Comment: @Bram28, If you're studying a formal deduction system (e.g. [Natural Deduction](https://en.wikipedia.org/wiki/Natural_deduction)) then it's not trivial at all that truth tables would give the same results. (See some discussion on wikipedia [here](https://en.wikipedia.org/wiki/Propositional_calculus#Soundness_and_completeness_of_the_rules).)
Comment: @MarkS. I don't understand why a truth-table would give a different result (namely, that the two statements are indeed equivalent) than a formal proof would show, unless the proof system is unsound or incomplete of course.
Comment: @Bram28 Of course every standard deduction system for propositional logic is sound and complete, but if you're interested in proving things from the standpoint of the deduction system, going through the metaproof that truth tables always work is much longer than just proving the claim directly in your deduction system.
Comment: @MarkS. I still don't understand ... truth-tables seem pretty easy compared to some proof systems. In fact, I see in your post that with that particular proof system used there the proof seems pretty involved.
Comment: @Bram28, Truth tables are absolutely easy to use, which is why a textbook in logic might spend time giving a metaproof that they give the same answers as the deduction system used in the book (by showing soundness and completeness). But at the high-school level, it's common just to say "it's intuitively obvious that these would give the same results as things like modus ponens" and call it a day.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/55803/discussion-between-mark-s-and-bram28).
Comment: @MarkS. Oh, I see now what you mean! Yes, it is indeed not obvious that any proof system would reach the same conclusions as a truth table.  But since truth-tables reflect the very semantical definitions of the logical operators involved, I would say that the task is to show a specific proof system is sound and complete, rather than to show that a truth-table is sound and complete: a truth-table systematically explores all possible truth-assignments ... Which is exactly the basis of how we define our semantics. ... Continued...
Comment: @MarkS. In other words, a truth-table, by its very method of exhaustively exploring all truth-assignments, is automatically sound and complete (if one gets the wrong answer, it is because one made a mechanical mistake in evaluating the statements involved). But for a proof system it is not at all obvious that it would soundly and completely capture the defined semantics of the operators involved, which is why all the meta-level proofs are for proof systems. Put differently yet: if a truth-table and a proof system reach different conclusions, then I blame the proof system, not the truth-table.
Comment: @Bram28, I agree with what you said, but I assume the OP was not looking for a truth table/semantics explanation since they mentioned DeMorgan's laws and this would be much easier to do if you allow truth tables.
Comment: @MarkS. OK, that makes sense! That was not clear to me from the question, but I can understand you interpreted it that way!
Comment: @MarkS. Just added my own formal proof!
Comment: @MarkS. Also added an algebraic proof. Given the reference to DeMorgan, maybe that is what the OP was looking for ...
Comment: @aucbrink  Please see the comments, answers, and the fact that your question has been put On Hold:  can you please specify what kind of proof you are looking for? Thanks!
Comment: I see. Yes, I failed to mention that I wanted to avoid truth tables, just because I wanted the algebraic proof. Also yes I've been working in Natural Deduction. I failed to mention all that as I still have tons to learn about all this proofy stuff. I will add this info to my question.
Comment: I will have an update to my question soon. Thanks guys for all your help, one of the proofs in particular is really helpful, I just need to prove one of the equivalencies.
Comment: I found something that works (or at least satisfies my curiosity)! Thanks for your help! The proof that mentions exportation is particularly helpful.
Comment: To explain the vague entry, I had no idea there where so many different methods and systems of proofs and have yet to learn what system my "teacher" and I are using. I have a ton to learn, but thanks so much guys!
Answer: To prove $p\lor(q\lor r)$ implies $(p\lor q)\lor r$, assume $p\lor(q\lor r)$ is true, and then, using that assumption, show that $(p\lor q)\lor r$ is true.

Thus, assume $p\lor(q\lor r)$ is true.

Then $p$ is true, or $q \lor r$ is true.

Suppose first that $p$ is true.

Then the truth of $p$ implies the truth of $p \lor q$, which in turn implies the truth of $(p\lor q)\lor r$, as required, so this case is done.
Next suppose $q \lor r$ is true.

Consider two subcases ...

Suppose first that $q\,$ is true

Can you finish it?
Answer: The OP has not specified what sort of deduction system they're using (natural deduction?), a computer-verified proof is available at this page on Metamath.
Basically, the proof steps are:

A tautology version of disjunction introduction lets us write $\varphi\to(\varphi\lor\chi)$
An "in the consequent" version allows us to introduce $\psi$ to the above to get $\varphi\to\left(\psi\lor(\varphi\lor\chi)\right)$
The other tautology version lets us write $\chi\to(\varphi\lor\chi)$
An "on both sides" version allows us to introduce $\psi$ to both sides of the above to get $(\psi\lor\chi)\to\left(\psi\lor(\varphi\lor\chi)\right)$
Finally, a theorem about combining two different implications with disjunction of the antecedents lets us take the things from lines 2 and 4 to get the desired $\left(\varphi\lor(\psi\lor\chi)\right)\to\left(\psi\lor(\varphi\lor\chi)\right)$

This proof and its required theorems have been verified in a certain system with only a few axioms discovered by Jan Łukasiewicz (Wikipedia's explanation, Metamath's explanation). The proof ultimately relies on a list of things* that are all numbered less than 400 except for orim12i #504 and orim2i #506. Since DeMorgan's laws are #476, #477, #478, and #484, this proof doesn't use DeMorgan's laws.

*Unfortunately, it's not feasible (certainly not readable) to reproduce the entire tree down to the axioms, but I can list what is used. Specifically, the proof relies on: the four syntax definitions that say its valid to use logical symbols (negations, implications, biconditionals, and disjunctions), the axioms and deduction rule (Simp, Frege, Transp., and Modus Ponens), the definition of or in terms of negation and implication, and the following 63 theorems:
$\begin{matrix}
\text{a1i}&\text{mpdd}&\text{con1i}&\text{sylbi}\\
\text{a2i}&\text{pm2.43i}&\text{con3d}&\text{bi2}\\
\text{mpd}&\text{syl6c}&\text{con3rr3}&\text{bicom1}\\
\text{syl}&\text{con4d}&\text{pm3.2im}&\text{bicomi}\\
\text{mpi}&\text{pm2.21d}&\text{impi}&\text{biimpri}\\
\text{mp2}&\text{pm2.21}&\text{expi}&\text{pm2.53}\\
\text{id}&\text{pm2.24}&\text{simprim}&\text{pm2.54}\\
\text{idd}&\text{notnot2}&\text{simplim}&\text{orrd}\\
\text{a1d}&\text{con2d}&\text{bi1}&\text{jaoi}\\
\text{a2d}&\text{mt2d}&\text{bi3}&\text{olc}\\
\text{sylcom}&\text{nsyl3}&\text{impbii}&\text{orc}\\
\text{syl5com}&\text{con2i}&\text{impbidd}&\text{orcd}\\
\text{com12}&\text{notnot1}&\text{impbid21d}&\text{olcd}\\
\text{syl5}&\text{con1d}&\text{impbid}&\text{orim12i}\\
\text{syl6}&\text{mt3d}&\text{dfbi1}&\text{orim2i}\\
\text{pm2.27}&\text{nsyl2}&\text{biimpi}&\text{}\\
\end{matrix}$
Answer: From your question it is not clear what kind of proof you are looking for, so I will give a couple of different proofs.
First, a formal semantical one.  That is, using the basic truth-functional definition of $\lor$:
$p \lor (q \lor r)$ is false iff
both $p$ and $q \lor r$ are false iff
$p$, $q$, and $r$ are all false iff
both $p \lor q$ and $q$ are false iff
$(p \lor q) \lor r$ is false
This of course also means that $p \lor (q \lor r)$ is true iff $(p \lor q) \lor r$ is true. Hence, they are equivalent.
Second, a formal derivation or formal proof. Now, there are many different proof systems, so if you were looking for one of these, you should have specified the inference rules that would be allowed, but in the absence of that, here is a formal derivation style proof in a fairly standard Fitch-style natural deduction type formal proof:

Finally, given your comment not to use DeMorgan, I suspect that you are looking for an algebraic proof. Now again, that means that you will have to tell us what equivalences we are allowed to use, but let's assume the following fairly standard equivalences:
Commutation
$p \land q \Leftrightarrow q \land p$
$p \lor q \Leftrightarrow q \lor p$
Double Negation
$\neg \neg p \Leftrightarrow p$
Implication
$p \rightarrow q \Leftrightarrow \neg p \lor q$
Exportation
$p \rightarrow (q \rightarrow r) \Leftrightarrow (p \land q) \rightarrow r$
With these, you can do the following:
$p \lor (q \lor r) \Leftrightarrow$ (Commutation)
$p \lor (r \lor q) \Leftrightarrow$ (Double Negation x 2)
$\neg \neg p \lor (\neg \neg r \lor q) \Leftrightarrow$ (Implication x 2)
$\neg p \rightarrow (\neg r \rightarrow q) \Leftrightarrow$ (Exportation)
$(\neg p \land \neg r) \rightarrow q) \Leftrightarrow$ (Commutation)
$(\neg r \land \neg p) \rightarrow q) \Leftrightarrow$ (Exportation)
$\neg r \rightarrow (\neg p \rightarrow q) \Leftrightarrow$ (Implication x 2)
$\neg \neg r \lor (\neg \neg p \lor q) \Leftrightarrow$ (Double Negation x 2)
$r \lor (p \lor q) \Leftrightarrow$ (Commutation)
$(p \lor q) \lor r$

Symbolic Logic Proof of Associativity


is it possible to prevent duplicate entry in the multiline textbox?

Question: what I'm trying to do is I want to try prevent duplicate entry from the multiline textbox . From what I know for Multiline , all of them is in one string. You can search but you cannot remove a line. Or is there any possible method to remove duplicate entry in a multiline textbox?
Answer: Preventing duplicate input in the first place is not really practical. Removing duplicate input is easy:
myTextBox.Lines = myTextBox.Lines.Distinct().ToArray()

Oops, just realised this is ASP.NET.  You could still do this:
myTextBox.Text = String.Join(Environment.NewLine,
                             myTextBox.Text.Split({Environment.NewLine}, StringSplitOptions.None).Distinct())

You'd have to postback to do that though.  Maybe you want to do it in client-side script, although you didn't say so.
Comment: I've tried it, it just doesn't work for me.Thank for the response tho. But how is it to apply to a client side script?
Comment: It works if you do it properly, so you didn't do it properly. As fore doing it client-side, if that is the question you want answered then put it in the question, not in a comment on an answer. Also, add appropriate tags to your question to indicate that this is actually a scripting question and not a VBV.NET question.
Comment: okay I've tried it again and it works. I just placed it wrongly at the previous try. Thank you for the help


What does this exception mean? and how do i solve this? java

Question: I am using IcePDF component to view pdf in JApplet on my web page. But for some reason i get this error. Can anybody tell why is this happening and how to solve it?
Exception in thread "thread applet-applet.KitKitApplet.class-1" java.lang.StackOverflowError
    at java.util.PropertyPermissionCollection.implies(Unknown Source)
    at java.security.Permissions.implies(Unknown Source)
    at sun.security.provider.PolicyFile.implies(Unknown Source)
    at java.security.ProtectionDomain.implies(Unknown Source)
    at java.security.AccessControlContext.checkPermission(Unknown Source)
    at java.security.AccessController.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPermission(Unknown Source)
    at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
    at java.lang.System.getProperty(Unknown Source)
    at org.icepdf.core.util.Defs.property(Defs.java:59)
    at org.icepdf.core.util.Defs.property(Defs.java:63)
    at org.icepdf.core.util.Defs.property(Defs.java:63)
    at org.icepdf.core.util.Defs.property(Defs.java:63)
    at org.icepdf.core.util.Defs.property(Defs.java:63)
    at org.icepdf.core.util.Defs.property(Defs.java:63)
    at org.icepdf.core.util.Defs.property(Defs.java:63)

Answer: Looks like you've run into this bug. The program is trying to read a system property that the applet sandbox won't allow it to read, and the ensuing SecurityException is not handled correctly by IcePDF.
Comment: Hi Michael,
But i have downloaded the latest version 4.0.1. Should i just quit using this component? or is there some alternative available?
Comment: @Nitesh: Unfirtunately, the bug has not been fixed yet. See if the bug report leads you to information about how to work around this problem in your particular case; you could also use a debugger to find out which system property the program is trying to access and how to avoid this.
Answer: This exception is caused when the current thread has exhausted it's stack space. This can happen when a function has recursed too many times, typically as a result if a non-terminating recurson.
Answer: you have something compiled without debug symbols that is why you see Unknown Source everywhere. The main thing is pretty self evident, your SecurityManager isn't setup with the correct permissions to do java.lang.System.getProperty(). You need to configure the applet security permissions to let that library access whatever property it is trying to get. You will probably have to Sign your Applet for your code to work.


Number Theory Problem That I don't Know Has a Solution

Question: Let $x$ and $n$ be positive integers. For what values $x$ and $n$ satisfy $x^2+615=2^{2n}$? Express as an ordered pair $(x,n)$.
Comment: Goodness, have you even tried to look for *examples* yourself first?  Just TRY SOMETHING and tell us what you found before asking others for help. (If $n$ is really meant to be there with the first power then you are trying to solve a congruence mod 4.)
Comment: The problem typed out wrong, srry
Comment: Ok, i forgot to bracket the exponent if you couldn't tell... chill :)
Comment: No, I couldn't tell earlier.  People post all kinds of questions here, some of which are dead easy and I figured this was yet another one like those.  Now I see your corrected question has some meat to it.  Still, you should do some numerical testing yourself first to check for any low-hanging solutions (say, with $1 \leq n \leq 50$) and report what you find as part of asking your question.  Also, what is the background for this: tell us where this question is coming from and if you have ever seen how to solve anything like this before.
Answer: $$615=2^{2n}-x^2=(2^n-x)(2^n+x)$$
Since $615=3 \cdot 5\cdot 41$ and $2^n+x>2^n-x$ there are few possible solutions:
$$2^n+x= 615 \\
2^n-x=1$$
or
$$2^n+x=205  \\
2^n-x=3$$
or
$$2^n+x= 123 \\
2^n-x=5$$
or
$$2^n+x= 41 \\
2^n-x=15$$
Now, simply solve each system, and check if $n$ is an integer. Note that this happens exactly when the sum on the RHS is a power of 2, which is only the case for $123+5=128$.
Comment: ok, I get it! At first, I combined the $2^2n$ into $4^n$ and didn't get much. Turns out, it was meant to be used for difference of squares. Thanks!
Answer: $(2^n-x^2)(2^n-x^2)=615=3\cdot5\cdot 41$. Only
$2^n-x^2 = 5$ and $2^n+x^2 = 123$ equations gives solution and we find $(x,n)=(59,6)$
Answer: One answer is  $ 59^2+615 = 2^{2*6}$ so the pair is $(59, 6)$ you can find this by trying numbers, (I used a script).
$$
x^2+615=2^{2n} = 4^n
$$
$$
log_4{(x^2+615)}=n
$$
You need to try different x values until you get an integer answer
Comment: I'm not sure such brute force calculation will help charaterize _all_ such number pairs.
Comment: since OP hasn't shown any effort in solving this I just wanted to give him one solution so he can use that to test his method. But since he didn't show us anything he tried I am not going to solve his homework quite yet.
Comment: I agree about that, but I don't think it should be posted as an _answer_ then; it's more of a comment.


Which type of strings to use on an inexpensive mandolin?

Question: I just received an inexpensive mandolin to see how I would like playing it before I buy a better quality instrument. I am sure that the strings that came on this instrument are of poor quality and they are VERY difficult to fret.
Should I be using silk and steel strings or maybe some other variety that would be more playable?
Comment: I have removed the request for recommendation - as that type of question is off topic here.
Answer: I worked in a guitar store, and I can tell you that you want anything that says "extra light". Now, to most brands, that means a specific mm measurement, but it will vary from brand to brand. But most of our brands were in the same range. So get anything that says "extra light" and make note of the mm measurement. If that still feels too thick, get smaller.
And don't spend to much. As a beginner, you can't tell the difference between cheap or expensive strings yet. (Heck, I still can't!)


Inference rules in ZFC

Question: I'm relatively new to formal logic.  I have found a list of ZFC axioms on Wikipedia, but do not know what the rules of inference are.  Is there a resource for what these inference rules are, or could someone list them for me?  I have a copy of Mendelson's text on formal logic, so I can consult that for further reading once I know what ZFC's inference rules are.
Comment: http://en.wikipedia.org/wiki/First-order_logic
Comment: Well, $\sf ZFC$ is extralogical. The inference rules are logical. These are different parts of the system.
Comment: I do not know what extralogical means, unfortunately.  Which inference rules should I use to prove theorems in ZFC?  Or is there something I am missing?
Comment: The logic is the underlying "CPU" and $\sf ZFC$ is the assembly code in which we write. Extralogical means that it's not a part of the CPU itself, so to speak. The inference rules are part of the underlying CPU, and $\sf ZFC$ is part of the program.
Comment: http://en.wikipedia.org/wiki/List_of_rules_of_inference - Does that contain all of the ones I would need?
Answer: ZFC is a first-order theory with a classical first-order logic with identity. If textbooks sometimes don't specify a particular system of logic for ZFC it is because it doesn't matter so long as it is a full classical system. You could use the ugly system in Mendelson's book, a natural deduction system, a sequent calculus, a tableaux system ... it won't matter because if there is a proof from the ZFC axioms to the conclusion $\phi$ in one system,  there will be a proof in the others. So just assume your favourite presentation of first-order logic is in play, and off you go ...
Comment: What's the precise meaning of "full classical system"?

Inference rules in ZFC


No response after executing .sh file and no logs are stored

Question: I have RHEL 6.5 server. I am trying to upgrade  a software. As per the procedure, i executed the file ./upgrade.sh.
I do not see any response from CLI or GUI. Ideally a upgradation window should pop up. But that is not happening.
Moreover, I am not finding any logs regarding this in /var/log/messages.
There is no restrictions on the permissions.
Comment: We don't know anything about the software you are upgrading and how this `upgrade.sh` script is working. This question can not be answered.
Comment: In other words, add more information about your current setup, the software you tried to update and output in its logs.
Comment: I'm voting to close this question as off-topic because it should be addressed to the vendor.
Answer: I recommend contacting the support team of the organization who made that software.  Unless you provide more details about the software that you are using, or at least the content of the upgrade.sh script, we probably won't be able to help you any further.


Proof by Iteration

Question: It seems that I suffer the "too-much-logic-too-pedantic-too-confused"-disease. (You know? This very disease which lets you doubt everything and lets you yell for formalized proof. It's annoying, especially in real life.)
The last days I've been trying to understand a certain argument which uses "iteration" (it is out of Hatcher's "Algebraic Topology", the proof for proposition 2B.1. a), page 169 -- but it doesn't matter, I would say).
The generalized problem
Generalized, what I want to proof are the following two claims:
1) For an intervall $I$, assuming $A(I)$, one can construct an intervall $J$, such that

$J \subsetneqq I$,
$length(I) = 2\cdot length(J)$ and that
$A(J)$ holds.

2) Then, by iteration, one has intervals
$$I_0 \supsetneqq I_1 \supsetneqq \ldots$$
with $A(I_m)$ for every $m\in\mathbb{N}$.
Where I stumble
While 1) just goes through by instantiating an arbitrary interval $I$ and constructing a $J$, part 2) seems quite hard to conclude, but just in a detail. In fact, 1) is the inductive step with the exception, that I have nothing which is a successor of something, as $J$ was constructed within the induction.
If I would have a sequence of intervals $\{I_m\}_{m\in\mathbb{N}}$, then of course, I could just run induction on it, using 1). But $I$ and $J$ are not related in this sense.
Ideas
The very first idea is: I'm just confused. This can happen from time to time, especially the more (mathematical) logic I consume. And I did.
The second idea: The sequence of intervals I would need to construct unravels (don't know if this is the right word here...). Take $I_0 = [0,1]$ for example. There are two possibilities (in Hatcher's proof) $[0,\frac{1}{2}]$ and $[\frac{1}{2},1]$. If it was the first, the sequence continues with either $[0,\frac{1}{4}]$ or $[\frac{1}{4},\frac{1}{2}]$. As I know the borders explicitly, maybe I could modify 1) into something where
$$J = [\frac{b}{2},b]\text{ or }[a,\frac{b}{2}]$$ and use this? Not sure.
The third idea: putting the borders as a "depending sequence", $a_{n+1} = f(a_n)$, but I have no clue what that should be.
Thanks for any help.
PS: Of course, this is just about formalizing as I cannot see how to give a more pedantic proof. I see the argument, but saying "then run the argument again", which has to happen infinite times, is not a proof at all, as it would need infinite steps.
Comment: @MauroALLEGRANZA Note the post says $I_{n+1}\subsetneq I_n$.
Answer: It follows from the following.
Dedekind's Recursion Theorem: Given a set $X$, $x\in X$ and a map $f\colon X\to X$, there exists (one and only one) function $h\colon \mathbb N\to \mathbb X$ such that $h(0)=x$ and $\forall m\in \mathbb N(h(m+1)=f(h(m)))$.
(For a proof see, for instance, Thomas Jech's Introduction to Set Theory, (chapter 3, section 3). I finally found it on wikipedia too).
In the notation of the theorem, let $X$ be the set of all intervals, let $f$ be one of the maps given by the process described in 1 and let $x=I$. The function $h$ is your desired sequence of intervals.
Comment: I don't think this is a disease at all. Some people like [to hurl the term *pedantic* at other's people feet as if it is something dirty, but I will pick up that label and wear it as a badge of honor](https://www.youtube.com/watch?v=zTFp7WG9J-E&t=83s). Your question is very pertinent and I wish I had thought of that before having been presented with the theorem above. Only after seeing it, did I realise its importance and how much humans take for granted.
Comment: Thank you very much for your answer (and also for your nice comment). In the middle of "working" mathematicians, my kind of interests seem to always miss the point – so it's good to see another perspective; and a recognition of my very interests: rather logic then topology.  ; )
Answer: You are actually using induction in step 2) as well, start with $I_0: A(I_0)$ (I assume $A$ is a predicate?). The step 1) gives you a new interval $I_1$ s.t. $A(I_1), I_1 \subsetneq I_0, l(I_1) = \frac12 l(I_0)$.
Now you've shown (in step 1)) that given $I_n, A(I_n)$ you can construct $I_{n+1}\subsetneq I_n, A(I_{n+1}), l(I_{n+1}) = \frac12 l(I_n)$. By induction (in step 2)) you obtain a sequence of intervals
$$(I_k)_{k=0}^\infty \text{ such that } A(I_k), l(I_k) = 2^{-k} l(I_0) \text{ and } I_j \subsetneq I_k\qquad\forall k,j\in\mathbb N, k<j$$
What you want to do with this sequence (build it's limit?) is up to you now.

The predicate used for induction will be
$$\phi(n): \exists! (I_k)_{k=0}^n, \underbrace{l(I_k) = 2^{-k} l(I_0), I_j \subsetneq I_k, A(I_k), R(I_k) = I_{k+1} \ \forall k,j\in\{1,\ldots, n\}, k<j}_{P((I_k))}$$
Where $R$ is the construction in step 1).
Then $\phi(n)$ gives you a sequence $(I_k)_{k=0}^n$ and you extend it to a sequence $(I_k)_{k=0}^{n+1}$ in the inductive step. This new sequence is a "witness" for $\phi(n+1)$ by construction, so you show $\phi(n) \Rightarrow \phi(n+1)$
The last step now is a short proof of the claim
$$\exists! (I_k)_{k=0}^\infty : P((I_k)_{k=0}^N)\ \forall N\in\mathbb N$$
Existence follows by defining $I_k := R^k(I_0)$ the $k$-times application of the reduction.
Uniqueness is given by contradiction: Assume $(I_k)$ and $(J_k)$ satisfy the claim but $I_N \ne J_N$. Then since $P((I_k)_{k=0}^N)$ and $P((J_k)_{k=0}^N)$, $\phi(N)$ implies $(I_k)_{k=0}^N = (J_k)_{k=0}^N$ contradicting the assumption.
Comment: Thanks for your answer! I thought about this, but the problem is, induction only gives you an universal quantifier in front of a fixed formula. Something like: if $\phi(0)$ and $\forall n. \phi(n)\Rightarrow\phi(n+1)$ then $\forall n. \phi(n)$. But you cannot obtain a "sequence of intervals" or anything "by induction." You would need to know all the $I_m$ before, to define such a $\phi(n)$.

So what I was asking for (now I realized) was a $\phi(n)$ which fits my needs, but it seems that this is not possible in this very case. (At least as long as I want to go with Hatcher's argument.)
Comment: @aphorisme Indeed the predicate will be
$$\phi(n): \exists (I_k)_{k=0}^n, l(I_k) = 2^{-k} l(I_0), I_j \subsetneq I_k, A(I_k) \ \forall k,j\in\{1,\ldots, n\}, kn$. This is similar to the proof of the theorem mentioned by GitGud.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/20388/discussion-between-aphorisme-and-alexr).
Comment: Thanks a lot for your effort.

Proof by Iteration


Linux - Bare Metal Restore from a Tar file

Question: I make a backup of my Debian webserver on a daily basis. A full backup on Sunday, and differentials each other day of the week.
The backup is made with Tar. I backup the whole system into the Tar file.
If the HDD on my webserver dies, I got all my backups in a safe place.
But what would be the best way to do a Bare Metal Restore on a new HDD with a differential backup make the previous day? Can I boot with a boot cd, and then format a new HDD and untar the backup file into it? How do I do that exactly?
EDIT:
This is my backup script:
#!/bin/sh
# Backup script

BACKUPDIR="/backups"
BACKUPFILE=$BACKUPDIR/backup_$(date +%y-%m-%d).tgz

if [ ! -d $BACKUPDIR ]; then
        mkdir $BACKUPDIR
fi

if [ -f $BACKUPFILE ]; then
        echo "Backup file already exists and will be replaced."
        rm $BACKUPFILE
fi

apt-get clean

tar czpf $BACKUPFILE --same-owner \
--exclude=$BACKUPDIR \
--exclude=/boot/grub/menu.lst* \
--exclude=/home/error.log \
--exclude=/proc \
--exclude=/media \
--exclude=/dev/* \
--exclude=/mnt \
--exclude=/sys/* \
--exclude=/cdrom \
--exclude=/lost+found \
--exclude=/var/cache/* \
--exclude=/tmp / 2>/home/error.log

Comment: Why not trying to use `backuppc`. It is an easy-to-use backup solution and it has a nice web interface.
Comment: It may help if you show us the command with options you use to create the backup.
Comment: As previous comments said, we can't answer the "How to restore" if we don't know how you backup exactly. There are many ways to backup "with tar", and we don't know which one you chose.
Comment: If you want to learn how to do this, I suggest you try doing a Debian install without using the installer as in boot of a livecd, then use debootstrap.
Comment: This is not a differential backup, is a full backup.
Answer: Simply restoring the HDD will not be enough, you're probably will want your boot record too which I hardly believe exists in your backup (am I wrong?, it's better for you if i do!)...
Lest assume you got the server to the point it can boot (i personally prefer creating the additional partition mounted to /boot which will have kernel and initrd with busybox or something similar to allow you basic maintenance tasks). You can also use a live CD of your Linux distribution.
Mount your future root partition somewhere and restore your backup.
tar was created for tapes so it support appending to archive files with same name. If you used this method just untar -xvpf backup.tar -C /mnt if not you'll need to restore "last sunday" backup and applying deferential parts up to needed day.
You should keep in mind that there is a lot of stuff that you should not backup, things like: /proc, /dev, /sys, /media, /mnt (and probably some more which depend on your needs).
 You'll need to take care of it before creating backup, or it may became severe pain while in  restore process!
There is many points that you can easily miss with that backup method for whole server:

commands used to restore may vary to much depend on real commands you used to backup your data.
boot record
kernel image and modules are ok and match each other after restore
ignore unwanted stuff on backup not restore.
etc, etc...

Some good points on that exact method can be found on Ubuntu Wiki:BackupYourSystem/TAR. Look for Restoring.
BTW:

have you ever tried to restore one of your backups?
have you considered changing your backup strategy?
have you considered separation of data you need to backup and system settings (there is some good stuff today to manage system configuration so it can be easily resorted with zero pain like puppet or chief, so only thing you should care about is real data)

P.P.S
I recommend reading couple of Jeff Atwood posts about backups  http://www.codinghorror.com/blog/2008/01/whats-your-backup-strategy.html and http://www.codinghorror.com/blog/2009/12/international-backup-awareness-day.html
Answer:
Boot with some LiveCD
Partition the new hard drive.
Mount it somewhere, everything in the right place (if you have separate /var or /home then do so)
Copy the files back
Make not backupped directories with appropriate access rights and owners, like /mnt /proc /sys /dev/
Create file in dev with: MAKEDEV generic
bind mount /proc /sys /dev to the target
Chroot to the target directory
update /etc/fstab according the new UUIDs
update-grub and grub-install
umount everything and reboot
Answer: Have a look at http://www.mondorescue.org/ as it can do online backups without shutting down the machine.
Answer: if differential backups are not mandatory, the best option for baremetal backup/restore is ddrescue : http://www.gnu.org/software/ddrescue/ddrescue.html


Combining vector spaces

Question: what are 3 ways to combine distinct vector spaces?
I can think of the Cartesian product and have proved it is a vector space
I can't think of any others.
Comment: There are many ways to combine vectors spaces. Perhaps you meant combine them in such a way that the result is also a vector space?
Answer: I would say

Tensorial Product
Direct Sum
Intersection
Answer: If $F$ and $G$ are vector subspaces of a vector space $E$ you can also consider $F\cap G$, or $E/F$. If you have a scalar product defined in your space you could also consider $F_\perp$. The dual space $E^*$.
Comment: the vector spaces are distinct, does that just mean they're not the same?
Comment: I don't have any context of your exercise, but I would say so. Anyway, if you are not allowed to use different subspaces of the same space you could consider the following: $E$ and $F$ distinct vector spaces. $L(E,F)$ is the space of linear maps $f:E\rightarrow F$. And, as I said before, the dual space.

Combining vector spaces


For positive integers a, b, with b odd, show that $(a+1)\mid (1 + a^b)$.

Question: $(1)$ Let a and b be positive integers and suppose b is odd. Show that $1 + a^b$  is divisible by $a+1$. $\;\quad( $Suggested method is using the geometric sum formula.)
$(2)$ Let k be a positive integer. Show that if $2^k + 1$ is prime, then $k=2^n$ for some $n \in \mathbb N$.
Comment: For the first one: let $m=a+1$. Now, you just need to prove that $1+(m-1)^b$ is a multiple of $m$. Use the binomial theorem.
Comment: Typically, try to limit your questions to one per post. Arguably, these might be seen as sufficiently related, so I'm not going to make an issue of it.
Comment: Ok sorry. Will do that in the future :)
Comment: See [$a^n - 1 \mid a^m - 1$ if and only if $n \mid m$](http://math.stackexchange.com/questions/413473) for a more general result.
Answer: If $k$ is not a power of two, so $k$ has an odd factor $b$, write $2^k+1=a^b+1$ for suitable $a$.
How does that answer question 2?
Answer: For your first question:
$ \sum_{k=0}^{b-1} (-a)^k = \frac{1-(-a)^b}{1+a} = \frac{1+a^b}{1+a} $ , since b is odd: $-(-a)^b = -(-1)^b*a^b = 1*a^b =a^b $
=> $(1+a)*[\sum_{k=0}^{b-1} (-a)^k] = 1 + a^b $
Hence $(a+1)|(a^b +1)$
Hint: For the second question, you might want to use the first question..


Manipulação de arquivo .txt

Question: Eu tenho uma página em php chamada "emblema.php", e um arquivo .txt chamado "emblema.txt". Neste arquivo .txt, é onde eu coloco título, código e descrição do emblema.
O código é assim:
badge_name_CÓDIGO DO EMBLEMA=NOME DO EMBLEMA (TITULO DO EMBLEMA)
badge_desc_CÓDIGO DO EMBLEMA=DESCRIÇÃO DO EMBLEMA

E eu queria saber se dava para eu criar isso sem ser manualmente.Obviamente, para adicionar um emblema, eu preciso duplicar este conteúdo e mudar o código, título e descrição.
Eu queria fazer com que fosse adicionado assim:
Comment: Sim, é possível. Veja as funções `fopen`, `file_put_contents`, `fread`, `fwrite` (as mesmas da linguagem C). Elas vão te ajudar.
Answer: Você pode utilizar a função file_put_contents para manipular um arquivo.
Criando um arquivo TXT
O file_put_contents pode ser utilizado para criar um arquivo com um determinado conteúdo.
Exemplo:
$filename = __DIR__ . '/arquivos/log.txt';

file_put_contents($filename, 'meu conteúdo');

O exemplo acima fará com que seja criado o arquivo log.txt dentro da pasta arquivos do diretório atual do seu script, definido pela constante mágica __DIR__.
Porém, nesse exemplo, o arquivo será sobrescrito caso ele exista. E, a cada nova requisição, sempre mudará o conteúdo.
Adicionando dados ao final de um arquivo TXT
Se você quer sempre quer adicionar um novo conteúdo no final do arquivo, você poderá utilizar a flag FILE_APPEND como parâmetro de file_put_contents.
Assim:
file_put_contents($filename, 'meu conteúdo', FILE_APPEND);

Isso sempre criará um novo conteúdo ao final do arquivo.
Por que não usar CSV?
Como no seu exemplo me parece que você está trabalhando com dados com estruturas organizadas específicas, eu utilizaria um CSV.
O PHP manipula muito bem o CSV.
Dê uma olhada nessas explicações do Manual do PHP:
fgetcsv
fputcsv
serialização de dados
A partir das funções serialize e unserialize do PHP é possível "salvar" valores de variáveis para, mais tarde, recuperá-los. Tudo que você precisa é de um arquivo onde salvar esses dados.
Veja um exemplo.
Salvando os dados:
$serial = serialize($_POST);
file_put_contents('serial.txt', $serial);

Recuperando os dados:
$dados = unserialize(file_get_contents('serial.txt'));
print_r($dados); // Dados anterioremente salvos vindos de $_POST

Parece-me que internamente o PHP utilize essas funções para salvar/recuperar os dados da sessão ($_SESSION).
Comment: Eu não uso o CSV, pois o sistema terá de ser mudado completamente. E tipo, como faço para que a base seja feita e o código, título e descrição sejam multiplicados conforme vai criando os outros?
Comment: Você quer criar mais de um arquivo? OU quer sempre adicionar dados ao final desse arquivo?
Comment: @Train não entendi o porque não usar o CSV, para que inventar um novo tipo de documento, sendo que existe um (o CSV) que pode ser facilmente manipulado. Ao meu ver não precisa mudar nada na resposta, é só uma escolha de formato, você não definiu que tipo de formato você quer na questão, então ao meu ver CSV é totalmente funcional para o seu caso :)
Comment: @WallaceMaxters A melhor situação é a *serialização de dados*, porém isto `file_put_contents('serial.txt', $serial);` não dividiria por `ID`, o melhor seria cada TXT ser um ID (código do emblema) ou você fornecer um exemplo que trabalhe com quebra de linha e usar `fgets`+`foef`+`while` :) Só uma ideia.
Comment: `file_get_contents` é a simplificação de `fgests` + `foef` + `while`. Não há por que usá-los como exemplo. Vou elaborar uma forma de fazer toda essa operação com o `file_get_contents` e `serialize`.

Manipulação de arquivo .txt


Erro na requisição

Question: Ola estou com um pequeno problema é o seguinte estou criando uma firebase cloud function que faz uma requisição aqui esta o codigo:
const functions = require('firebase-functions');
var axios = require('axios');
exports.get_video_info = functions.https.onCall(function(data){

  var url = "https://youtube.com/get_video_info?video_id="+data.id;
  return axios.get(url)
});

Mas quando chamo a função aparece o seguinte erro no google cloud:
Unhandled error { Error: getaddrinfo EAI_AGAIN youtube.com:443
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:67:26)
  errno: 'EAI_AGAIN',
  code: 'EAI_AGAIN',
  syscall: 'getaddrinfo',
  hostname: 'youtube.com',
  host: 'youtube.com',
  port: 443,
  config:
   { adapter: [Function: httpAdapter],
     transformRequest: { '0': [Function: transformRequest] },
     transformResponse: { '0': [Function: transformResponse] },
     timeout: 0,
     xsrfCookieName: 'XSRF-TOKEN',
     xsrfHeaderName: 'X-XSRF-TOKEN',
     maxContentLength: -1,
     validateStatus: [Function: validateStatus],
     headers:
      { Accept: 'application/json, text/plain, */*',
        'User-Agent': 'axios/0.18.0' },
     method: 'get',
     url: 'https://youtube.com/get_video_info?video_id=R3cbfZKfmkE',
     data: undefined },
  request:
   Writable {
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     domain:
      Domain {
        domain: null,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        members: [] },
     _events:
      { response: [Function: handleResponse],
        error: [Function: handleRequestError] },
     _eventsCount: 2,
     _maxListeners: undefined,
     _options:
      { maxRedirects: 21,
        maxBodyLength: 10485760,
        protocol: 'https:',
        path: '/get_video_info?video_id=R3cbfZKfmkE',
        method: 'get',
        headers: [Object],
        agent: undefined,
        auth: undefined,
        hostname: 'youtube.com',
        port: null,
        nativeProtocols: [Object],
        pathname: '/get_video_info',
        search: '?video_id=R3cbfZKfmkE' },
     _ended: true,
     _ending: true,
     _redirectCount: 0,
     _redirects: [],
     _requestBodyLength: 0,
     _requestBodyBuffers: [],
     _onNativeResponse: [Function],
     _currentRequest:
      ClientRequest {
        domain: [Object],
        _events: [Object],
        _eventsCount: 6,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: false,
        sendDate: false,
        _removedConnection: false,
        _removedContLen: false,
        _removedTE: false,
        _contentLength: 0,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Object],
        connection: [Object],
        _header: 'GET /get_video_info?video_id=R3cbfZKfmkE HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nUser-Agent: axios/0.18.0\r\nHost: youtube.com\r\nConnection: close\r\n\r\n',
        _onPendingData: [Function: noopPendingOutput],
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'GET',
        path: '/get_video_info?video_id=R3cbfZKfmkE',
        _ended: false,
        res: null,
        aborted: undefined,
        timeoutCb: null,
        upgradeOrConnect: false,
        parser: null,
        maxHeadersCount: null,
        _redirectable: [Circular],
        [Symbol(outHeadersKey)]: [Object] },
     _currentUrl: 'https://youtube.com/get_video_info?video_id=R3cbfZKfmkE' },
  response: undefined }

Já não sei mais o que faço.
Answer: Isso pode estar relacionado ao plano do Firebase Cloud. Existe uma limitação de acesso a APIs quando o plano é gratuito. Neste post se descreve um problema como o seu:
https://stackoverflow.com/questions/40182121/error-getaddrinfo-eai-again
Uma das formas de contornar este problema sem ter que fazer o upgrade do plano seria trocar o endereço da API, ao invés de acessar os endpoints do domínio youtube.com, utilizar as API do domínio googleapis.com
No link do tutorial abaixo, feito este mês, se mostra como fazer isso. Neste link, se utilizou o PowerShell para acessar a API, mas, você pode considerar apenas os endereços que ele acessou e utilizar o Axios para fazer a comunicação
https://lazywinadmin.com/2019/04/retrieving_youtube_videos_information_with_powershell.html#
Comment: Depois de eu ver sua resposta eu fui pesquisar e no site do Google Cloud sobre o preço vi que no plano gratuito só pode fazer chamadas as APIs da Google

Erro na requisição


What is y_pred in keras?

Question: In the keras-ocr example, they are using CTC loss function. In the model compile line,
# the loss calc occurs elsewhere, so use a dummy lambda function for the loss
model.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=sgd)

they are using a dummy lambda function with y_true,y_pred as inputs and y_pred as output. But y_pred was already defined previously as the softmax activation.
y_pred = Activation('softmax', name='softmax')(inner)

If y_pred is softmax activation then where is CTC loss being used?. Does y_pred mean the output of the last previous layer, in keras irrespective of whether it has already been defined?. (because in the code, the layer's output just before the compile line is CTC loss).
Answer: As it is said in the comment, the loss calculation is already done somewhere else, so the {'ctc': lambda y_true, y_pred: y_pred} just takes already pre-calculated loss in y_pred and discards y_true as not needed without any calculations.
Comment: @timedacorn nope. the `loss_out` layer computes the loss. `model.compile()` gets a lambda function, with the arbitrarily named arguments, which can be `a` and `b` or `x` and `y` or `y_pred` and `y_true`. the first argument is discarded, the second is used as the loss. argument names are chosen exclusively for easy understanding =)
Comment: "just takes already pre-calculated loss in y_pred". There is no line in the code which does that. The loss is precalculated, yes, but I can't see where it's assigned to the y_pred variable.
Comment: @timedacorn the actual loss is calculated by `ctc_lambda_func()` (line 334), which is used in building the `loss_out` layer, inside the model (lines 475 and 480).
Comment: so the loss_out layer's output is the `y_pred` value which is being passed to the model.compile right?

What is y_pred in keras?


Envio formulario para dois arquivos php

Question: Tenho uma duvida curiosa e talvez idiota, mas vamos lá.
É possível enviar os dados de um formulário para dois arquivos diferentes em php?
Comment: Seja um pouco mais especifico você quer que os dados digitados de um formulário preencham 2 bancos de dados diferentes??
Comment: Sim vai alimentar bancos diferentes ao mesmo tempo com um único formulário.
Comment: Se quiser a falar de duas `actions` do form, não creio que seja possivel
Comment: ok vou pesquisar deve haver algum resolução possível obrigado a todos se eu encontrar uma solução vou escrever aqui.
Answer: Usando PHP: Dá para enviar via post ou get para um arquivo (controller), que tratará e distribuirá os dados para os 2 arquivos distintos (models).
Usando JAVASCRIPT: Dá para você pegar os campos que quiser e enviar (via post ou get) para arquivos diferentes via AJAX.
Espero ter ajudado.
Answer: Como disse o Alan, isso é possível via AJAX.
Mesmo não conhecendo as tuas necessidades, posso afirmar que o mais "barato" será sempre fazer o processamento todo num único script PHP no lado do servidor.

Envio formulario para dois arquivos php


Size of dynamic array vs static array

Question: What is the maximum size of static array, and dynamic array? I think that there is no limit for dynamic array but why static arrays have a limited size?
Comment: In your comment to shekhar's answer you mention that, on the contrary, it dumps. Which means that it compiles. Also, by "class variable", do you mean that it's a static member?
Comment: There is no range as such. Lot depend on your machine configuration.
Comment: @Digital_Reality I asked cause `int Data[8][499][15];` fails on my computer
Comment: that is just 29MB storage. I guess, there might be some other allocation causing this.
Comment: it also depends on compiler, some compilers might move that allocation to the heap from the stack.
Comment: When you say "fails on my computer", do you mean it fails to compile or does it crash? Is that a function-local variable?
Comment: @bereal it fails to compile, It is a class variable
Comment: I guess that by "static" he means "non-static"
Answer:
Unhandled exception at 0x011164A7 in StackOverflow.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00482000)

This looks more like a runtime error. More precisely - stack overflow.
In most places the size of array is limited only by available memory. However, the limit on stack allocated objects is usually much more severe. By default, it's 1Mb on Windows and 8Mb on Linux. It looks like your array and other data already on the stack is taking more space than the limit.
There are few ways to avoid this error:

Make this array static or declare it at top level of your module. This way it will be allocated in .bss segment instead of stack.
Use malloc/new to explicitly allocate this array on heap.
Use C++ collections such as std::vector instead of arrays.
Increase stack size limit. On Linux this can be done with ulimit -s unlimited
Comment: gcc has a switch to increase stack size also. On my system it can go to over 1GB (default is 2MB).
Answer: The maximum size of an array is determined by the amount of memory that a program can access. On a 32-bit system, the maximum amount of memory that can be addressed by a pointer is 2^32 bytes which is 4 gigabytes. The actual limit may be less, depending on operating system implementation details.
Note that this has nothing to do with the amount of physical memory you have available. Even on a machine with substantially less than 1 GB of RAM, you can allocate a 2 GB array... it's just going to be slow, as most of the array will be in virtual memory, swapped out to disk.
Comment: I have struct(232 B) and allocated it this way `struct_name Data[8][499][15]; so why it fails durning compile time?
Comment: @Quest what compiler are you using and what error are you getting?
Comment: @Banthar that's all I can see: Unhandled exception at 0x011164A7 in StackOverflow.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00482000). VC++ 2013
Comment: This all might be happening because your computer environment is not fit to perform this array allocation!

Size of dynamic array vs static array


discrete random variables (vectors) and independence

Question: <code>X = [7,-5,-4,-2]
Y = [1,-1,2,-2]
</code>
Are the two random variables independent?
P(X=x) = P(Y=y) = .25 for each value of x and y.
P(X=x|Y=y) is either 0 or .25 for each x and y.
The probability of each ordered pair (i.e. (7,1), (-5,-1), (-4,2),(-2,-2) ) is also .25.
I see no relationship between X and Y; can I say they are independent?
How in general do I approach vectors like this in problems about independent random variables?
Answer: The last question is too broad without additional info about the distributions of each random variable.
Given:

$\forall x \in \{7,-5,-4,-2\}, \forall y \in \{1,-1,2,-2\}, P(X = x) = P(Y = y) = \dfrac14$
$\forall x \in \{7,-5,-4,-2\}, \forall y \in \{1,-1,2,-2\}, P(X = x \mid Y = y) \in \left\{ 0, \dfrac14 \right\}$

To show: independence of $X$ and $Y$
$$\forall x \in \{7,-5,-4,-2\}, \forall y \in \{1,-1,2,-2\}, P(X = x \mid Y = y) = \dfrac14 \stackrel{(1)}{=} P(X = x)$$
Suppose not.
\begin{align}
& \exists x \in \{7,-5,-4,-2\}, \exists y \in \{1,-1,2,-2\}, P(X = x \mid Y = y) \ne \dfrac14 \\
\stackrel{(2)}{\implies}& \exists x \in \{7,-5,-4,-2\}, \exists y \in \{1,-1,2,-2\}, P(X = x \mid Y = y) = 0
\end{align}
However,
\begin{align}
& \sum_{x' \in \{7,-5,-4,-2\}} P(X = x' \mid Y = y) \\
&= \sum_{x' \in \{7,-5,-4,-2\} \setminus \{x\}} P(X = x' \mid Y = y) \tag{*} \label1 \\
&= 1
\end{align}
Note that \eqref{1} is a sum of three nonnegative numbers, so as least one of them is greater or equal to $\dfrac13$.  This contradicts (2).  Hence $X$ and $Y$ are independent.
Comment: This addresses this specific problem, thank you. I got this problem from notes from a course; a similar problem is at http://www.math.harvard.edu/~knill/teaching/math19b_2011/handouts/19b_review_2011.pdf, about slide 7. I haven't seen anyone else talk about random vectors this way, so if there is no general approach, I am ok with that.
Comment: @cumin Next time, it's better to put the link in the question body instead of a comment, so that we know what's your course is assuming: finite probability space $\Omega$, which is not general in [tag:probability-theory] at all. (Any random variables can be regarded as a vector, and expectation is a functional on the space of random variables.)  I see that slide 7/106 is a question about [tag:dice].  You mean slide 14/106? I'm not sure about the notation. It means the same as in your [lecture notes](http://www.math.harvard.edu/~knill/teaching/math19b_2011/handouts/math19b_2011.pdf)?
Comment: @cumin In your lecture notes, a vector in $\Bbb{R^n}$ is considered to be a random variable on $\Omega = \{1,\dots,n\}$.  That's the only way to make sense of that slide.  For a finite $\Omega$, to prove that two random variables $X,Y$ are independent is to check $$\forall x,y, P(X = x \mid Y = y) = P(X = x), \text{ or equivalently} \\ E[1_x1_y] = E[1_x] E[1_y]$$  That's *the* way to show independence.  In other words, you may *classify* the entries of $X$ according to their values.  Then, in each class, see if the distribution of $Y$ has changed.
Comment: @cumin If they are independent, the distribution of $Y$ should be left unchanged.  In the question body, **your vector notation for random variables $X$ and $Y$ are not consistent with the given condition (2)**.


Logistic regression: what is the link between the binomial family and the binomial distribution?

Question: When I want to estimate a logistic regression in R, I type
lm <- glm(y ~ x, data=df, family=binomial(link="logit"))

I wonder what is the relationship between the "binomial family" and the binomial distribution.
Answer: Logistic regression in effect estimates the probability of an event happening based of the values of the independent variables, or more precisely the log-odds, a monotonic function of the probability.
Your observations are essentially cases of the event happening or not: if there is one possibility being observed for that combination of values of the independent variables then it has a Bernouilli distribution of happening or not; and if several possibilities are being observed for that combination then the number occurring has a binomial distribution (typically when the independent variables are discrete rather than continuous).  The Bernouilli distribution is just a special case of the binomial distribution.
So logistic regression estimates the probabilities which would maximise the likelihood of the observations using a binomial model, subject to the constraints of the regression.  This is what links logistic regression and binomial distributions. You do not know the parameters of the binomial distributions, so they are the binomial family.
glm in R allows other generalised linear models apart from logistic regression.  See https://stat.ethz.ch/R-manual/R-devel/library/stats/html/family.html for details on other "families" that can be used for other models, such as gaussian or poisson  or Gamma, all of which involve single types of distribution but with unknown parameters so each making up a family.