Erro ""AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 0" no Java ao tentar fazer IF

Question: Estou fazendo uma condição na execução de uma pesquisa no Java, o que acontece é que não posso ter espaço em branco, asterisco(*) ou ponto de interrogação(?) como primeiro caractere da busca. Porém o Java está me retornando o seguinte erro quando deixo o campo em branco:
Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.String.charAt(Unknown Source)
    at main.Princ$4.actionPerformed(Princ.java:255)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Condição da linha 255:
        if (Character.toString(txtConteudo.getText().charAt(0))
                        .equals(" ")
                || Character.toString(txtConteudo.getText().charAt(0))
                        .equals("")
                || Character.toString(txtConteudo.getText().charAt(0))
                        .equals("?")
                || Character.toString(txtConteudo.getText().charAt(0))
                        .equals("*")) {
            JOptionPane
                    .showMessageDialog(
                            panel,
                            "O campo de busca não pode estar vazio ou possuir \"?\", \"*\" ou espaço em branco como primeiro caracter.");

        } else {
            // executa a busca
        }

Comment: Isso não iria estourar da mesma forma? Pois se não tem char na posição 0, ao executar o método ele iria dar um throw StringIndexOutOfBoundsException, não?
Comment: @PauloRoberto como que sua sugestão na primeira linha evita a exceção? Ele vai continuar tentando acessar uma posição que não existe. A única resposta até agora responde a pergunta corretamente.
Comment: Postei uma resposta explicando melhor o que quis dizer, ficou bem simples @Strokes
Comment: Opa, desculpem. Vou postar uma resposta melhor formulada e apagar meu comentário.
Answer: O problema é que não existe nenhum char na posição 0, pois a String esta vazia. O que você tenque fazer é uma verificação antes, para ver se a String está vazia ou não.
Um possível exemplo:
if(txtConteudo.getText().length() > 0){
        if (Character.toString(txtConteudo.getText().charAt(0))
                        .equals(" ")
                || Character.toString(txtConteudo.getText().charAt(0))
                        .equals("?")
                || Character.toString(txtConteudo.getText().charAt(0))
                        .equals("*")) {
            JOptionPane
                    .showMessageDialog(
                            panel,
                            "O campo de busca não pode estar vazio ou possuir \"?\", \"*\" ou espaço em branco como primeiro caracter.");

        } else {
            // executa a busca
        }
}else
{
JOptionPane.showMessageDialog( panel,
                                "O campo de busca não pode estar vazio.");
}

Comment: `length()`, pois é um método, não um atributo
Comment: talvez tb fosse bom vc tirar a condição `.equals("")`, e colocar a msg de erro no else do primeiro if, entendeu o por quê?
Comment: desculpe, não testei o código, vou editar a resposta. Obrigado!
Comment: Sim eu entendi, mas apenas fiz o if inicial, não fiz uma análise do código que o OP postou.
Comment: sim sim, só sugeri, inclusive achei q eu tava palpitando tanto na sua que acabei não aguentando e escrevi uma resposta tb, rs..
Answer: O tamanho da sua String retornada pela operação txtConteudo.getText() tem tamanho 0, e você tenta acessar seu primeiro elemento através do comando txtConteudo.getText().charAt(0), ou seja, você está tentando acessar um caractere além do último caractere válido. Na verdade você não possui nem sequer um caractere e tenta acessar o primeiro, logo uma exceção é lançada.
Percebi que você tentou fazer tal validação através de uma das condições do seu if:
Character.toString(txtConteudo.getText().charAt(0)).equals("")

Mas a exceção é lançada antes mesmo da sua linha de código chegar até o equals(""), pois ela acontece no charAt(0), portanto, essa linha não serve para nada. Ao invés disso, verifique o tamanho da sua String ANTES de tudo, e somente depois tente acessar seus caracteres.
Exemplo:
    if(txtConteudo.getText().length() == 0 //graças ao short-circuit não compara as demais se essa condição é falsa
       || Character.toString(txtConteudo.getText().charAt(0)).equals(" ")
       || Character.toString(txtConteudo.getText().charAt(0)).equals("?")
       || Character.toString(txtConteudo.getText().charAt(0)).equals("*")) {

        JOptionPane.showMessageDialog(panel,
           "O campo de busca não pode estar vazio ou possuir \"?\", \"*\" ou espaço em branco como primeiro caracter.");
    } else {
        // executa a busca
    }

Veja a documentação StringIndexOutOfBoundsException e String length()
Comment: Testetesteteste
Answer: Você pode resolver seu problema com verificação de operador ternário atribuído diretamente na variável, sendo assim, não tendo que converte-la e a acessa-la novamente à toda verificação, poupando código desnecessário e performance:
//compare vai receber o txtConteudo na 0 se length for > 0 senão recebe ""
String compare = (txtConteudo.getText().length() > 0) ? Character.toString(txtConteudo.getText().charAt(0)) : "";
if (" ".equals(compare) || ("").equals(compare) || "?".equals(compare) || "*".equals(compare))
  JOptionPane.showMessageDialog(panel, "O campo de busca não pode estar vazio ou possuir \"?\", \"*\" ou espaço em branco como primeiro caracter.");
else
  // executa a busca

Veja como ficou simples, e também note que eu inverti a ordem do equals() para prevenir erros caso a variável à ser comparada fosse nula, é sempre melhor utilizar o equals() desta forma, prevenindo sempre NullPointerException's


Atr bands take profit and stop loss sometimes skips or randomly closes position

Question: "hello this strategy that takes profit when ATR bands from trade entry either upper or lower band is crossed, it works but sometimes tp or sl is skipped or position randomly closed."
This what happen when runs somewhat correct [1]:https://i.stack.imgur.com/Ek8GF.png
this what happens when completely wrong
[2]: https://i.stack.imgur.com/xDWR9.png
[3]: https://i.stack.imgur.com/wpS8A.png
[4]: https://i.stack.imgur.com/JvSXV.png
//@version=5
strategy("2Ma cross ATR Bands strategy", overlay = true)

// Inputs
atrPeriod = input(3, "ATR Period")
srcUpper = input(defval = close, title = "Source Upper")
srcLower = input(defval = close, title = "Source Lower")
atrMultiplierUpper = input(title = "ATR Multiplier Upper", defval = 4.0, tooltip ="3.8" )
atrMultiplierLower = input(title = "ATR Multiplier Lower", defval = 3.0, tooltip = "2.5")

// ATR
atr = ta.atr(atrPeriod)

// Plotting
plot(srcUpper + atr * atrMultiplierUpper, color = color.green)
plot(srcLower - atr * atrMultiplierLower, color = color.red)
plot(ta.sma(close,10))

// Entry condition
buysign= ta.crossover(close, ta.sma(close,10))

// Trading session
// session = input.session("0200-1600", "Session")
// t = time(timeframe.period, session)
// bgcolor(time == t ? color.rgb(76, 175, 79, 80) : na)

// Define take profit and stop loss
tp = srcUpper + atr * atrMultiplierUpper
sl = srcLower - atr * atrMultiplierLower

//place trade
if buysign
    strategy.entry("long", strategy.long)

//exit trade
if buysign
    strategy.exit("TP/SL", stop = sl, limit = tp)

Answer: With
atr = ta.atr(atrPeriod) you are always updating the value of atr.
If you look closely, your exits use the last atr value and not the one at the time of entry.
You need to use a var variable to store the atr value at the entry and then use it for your exits.
You can do something like this:
var float atr_at_entry = na
is_new_position = ((strategy.position_size[1] == 0) and (strategy.position_size !=0))  // Assuming you only go long
atr_at_entry := is_new_position ? atr : atr_at_entry  // Store the atr value if it is a new position. Otherwise, keep its old value

And then later use atr_at_entry in your TP and SL calculations.


Maximum likelihood estimation problem

Question:
In a town, there are taxis labeled from $1$ to $n$ ($n$ is the total number of taxis). We arrive in the town and see a taxi with label $100$. With the method of maximum likelihood estimation, find $n$.

The solution says $n=100$, but I can't figure out why.
Comment: While the MLE estimates $n$ to be $100$, following the German Tank Problem, the estimate will be $2\cdot 100 - 1=199$
Answer: The likelihood on this data is $1/n$ if $n\ge 100$ and zero otherwise (since a draw of $100$ is impossible if $n<100$). This is maximized for $n=100,$ so the MLE is $100.$
Comment: I would like to ask when do you use then 1/n=L(n) and since we have only one sample it means ln(1/n)=ln(L(n)) and 1/n=0 with derivation but I know it doesent make sense. So I want to know when to use logarithm and derivations
Comment: Clearly $n$ must be at least 100. To maximize the likelihood then $1/n$ needs to be as large as possible, i.e. n as small as possible. Thus $n$ must be 100.
Comment: @MirjanPecenko : Taking logarithms in MLE problems is very useful in many instances, but not this one, and you shouldn't apply it without thinking. Moreover, setting derivatives to $0$ to find maximum points is also very useful in many problems, but not in this one, and again you shouldn't apply it without thinking.
Comment: So I can apply it only when it isn't obvious what the maximum
Comment: @MirjanPecenko Applying the logarithm doesn't do anything substantial. If something maximizes $f(\theta)$ it maximizes $\log(f(\theta))$ and vice versa, and it's usually easier to work with the log since it's a sum rather than a product. But the lesson here is that maximization sometimes requires more thought than just taking a derivative. Remember from calculus: the maximum of a differentiable function can occur at a critical pt *or at one of the endpoints of the interval*. This situation is more like when it's at an endpoint (the fact that it's integer-valued complicates things as well).
Comment: In general, if one would observe more taxis, would n be equal to the greatest taxi number?
Answer: The probability that the number of the first taxi observed is $100$ is
$$
\begin{cases}
1/n & \text{if there are $n$ taxis and $n\ge100$}, \\
0 & \text{if there are $n$ taxis and } n<100.
\end{cases}
$$
So the probability is highest when $n=100,$ so that is the maximum-likelihood estimate.

Maximum likelihood estimation problem


Como iniciar um aplicação em Python junto com o Windows?(cx_freeze)

Question: Olá, estou tentando desenvolver um aplicação que se inicia junto com o windows, mas já tentei fazer com que o programa se auto copie para a pasta

"C:\Users\User\AppData\Roaming\Microsoft\Windows\Start
  Menu\Programs\Startup"

mas aparece acesso negado, eu estou utilizando Python 3.5 e o cx_freeze para gerar o executável.
Comment: Você pode compartilhar a parte do seu código usada para o programa se auto copiar?
Answer: Você poderia fazer um bat e adiciona-lo junto ao startup do PC. Assim você faria com que seu bat tivesse o seguinte conteúdo:
C:/Caminho/Do/python.exe C:/Caminho/Do/Seu/Arquivo

E se você executar você pode executar seu script. Feito este arquivo bat, basta você adiciona-lo na lista de programas a inicializarem quando seu PC inicializar.
Comment: O problema é que eu não desejo apenas no meu computador, eu desejo através do cx_freeze conseguir fazer com que ele se inicie com o windows em qualquer máquina, Obj pela resposta.
Answer: Tente utilizar a pasta

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

Não se esqueça de se certificar que está rodando seu programa como administrador.
Answer: Usar o próprio Python para isso
Você pode usar o próprio Python para escrever um arquivo .bat na pasta de inicialização de programas do Windows.
Você consegue acessar esta pasta seguindo as seguintes ordems:

Pressione Windows+r.
Digite shell:startup
Pressione Enter

Vai iniciar seu explorer, e nele irá conter esta seguinte pasta:

C:\Users\%user%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Criando um arquivo .bat nesta pasta, seu programa irá iniciar junto com Windows.
from getpass import getuser
from os import path
from sys import argv

def startup(file_path=""):
        USER = getuser()
        if(file_path == ""):
            file_path = path.dirname(path.realpath(__file__))
            bat_path = r'C:\Users\%s\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' % USER
        with open(bat_path + '\\' + "open.bat", "w+") as bat_file:
            bat_file.write(r'start "" %s' % file_path + "\\" + argv[0])
startup()

O código cria um arquivo .bat na mesma pasta que citei acima.
Você também pode modificar este programa para iniciar arquivos .exe, como você mesmo citou ali acima, estava usando cx_freeze.
Você poderia automatizar isso para o próprio script criar um executável dele mesmo. Com o próprio modulo cx_freeze.
Se você souber utilizar o cx_freeze, dá para automatizar tudo. Como neste pequeno exemplo. Em outro script:
from cx_Freeze import setup, Executable

setup(name = "startup" ,
      version = "0.1" ,
      description = "" ,
      executables = [Executable("AQUI SEU ARQUIVO PRINCIPAL")])

Não sei o que você quer fazer com esse programa no startup do Windows. Porém se a intenção for ser silencioso, como em um malware. Você poderia automatizar tudo.
Primeiro, rode seu script de criar um executável. Depois você altera a linha:
file_path = "DIRETORIO\\DO\\SEU\\SCRIPT\SCRIPT.EXE"
with open(bat_path + '\\' + "SEU_SCRIPT.EXE", "w+") as bat_file:
            bat_file.write(r'start "" %s' % file_path)


Find $ S=\frac{\cos 2x}{1\cdot 3}+\frac{\cos 4x}{3\cdot 5}+\frac{\cos 6x}{5\cdot 7}+\dots=\sum_{n=1}^\infty\frac{\cos (2nx)}{(2n-1)(2n+1)} $

Question:
Find a sum of the series:
  $$
S=\frac{\cos 2x}{1\cdot 3}+\frac{\cos 4x}{3\cdot 5}+\frac{\cos 6x}{5\cdot 7}+\dots=\sum_{n=1}^\infty\frac{\cos (2nx)}{(2n-1)(2n+1)}
$$

My attempt:
$$
\begin{aligned}
&z=\cos x+i\sin x\\
&S=\frac{1}{2}\text{Re}\sum_{n=1}^\infty\frac{z^{2n}}{2n-1}-\frac{1}{2}\text{Re}\sum_{n=1}^\infty\frac{z^{2n}}{2n+1}
\end{aligned}
$$
But calculating these sums seems a bit difficult to me. Perhaps there is a better approach to this problem?
Answer: Note that
$$1+z^2+z^4+\cdots = \frac{1}{1-z^2}.$$
Integrating both sides,
$$z+\frac{z^3}{3}+\frac{z^5}{5}+\cdots=\frac 12 (\log(1+z)-\log(1-z)) = \tanh^{-1}(z).$$
Observe that multiplying both sides by $z$ gives
$$\sum_{n=1}^\infty \frac{z^{2n}}{2n-1} = z\tanh^{-1}(z)$$
and multiplying the left hand side by $\frac 1z$ and subtracting the $1$ term gives
$$\sum_{n=1}^\infty \frac{z^{2n}}{2n+1} = -1 + \frac{\tanh^{-1}(z)}{z}.$$
Rewriting $\tanh^{-1}(z)$ as $\ln\left(\frac{1-z}{1+z}\right)$, remembering that $z$ is on the unit circle, we can draw vectors $1+z$ and $1-z$ in the complex plane. Doing some basic geometry, we can see that the angle between these is $\frac \pi 2$, and that the lengths of $1+z$ and $1-z$ are $2 \cos \left(\frac \theta 2 \right)$ and $2 \cos \left( \frac \pi 2 - \frac \theta 2 \right) = 2 \sin \left( \frac \theta 2 \right)$.
So $\frac{1-z}{1+z} = -i \cdot \tan \left(\frac x2 \right)$, and so the $\log$ of this is
$$-\frac{i \pi}{2} + \ln\left(\tan \left(\frac x2 \right)\right)$$
(since $\log(-i) = -\frac{i \pi}{2}$).
From here, everything is easily calculatable.
Comment: I'm afraid the rest is not clear, since it is quite difficult to find Re(tanh$^{-1}(z)$) :(
Comment: I mean we will have to switch back to logarithms and do something like this: Re$(X\cdot\ln(z))$=Re$(X\cdot(\ln|z|+i\cdot Arg(z)))$, and it is arduous here.
Comment: Remember that $z = e^{ix}$ is on the unit circle.
Comment: @Bonrey I've edited the solution; I've now clarified how to simplify $\tanh^{-1}(z)$, and given its real part.
Answer: $$2S=\sum_{r=1}^\infty\dfrac{\cos2rx}{2r-1}-\sum_{r=1}^\infty\dfrac{\cos2rx}{2r+1}$$
which is real part of $$\sum_{r=1}^\infty\dfrac{(e^{ix})^{2r}}{2r-1}-\sum_{r=1}^\infty\dfrac{(e^{ix})^{2r}}{2r+1}$$
$$=e^{ix}\cdot\sum_{r=1}^\infty\dfrac{(e^{ix})^{2r-1}}{2r-1}-e^{-ix}\cdot\sum_{r=1}^\infty\dfrac{(e^{ix})^{2r+1}}{2r+1}$$
$$=e^{ix}\cdot\ln\dfrac{1-e^{ix}}{1+e^{ix}}-e^{-ix}\left(\ln\dfrac{1-e^{ix}}{1+e^{ix}}-1\right)$$
$$=(e^{ix}-e^{-ix})\left(\ln\dfrac{1-e^{ix}}{1+e^{ix}}\right)+e^{-ix}$$
$$=2i\sin x\left(\ln(-1)+\ln\dfrac{e^{ix/2}-e^{-ix/2}}{e^{ix/2}+e^{-ix/2}}\right)+\cos  x-i\sin x$$
$$=2i\sin x\left(\ln(-i)+\ln\tan\dfrac x2\right)+\cos  x-i\sin x$$
Now the principal value of $\ln(-1)$ is $-\dfrac{i\pi}2$
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\underline{\underline{\mbox{Note that}}}\quad
\bbox[10px,#ffd]{\left.\sum_{n = 1}^{\infty}{\cos\pars{2nx} \over
\pars{2n - 1}\pars{2n + 1}}
\,\right\vert_{\ \color{red}{\large x\ \in\ \mathbb{C}}}}
\\[5mm] = &\
{1 \over 2}\sum_{n = 1}^{\infty}{\expo{2n x\ic} \over
\pars{2n - 1}\pars{2n + 1}} + \pars{x \to - x}\label{1}\tag{1}
\end{align}

\begin{align}
&\bbox[10px,#ffd]{{1 \over 2}\sum_{n = 1}^{\infty}{\expo{2n x\ic} \over
\pars{2n - 1}\pars{2n + 1}}} =
{1 \over 4}\sum_{n = 1}^{\infty}{\expo{2nx\ic} \over 2n - 1} -
{1 \over 4}\sum_{n = 1}^{\infty}{\expo{2nx\ic} \over 2n + 1}
\\[5mm] = &\
{1 \over 4}\sum_{n = 1}^{\infty}{\expo{2nx\ic} \over 2n - 1} -
{1 \over 4}\sum_{n = 2}^{\infty}{\expo{2nx\ic}\expo{-2xi} \over 2n - 1} =
{1 \over 4} + {1 \over 4}\pars{1 - \expo{-2xi}}
\sum_{n = 1}^{\infty}{\expo{2nx\ic} \over 2n - 1}
\\[5mm] = &\
{1 \over 4} + {1 \over 2}\,\ic\sin\pars{x}
\bbox[#eef,1px]{\expo{-xi}\sum_{n = 1}^{\infty}{\expo{2nx\ic} \over 2n - 1}}
\label{2}\tag{2}
\end{align}
Lets evaluate the $\ds{\bbox[5px,#eef]{\mbox{blue}}}$ expression in (\ref{1}):
\begin{align}
&\bbox[#eef,1px]{\expo{-xi}\sum_{n = 1}^{\infty}{\expo{2nx\ic} \over 2n - 1}} =
\expo{-xi}\sum_{n = 2}^{\infty}{\expo{nx\ic} \over n - 1}\,{1 + \pars{-1}^{n} \over 2} =
{1 \over 2}\sum_{n = 1}^{\infty}{\pars{\expo{x\ic}}^{n} \over n}
\bracks{1 - \pars{-1}^{n}}
\\[5mm] = &\
{1 \over 2}\sum_{n = 1}^{\infty}{\pars{\expo{x\ic}}^{n} \over n} -
{1 \over 2}\sum_{n = 1}^{\infty}{\pars{-\expo{x\ic}}^{n} \over n} =
-\,{1 \over 2}\ln\pars{1 - \expo{xi}} +
{1 \over 2}\ln\pars{1 + \expo{xi}}\label{3}\tag{3}
\end{align}
Replacing (\ref{3}) in (\ref{2}):
\begin{align}
&\bbox[10px,#ffd]{{1 \over 2}\sum_{n = 1}^{\infty}{\expo{2n x\ic} \over
\pars{2n - 1}\pars{2n + 1}}} =
{1 \over 4} + {1 \over 4}\,\ic\sin\pars{x}
\bracks{\ln\pars{1 + \expo{x\ic}} - \ln\pars{1 - \expo{x\ic}}}
\end{align}
The final result is found by replacing this result in (\ref{1}}:
\begin{align}
&\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!\!
\bbox[10px,#ffd]{\left.\sum_{n = 1}^{\infty}{\cos\pars{2nx} \over
\pars{2n - 1}\pars{2n + 1}}
\,\right\vert_{\ \color{red}{\large x\ \in\ \mathbb{C}}}}
\\[5mm] = &\
{1 \over 2}
\\[2mm]  + & {1 \over 4}\,\ic\sin\pars{x}
\bracks{\ln\pars{1 + \expo{x\ic}} - \ln\pars{1 - \expo{x\ic}} -
\ln\pars{1 + \expo{-x\ic}} + \ln\pars{1 - \expo{-x\ic}}}
\label{4}\tag{4}
\end{align}

When $\ds{x \in \mathbb{R}}$, (\ref{4}) is reduced to:
\begin{align}
\mrm{f}\pars{x} & =
\left\{\begin{array}{lcl}
\ds{\mrm{f}\pars{-x}} & \mbox{if} & \ds{x < 0}
\\[2mm]
\ds{{1 \over 2} - {1 \over 4}\,\pi\sin\pars{x}}                         & \mbox{if} & \ds{0 \leq x \leq \pi}
\\[2mm]
\ds{\mrm{f}\pars{x - \pi}} && \mbox{otherwise}
\end{array}\right.
\end{align}
$\ds{\mrm{f}\pars{x}}$ Graph" />


Unable to provision VMs using SoftLayer API and Ansible due to 500 Server Errors

Question: We're using Ansible to provision a set of virtual machines. To do this, we're using the softlayer.py script found here, as part of ansible: https://github.com/ansible/ansible/blob/devel/contrib/inventory/softlayer.py
We are running: ansible-playbook manifest.yml -s -i softlayer.py
manifest.yml contains a bunch of ansible tasks that should provision our VMs. Here is an example with all sensitive information removed:
- gather_facts: false
hosts: localhost
name: Build Servers
sudo: false
tasks:
- local_action:
cpus: 4
datacenter: sjc03
dedicated: false
disks:
- 25
domain: test.example.sample.net
hostname: machine-one
hourly: false
memory: 8192
module: sl_vm
nic_speed: 1000
os_code: UBUNTU_14_64
private: true
private_vlan: 1234567
ssh_keys: []
tags:
- tagone
- tagtwo
- tagthree
- tagfour
- test.example.sample.net
name: Build machine-one server

Below is the full error output, if it's of any use:
Inventory script (softlayer.py) had an execution error: Traceback (most recent call last):
File "/opt/test/job/softlayer.py", line 207, in <module>
SoftLayerInventory()
File "/opt/test/job/softlayer.py", line 84, in __init__
self.get_all_servers()
File "/opt/test/job/softlayer.py", line 204, in get_all_servers
self.get_virtual_servers()
File "/opt/test/job/softlayer.py", line 188, in get_virtual_servers
instances = vs.list_instances(mask=mask)
File "/usr/local/lib/python2.7/dist-packages/SoftLayer-4.0.3-py2.7.egg/SoftLayer/managers/vs.py", line 141, in list_instances
return func(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/SoftLayer-4.0.3-py2.7.egg/SoftLayer/API.py", line 362, in call_handler
return self(name, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/SoftLayer-4.0.3-py2.7.egg/SoftLayer/API.py", line 330, in call
return self.client.call(self.name, name, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/SoftLayer-4.0.3-py2.7.egg/SoftLayer/API.py", line 226, in call
return self.transport(request)
File "/usr/local/lib/python2.7/dist-packages/SoftLayer-4.0.3-py2.7.egg/SoftLayer/transports.py", line 162, in __call__
raise exceptions.TransportError(ex.response.status_code, str(ex))
SoftLayer.exceptions.TransportError: TransportError(500): 500 Server Error: Internal Server Error for url: https://api.softlayer.com/xmlrpc/v3.1/SoftLayer_Account

What could be causing this?
Answer: This seems to be specific to calling  getVirtualGuests on https://api.softlayer.com/xmlrpc/v3.1/SoftLayer_Account with a particular set of credentials / on a particular account and with a particular mask.
<?xml version='1.0'?>
<methodCall>
<methodName>getVirtualGuests</methodName>
<params>
<param>
<value><struct>
<member>
<name>headers</name>
<value><struct>
<member>
<name>SoftLayer_ObjectMask</name>
<value><struct>
<member>
<name>mask</name>
<value><string>mask[id,globalIdentifier,hostname,domain,fullyQualifiedDomainName,primaryBackendIpAddress,primaryIpAddress,datacenter,tagReferences.tag.name,lastKnownPowerState.name,powerState,maxCpu,maxMemory,activeTransaction.transactionStatus[friendlyName,name],status]</string></value>
</member>
</struct></value>
</member>
<member>
<name>SoftLayer_AccountObjectFilter</name>
<value><struct>
</struct></value>
</member>
<member>
<name>authenticate</name>
<value><struct>
<member>
<name>apiKey</name>
<value><string>xxxxxxx</string></value>
</member>
<member>
<name>username</name>
<value><string>example</string></value>
</member>
</struct></value>
</member>
</struct></value>
</member>
</struct></value>
</param>
</params>
</methodCall>

POSTing that XML to the xmlrpc endpoint above I hit the 500 error with the particular credentials mentioned in the original question. If I use a different set of (valid) credentials, I'm returned my list of servers as I'd expect. If I supply invalid credentials then I receive "Invalid API token." back as I'd expect.
The surprising thing in the 500 case is that it does seem to have run the query (as SoftLayer-Total-Items: 70 is returned in the header), but the HTTP code is 500 and the body of the response is empty.
If I inspect the http requests made by slcli -vvv vs list (which succeeds) I see that it sends a different mask to the same method, so perhaps the mask in the ansible softlayer.py is relevant.
Answer: According to the exception, there exist a lot of 500 errors for many reasons:

Timeouts
Out of memory
Invalid requests
Bugs

I'm not sure how Ansible is handling and sending the parameters to SoftLayer API Python Client, but a quick view, Ansible is using SoftLayer-4.0.3 and SoftLayer API Python Client has released the v5.2.0, we recommend to use this, in order to get the last updates and avoid possible issues.
I did some tests using SoftLayer Python Command-line Interface sending the same parameters that you tried and it is working fine:
slcli vs create --hostname=machine-one --domain=stest.example.sample.net --cpu 4 --memory 8192 -o UBUNTU_14_64 --datacenter=sjc03 --billing=monthly --tag tagone,tagtwo,tagthree,tagfour,test.example.sample.net --public --network 1000 --private

I recommend to submit an issue in the below link, in order that Ansible can verify and fix it:
https://github.com/ansible/ansible/issues


What's a good way to dynamically generate PNGs in ASP.NET?

Question: I have a need to generate small PNG images in ASP.NET.  The images could have things like simple geometries and text.  Is it necessary to use a 3rd party library to generate images in ASP.NET?
Answer: Something like this?
Bitmap bmp = new Bitmap(300, 300);
Graphics g = Graphics.FromImage(bmp);

g.Clear(Color.Transparent);
g.FillRectangle(Brushes.Red, 100, 100, 100, 100);

g.Flush();
bmp.Save("test.png", System.Drawing.Imaging.ImageFormat.Png);

(from here)
You'd have to play around with the contents of the image of course, but the graphics namespace probably has most of what you need.
Comment: For some reason, I never noticed the Clear method. I've always manually used FillRectangle for the entire surface, so thanks kprobst. :)
Answer: You can do that just using the Bitmap and other graphics related classes in the .NET framework.
        Bitmap bmpImage = new Bitmap(width, height);
        Graphics gr = Graphics.FromImage(bmpImage);
        //Draw using gr here

        //stream to the client
        Response.ContentType = "image/png";

        //write to memory stream first, png can only be written to seekable stream
        using(MemoryStream memStream = new MemoryStream())
        {
          bmpImage.Save(memStream, ImageFormat.Png);
          memStream.WriteTo(Response.OutputStream);
        }
        bmpImage.Dispose();

Comment: You *must* wrap a using clause around all System.Drawing objects (Graphics, Bitmap). MemoryStream doesn't even do anything a dispose time, ironically.


sp_nonblocking_write does sends the first byte only, whereas sp_blocking_write is working properly [under Windows]

Question: Under Windows XP SP3, I have tried to use sp_nonblocking_write function to send AT command to a phone connected through usb, this function always returns 1 (sends only the first byte), whereas sp_blocking_write function works without problems.
What could be the problem ?
Thank you for your understanding.
Comment: the answer is in this post:
[http://stackoverflow.com/questions/43821881/asynchronous-writefile-works-only-on-step-by-step-debugging-this-drives-me-insa](http://stackoverflow.com/questions/43821881/asynchronous-writefile-works-only-on-step-by-step-debugging-this-drives-me-insa) Thank you.
Answer: it was a bug. I have fixed it.


How to provide a specific node template in a custom module

Question: I am using a custom module and using Bartik theme(from Drupal 8 core module) and hence need to define a content type specific template like node--[type].html.twig
I added hook_theme in my custom module as follows
function custom_autofill_reference_theme($existing, $type, $theme, $path){
   drupal_set_message($path);
   return [
    'node' => [
      'path' => $path . '/templates',
      'template' => 'node',
    ],
  ];
}

but not sure on how to add a content type specific template in a custom module without the need to create a custom theme?
Comment: You mean a content type specific template in a custom module without the need to create a custom *theme*?
Comment: yes @4k4, I found the solution , I will send an answer for the same.
Answer: /**
 * Implements hook_theme().
 */
function custom_theme() {
  return [
    'node__custom_content_type' => [
      'base hook' => 'node',
    ],
  ];
}

Then make sure that you have the content type template under custom/templates/node--custom-content-type.html.twig


React : Call a function from inside render function

Question: I have referred to couple of similar questions, but I have a situation little different.
Call a React Function from inside Render
How to Call a Function inside a Render in React/Jsx
React: Cant call a function inside child component

export default class CodeEditor extends React.Component {

  appendAssets(asset) {
    console.log(asset)
    this.refs.editor.editor.insert(`player.asset('${asset}')`)
    this.refs.editor.editor.focus()
  }

  render() {
    function sequenceHierarchy (data, outputArray) {
      level++
      data.forEach(function (asset){
        outputArray.push(<li className={`level_${level}`}><button onClick={_ => this.appendAssets(asset.name)}>{asset.name}</button>
)
        if(asset.children.length) {
          sequenceHierarchy(asset.children, outputArray)
        }
      })
      level--
    }
  }

}

So the onClick of button inside sequenceHierarchy function has to call appendAssets. Of course since this wouldn't be able to call it as it is not the part of this component, I also tried with just appendAssets(asset.name), still it gives a error of Uncaught ReferenceError: appendAssets is not defined
Answer: I strongly advise you to read this answer for understanding this keyword and its behaviors inside function.
Quoting from the linked answer:

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scope, like other variables.

(Please read whole linked answer before proceeding further)
You can either set a reference to the variable which refers to correct this. See this JSFiddle
let that = this; // assign this reference to variable that.
function sequenceHierarchy (data, outputArray) {
   data.forEach((item) => {
        outputArray.push(

            <button onClick={that.appendAssets.bind(this, item)}>
               Append {item}
             </button>

      );
   })
}

or
You can use bind method to set correct this, while invoking sequenceHierarchy function as follows. See this JSFiddle
{sequenceHierarchy.bind(this, (['1', '2', '3'], []))}

or
You can use ES6 arrow function to invoke sequenceHierarchy function like this.
{() => {sequenceHierarchy(['1', '2', '3'], [])}}

All above methods will work fine.
Hope this helps :)
Comment: Thanks Hardik. That helped me out.
Comment: Glad it helped :)


How do I exclude certain commits from GitHub's stat tracking

Question: Is there any way to exclude certain commits from GitHub's stat tracking?
I occasionally need to commit a 3rd party library. As these tend to be large, they mess up the contributors data (I have 350K additions today, I'm on a roll) and code frequency charts, which is a flat line with a spike every time I check in a library.
Answer: I guess the only chance will be that you put the dependency in a separate repo (if they do not already have a git repo for it) and add it as a submodule.
This way updating to a new version will be only one commit where you update the sha1 of the submodule HEAD you are using.


Mathematical physics problem. Eletric and Magnetic field. Velocity of propagation of the electromagnetic energy.

Question:
If we define the velocity of propagation of the electromagnetic energy, for an arbitrary field in the vacuum, for $\vec{S} = U\vec{v}$ , where $U$ is the density of electromagnetic energy, then
$$\left(1-\frac{v^{2}}{c^{2}}\right)U^{2} = (U_{E} - U_{M})^{2} + \frac{\epsilon_{0}}{\mu_{0}}(\vec{E}.\vec{B})^{2}$$

I'm trying to use the equations:
$$\vec{S}=\frac{1}{\mu_{0}}(\vec{E}\times\vec{B})$$
and
$$(\vec{a}\times\vec{b})^{2} + (\vec{a}.\vec{b}) = a^{2}b^{2}$$
But I'm not getting that equality. Can someone help me?
Answer: This is straightforward. Use $c^2=1/\sqrt{\epsilon_0\mu_0}$.
\begin{align}
\left(1-\frac{v^2}{c^2}\right)U^2&=U^2-\frac{v^2}{c^2}U^2=U^2-\frac{1}{c^2}\left\|\mathbf{S}\right\|^2\\
&=\left[\frac{1}{2}\left(\epsilon_0\left\|\mathbf{E}\right\|^2+\frac{1}{\mu_0}\left\|\mathbf{B}\right\|^2\right)\right]^2-\frac{1}{c^2}\left\|\frac{1}{\mu_0}\mathbf{E}\times\mathbf{B}\right\|^2\\
&=\frac{1}{4}\left(\epsilon_0^2\left\|\mathbf{E}\right\|^4+2\frac{\epsilon_0}{\mu_0}\left\|\mathbf{E}\right\|^2\left\|\mathbf{B}\right\|^2+\frac{1}{\mu_0^2}\left\|\mathbf{B}\right\|^4\right)-\frac{1}{c^2\mu_0^2}\left(\left\|\mathbf{E}\right\|^2\left\|\mathbf{B}\right\|^2-\left(\mathbf{E}\cdot\mathbf{B}\right)^2\right)\\
&=\frac{1}{4}\left(\epsilon_0^2\left\|\mathbf{E}\right\|^4+2\frac{\epsilon_0}{\mu_0}\left\|\mathbf{E}\right\|^2\left\|\mathbf{B}\right\|^2+\frac{1}{\mu_0^2}\left\|\mathbf{B}\right\|^4\right)-\frac{\epsilon_0}{\mu_0}\left(\left\|\mathbf{E}\right\|^2\left\|\mathbf{B}\right\|^2-\left(\mathbf{E}\cdot\mathbf{B}\right)^2\right)\\
&=\frac{1}{4}\left(\epsilon_0^2\left\|\mathbf{E}\right\|^4-2\frac{\epsilon_0}{\mu_0}\left\|\mathbf{E}\right\|^2\left\|\mathbf{B}\right\|^2+\frac{1}{\mu_0^2}\left\|\mathbf{B}\right\|^4\right)+\frac{\epsilon_0}{\mu_0}\left(\mathbf{E}\cdot\mathbf{B}\right)^2\\
&=\left[\frac{1}{2}\left(\epsilon_0\left\|\mathbf{E}\right\|^2-\frac{1}{\mu_0}\left\|\mathbf{B}\right\|^2\right)\right]^2+\frac{\epsilon_0}{\mu_0}\left(\mathbf{E}\cdot\mathbf{B}\right)^2.
\end{align}


Deixar função rodando em loop até a aplicação fechar

Question: Tenho o seguinte codigo que fica trocando de imagem de tempo em tempos.
if Timer1.enabled = true then
begin
 Gauge1.Progress := Gauge1.Progress +1;
   if Gauge1.Progress=10 then
Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\2.jpg');

   if Gauge1.Progress=30 then
Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\3.jpg');

   if Gauge1.Progress=50 then
Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\1.jpg');
 end;

Como faço pra que fique rodando em loop até que a aplicação seja finalizada
Answer: Use uma estrutura de repetição par isto, vamos tentar com while:
while Gauge1.Progress < 100 do
begin
  if (Gauge1.Progress = 10) then
  begin
    Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\2.jpg');
  end
  else if (Gauge1.Progress = 30) then
  begin
    Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\3.jpg');
  end
  else if (Gauge1.Progress = 50) then
  begin
    Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\1.jpg');
  end;
  Inc(Gauge1.Progress);
end;

Ou seja enquanto a % não chegar a 100% você vai atualizando, agora você precisa encaixar essa estrutura de forma quem não pare seu sistema para executar ela! Isso já depende de quando você vai rodar essa implementação da Gauge.
Answer: Vamos lá esclarecer a sua dúvida... Você pode fazer da seguinte maneira. Dado que você já tenha incluído um componente do tipo Timer na tela chamado Timer1.
1º - Crie um evento OnTimer do componente Timer.
2º - Coloque o código, ficando parecido como este.
procedure TForm1.Timer1Timer(Sender: TObject);
begin
    Gauge1.Progress := Gauge1.Progress + 1;

    if Gauge1.Progress = 10 then
        Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\2.jpg')
    else if Gauge1.Progress = 30 then
        Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\3.jpg')
    else if Gauge1.Progress = 50 then
        Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\1.jpg');
end;

3º - Defina o tempo em que o Gauge1.Progress será incrementado, em Timer1 na propriedade Interval, lembrando que o tempo é medido em ms, ou seja, 1000 é 1 segundo. Caso seja 1 segundo o tempo definido, em 10 segundos o processo trocará a imagem para a 2.jpg, em 30 segundos 3.jpg e assim por diante.
4º - Quando você quiser iniciar essa contagem basta colocar a propriedade Enabled do Timer1 em True, e caso contrário False.
5º - Neste caso a partir de 50 a imagem sempre será a 1.jpg, digamos que quando o Gauge1.Progress chegar em 60 vamos querer iniciar a contagem novamente do 0. Então trocamos o código e colocamos algo assim:
procedure TForm1.Timer1Timer(Sender: TObject);
begin
    Gauge1.Progress := Gauge1.Progress + 1;

    if Gauge1.Progress = 10 then
        Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\2.jpg')
    else if Gauge1.Progress = 30 then
        Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\3.jpg')
    else if Gauge1.Progress = 50 then
        Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\1.jpg')
    else if Gauge1.Progress = 60 then
        Gauge1.Progress = 0;
end;

6º - Caso o Gauge1.Progress não possa ser zerado, dependendo da lógica do seu programa, então crie uma variável no Form do tipo Integer para fazer este processo. Ficando algo como:
private
    contador: Integer;
...
...
procedure TForm1.Timer1Timer(Sender: TObject);
begin
    Gauge1.Progress := Gauge1.Progress + 1;
    Inc(contador);

    if contador = 10 then
        Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\2.jpg')
    else if contador = 30 then
        Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\3.jpg')
    else if contador = 50 then
        Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\1.jpg')
    else if contador = 60 then
        contador = 0;
end;

Answer: Cara, basicamente pode usar o TTimmer, coloque no evento dele: onTimer,e defina o Interval para o tempo que achar necessaríssimo.
Comment: não preciso usar uma tgauge para controlar?, se puder ser um pouco mais especifico
Comment: Não o Timmer ja tem um loop, o onTimer
Comment: pode editar sua pergunta e colocar um exemplo de como ficaria?
Answer: procedure TForm1.Timer1Timer(Sender: TObject);
begin
    if Timer1.enabled = true then
    begin
        Gauge1.Progress := Gauge1.Progress +1;
        if Gauge1.Progress=10 then
            Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\2.jpg');

        if Gauge1.Progress=30 then
            Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\3.jpg');

        if Gauge1.Progress=50 then
            Image1.Picture.LoadFromFile('C:\contas_a_pagar\img\home\1.jpg');
    end;
end;

na propriedade Interval você define o tempo do loop em milessegundos.
Timer1.interval := 1000; //1 segundo
Comment: Você simplesmente copiou meu código e não me auxiliou em nada.
Comment: Se olhar bem na primeira linha eu coloquei no evento onTimer, e na ultima linha expiquei como funciona o componente Timer.


Preciso que uma imagem SVG fique fixa a um canto de uma Div com Tamanho variado

Question: queria saber como posso fazer uma imagem (svg) ficar "presa" a um canto de uma div...
ex:

Eu tenho a DIV (roxa) e o SVG (vermelho)
sendo que a DIV tem uma largura padrão e ela n cresce mais do que isso,
já na altura ela pode variar, e daí quando ela cresce o SVG fica mais ou menos assim onde ele estava antes:

E o que eu queria era que o SVG ficasse assim:

O SVG preso no canto inferior esquerdo da DIV...
Desculpa se eu n expliquei direito, eu sou novo nessa "área" de Css, html etc.
Answer: Acho que position relative na div roxa e position absolute na div vermelha, ajeitando com top e left você ajeita a posição dela. Eis o código:
<code>div.pai {
position: relative;
}
svg {
position: absolute; //isso vai deixar o svg com posição absoluta relativa ao
próximo elemento pai com position definida que não seja static
top: distância do topo aqui;
left: distância da esquerda aqui; //Valores negativos pra sair da box vermelha
;
</code>
Answer: Uma solução seria colocar um position absolute no svg e ajustar com bottom e left.
Algo tipo assim: https://codepen.io/peedroo/pen/QWvJjop
Comment: Deu certo, eu estava usando TOP no lugar do Bottom por isso que quando a DIV era maior o SVG ainda ficava "preso" na parte de cima da DIV... Muito Obrigado!


how to define SpreadsheetApp.getActiveSheet()

Question: I want to have my app script generate output to a SPECIFIC sheet, not the first sheet in the document.
i am looking to do the following:

Have 2 app scripts run on timers for a single google sheet document
App Script 1 will put data into sheet1, named "order_1"
App script 2 will put data into sheet2, named "orders_2"

my code currently puts the output into the active sheet, which is always the first sheet in the document
function import_Completed_orders_FromGmail() {
var threads = GmailApp.search('subject: "orders"');
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];

// Is the attachment a CSV file
  attachment.setContentTypeFromExtension();
  if (attachment.getContentType() === "text/csv") {

    var sheet = SpreadsheetApp.getActiveSheet();
    var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");

    // Remember to clear the content of the sheet before importing new data
    sheet.clearContents().clearFormats();
    sheet.getRange(1, 1, csvData.length,
csvData[0].length).setValues(csvData);
}
}

is there a way to define "ActiveSheet" by name? or to specify a specific sheet to put this output?
Answer: Use getSheetByName(name) method from Class Spreadsheet.
In order to get a Spreadsheet object you will have to use one of the SpreadsheetApp methods to open a spreadsheet like openById(id), open(file), openByUrl(url), getActiveSpreadheet().
Comment: amazing! just tried it and worked perfectly. thank you
Answer: You can get both sheet separately and use them in the code.
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet1 = ss.getSheetByName("order_1");
 var sheet2 = ss.getSheetByName("order_2");

Comment: thank you for the reply. i don't believe that will work. my code outputs the contents of an email attachment, attachment A, to sheet 'order_1', and what i want, is a secondary app-script to output the contents of a separate attachment, attachment B, to sheet 'order_2'. Currently I use 2 separate documents then use the "importrange" function to pull the data to one "master" document....but this method will become more and more complex as i add additional sheets.


How should I modify a contrib module?

Question: I have to modify a contrib module with a custom function. In my case I can't use hooks to extend it.
Is there a best practice, for example renaming the module and placing in sites/default/modules?
Comment: It depends on the magnitude of change and size of contrib module that you want to customize.
Answer: If your addition is general and not specific to your site, you could create an issue and post a patch there.
And even if you have a site specific extension, maybe it can be solved in a way that just requires an additional hook to the contrib module itself which could be useful for other use cases as well. Then you could again create an issue for that.
Comment: Yes! This is a mindset. You can always custom code something for your specific use case, but solving it in a way that is useful for others is what open source is about!
Answer: What I've found useful is to add a contrib and a custom folder, or maybe a contrib-custom folder inside modules folder, there you can move the modules that you've created or contrib modified.
Additionally you need to keep track of the patch that you applied somewhere, maybe a patches folder with the .patch and a readme of the changes.
Comment: It can also be helpful to modify the contrib module's .info file to include the patch number in the version string, like `version = "[version]+[issue]-[patch]"`. E.g. `version = "7.x-3.6+2606586-9"`, though this may cause it to show as having updates available, even if you're using the newest version plus a patch.
Answer: Depending on your situation, you can try creating a patch for it so that the module can still be updated and you can re-apply the patch file after updates to the module to keep your customizations.

How should I modify a contrib module?


How to tell whether a PDF is tagged

Question: Is it possible to determine programatically whether a PDF is "tagged" (for accessibility)? I'm using PHP, and would like (if possible) to simply read a PDF file and return true if tagged, false if not.
I've looked at FPDF and TCPDF, but it isn't clear to me whether either can extract this information.
Answer: In the official ISO PDF-1.7 specification (in the copy available for free from the Adobe website), I read on page 574:

"A Tagged PDF document shall also contain a mark information dictionary (see Table 321) with a value of true for the Marked entry."

To me that means...

...you'll have to parse the PDF structure and
...look for the document catalogue
...where there should be a MarkInfo entry
...specifying a mark information dictionary
...which should contain a key named Marked with a boolean value of true for tagged PDF.
Comment: @TerrillThompson: The document catalog can be compressed.
Comment: That seems to always appear as "<>", findable by searching the PDF as a string. Thanks !
Comment: @Terrill Thomson: Yes, it may work for 95% or more of all tagged PDFs. But don't rely on just grepping for that string if you need high reliability. (Also, one could easily create such a PDF which declares itself as tagged this way, but in practice doesn't 'keep the promise' and does fail all compliance checks...
Answer: Perhaps you can go further with this (check all PDF_get_xx functions).
You will also need this as reference.
Based on this:
<code>Characteristics of a properly tagged PDF:

    - The PDF file includes a logical reading order for its content
    - Images are given correct alternate descriptions
    - Tables are correctly tagged to represent the table structure
    - Form-fields are authored to promote their utility to screen-readers
    - Represents text as Unicode to clear up composition irregularities such as soft
      and hard hyphens
</code>
you might get further.

How to tell whether a PDF is tagged


Understanding this example of projective geometry in Algebraic matroids

Question: In this paper by Evans and Hrushovski: https://londmathsoc.onlinelibrary.wiley.com/doi/abs/10.1112/plms/s3-62.1.1
 they characterize projective planes in algebraically closed fields. These are coordinated by the skew-fields of quotients of the endomorphism rings of connected one-dimensional algebraic groups.
I'm trying to understand their "Example 2" (which is actually the general construction according to Theorem 3.3.1), in which (the representation of) all the ground set elements are of the form $\alpha_1x_1*\alpha_2x_2*\alpha_3x_3$, where $x_1,x_2,x_3$ are independent generic elements of a connected one-dimensional algebraic group $(G, *)$ and $\alpha_1,\alpha_2,\alpha_3\in {\rm End}(G)$ not all $0$.
I tried understanding it by looking at examples that I know, but I haven't managed. For example (this is their Example 1), if $x_1,x_2,x_3$ are algebraically independent over the algebraically closed field $\mathbb{K}$, we can look at all the elements $x_1^{m_1}\cdot x_2^{m_2}\cdot x_3^{m_3}$ with $m_1,m_2,m_3\in \mathbb{Z}$ not all $0$. This example (extended to general rank) shows that matroids linear over $\mathbb{Q}$ are algebraic in all characteristics (?).
Second example, we look at all the elements $\alpha_1 x_1+\alpha_2 x_2+\alpha_3 x_3$ with $\alpha_1,\alpha_2,\alpha_3\in \mathbb{K}$ not all $0$. This example (extended to general rank) is usually used to show that every linear matroid is algebraic over the same field.
If I understand correctly, then in the first case $G=\mathbb{G}_m(\overline{\mathbb{K}(x_1,x_2,x_3)})$ with ${\rm End}(G)=\{x\mapsto x^m\ |\ m\in \mathbb{Z}\}$, while in the second case $G=\mathbb{G}_a(\overline{\mathbb{K}(x_1,x_2,x_3)})$ and the endomorphisms in the example are $x\mapsto \alpha x$. If ${\rm char}(\mathbb{K})=0$ these are all (?), but otherwise in the second case there are more because $x\mapsto x^p$ is also an endomorphism (?).
I guess my first question is if I understood correctly so far.
My main question is regarding the general construction, because there is another case they describe in the paper (other than $G=\mathbb{G}_m$ and $G=\mathbb{G}_a$), where $G$ is an elliptic curve. I don't understand how the elements look in this case, i.e., how the multiplication and isogenies work here to generate a general element. I'm not even sure what a generic element of $G$ means here - is it a uniformizer for the curve?
I'd really appreciate it if someone could give me some concrete example with a concrete elliptic curve (preferably a simple non-trivial one).
Answer: If a matroid is linear over the endomorphism ring of a connected one-dimensional algebraic group, then it is algebraic. This leaves the 3 options described in section 3.1 and mentioned by you. So I guess your question is how to go from a linear representation over the endomorphism ring to an algebraic representation in general. It is answered in the introduction of this paper.
Sections 6.3 and 8.3 of this PhD thesis might also interest you, and contain a few examples.
Comment: Thanks Guus, I will have a look at your paper and PhD. However, I was sort of hoping for an explicit example with elliptic curves, which (apparently since it is more complex) I could not find anywhere.
Answer: An example of an algebraic representation over $\mathbb{F}_2$ of the matroid $M(K_4)$ is the following, where a triple is on a line if and only if it is algebraically dependent:

Here the group multiplication is defined by $$x * y = \frac{x+y}{1+xy}.$$
This group is neither $\mathbb{G}_a$ nor $\mathbb{G}_m$, so it is the group of an elliptic curve, although I am not sure which one.
Comment: But the order of every element in this group is $2$ ($x*x*x=x$), so why isn't the group isomorphic to $\mathbb{G}_a(\mathbb{F})$?
Comment: The same can be said of any elliptic curve in characteristic 2: elliptic curves are additive groups, but not necessarily the additive group of $\mathbb{F}$.
Comment: I think you misunderstood what I meant: this group is not only abelian, it is also isomorphic to an additive group of a field of characteristic $2$ (because it is an elementary abelian 2-group, i.e., the order of every element is $2$). I don't think there are (m)any  elliptic curves in which $x*x*x=x$ (i.e., $x*x=0$) for all $x\in G$ - geometrically this doesn't seem to make sense.
Comment: Actually, for _every_ elliptic curve $G$ defined over a field of characteristic 2, each $x \in G$ satisfies $x * x = 0$. Indeed, elliptic curves in characteristic 2 are a special breed.
Comment: Do you have a reference/proof for this statement? It seems to quite contradict what I've understood about elliptic curve groups.
Comment: For instance the section about characteristic 2 at http://www-math.ucdenver.edu/~wcherowi/courses/m5410/ctcellip.html
Comment: I think you misunderstood what is written there - it is written that the form (2) doesn't work in characteristic $2$, as in this case indeed it would be that $2P=O$ for all the points. But, the form (2) ***is not*** the correct form for elliptic curves in characteristic $2$, because in characteristic $2$ it is singular.  Quoting from your reference: "... observe that the formula (2) does not work well in characteristic $2$ ...if $P$ has coordinates $(x,y)$, our **previous** computation would have $-P = (x,-y)$ ...  in characteristic $2$ we have $-P = (x,1+y)$".
Comment: You are right, I did misunderstand. Thank you. I will have to think about this/another example a bit more.
Comment: Thank you for your help so far, I think I already understand a bit better. But I'm now convinced that the group in this example is isomorphic to $\mathbb{G}_a$ and not an elliptic curve group, so I still don't know how such a construction would look.
Comment: Would a similar algebraic representation with the group action $x*y = \frac{x+y+xy}{1+xy}$ be a better candidate? It is commutative, associative, and $x*x*x = x^4$.
Comment: You mean $x*x*x*x=x^4$. It might be correct - I tried to think about this example a bit, but I'm still confused. Maybe you could give some reasoning why it should be an elliptic curve group, and not isomorphic to $\mathbb{G}_m$? Could you also just define $x*y=x+y+xy$ or would this not work?


Equilibrium Points of ODE

Question: I am given the following two equations as models for male and female population
$\dfrac {df} {dt}$ = $\dfrac {mf} {m+f}$$B_f-fD_f$
$\dfrac {dm} {dt}$ = $\dfrac {mf} {m+f}$$B_m-mD_m$
assume $D_m$=$D_f$=$D$
The equilibrium points two the previous two equations form a line in the $f-m$ plane and I am trying to find the equilibrium ratio of $m/f$
I have tried moving everything to one side for both of them and then integrating and solving for $m$ and $f$ respectively but it seems to just get more complicated
Answer: (For simplicity I will assume that $B_m\neq 0 \neq B_f$).

An equilibrium point must satisfy $\dfrac {df} {dt}=0$ and $\dfrac {dm} {dt}=0$, i.e.,
$\dfrac {mf} {m+f}$$B_f$ = $fD$
$\dfrac {mf} {m+f}$$B_m$ = $mD$
Notice that this is trivially satisfied by $m=f=0$ meaning the origin is always an equilibrium point. Moreover, if $D=0$ then it is necessary that either $m=0$ or $f=0$. In other words, the $m$ and $f$ axes are the set of equilibrium points.
Now the only case left to worry about is when $D\neq 0$. Since we already know that the origin is an equilibrium point, let us ignore it for now and we'll be able to divide the second equation by the first and yield,
$\dfrac{m}{f}=\dfrac{B_m}{B_f}$
which is the only other family of equilibrium points.
So in summary,

If $D=0$, then the axes are the equilibrium points.
If $D\neq 0$, then the line $f=\dfrac{B_f}{B_m}m$ are the equilibrium points.
Answer: Equilibrium occurs when $\dfrac{\mathrm{d}f}{\mathrm{d}t}=\dfrac{\mathrm{d}m}{\mathrm{d}t}=0$.
$\dfrac{f}{B_f}=\dfrac{m}{B_m}=\dfrac{mf}{D(m+f)}\\
\dfrac{m}{f}=\dfrac{B_m}{B_f}$

Equilibrium Points of ODE


How do I get access to INodeServices without dependency injection

Question: I'd like to run some node code from my c#.  Microsoft.AspNetCore.NodeServices seems to be the way to do this job however the examples are all very similar and all involve putting
services.AddNodeServices();

in the configure services function and then DI adds the implementation of INodeServices to a controller. Like this
public class foo
{
    private readonly INodeServices _nodeServices;

    public foo(INodeServices nodeServices)
    {
        _nodeServices = nodeServices;
    }
}

As I'm using this in a class library rather than a webapi how is DI going to work?  Also how do I call the class from a unit test, what can I pass into the constructor? I'm sure I'm missing something obvious.
Comment: The DI container built into ASP.NET Core is not part of ASP.NET Core. You can use it by referencing the NuGet package Microsoft.Extensions.DependencyInjection
Comment: You can build up the object graph yourself and build a service provider. Reference the library suggested in the previous comment and check this site for examples of how to use it in an application outside of asp.net-core.
Comment: Very useful article here [Essential .NET - Dependency Injection with .NET Core](https://msdn.microsoft.com/en-us/magazine/mt707534.aspx)
Answer: The concept of DI is that it can be used to resolve object graphs. That is, it doesn't just resolve dependencies of the Controller class, but dependencies of those dependencies, dependencies of those dependencies, etc.
To use INodeServices in your own library, you simply need to reference Microsoft.AspNetCore.NodeServices, then accept it as a constructor parameter.
public class MyServiceFromMyLibrary : IMyServiceFromMyLibrary
{
    private readonly INodeServices nodeServices;

    public MyServiceFromMyLibrary(INodeServices nodeServices)
    {
        this.nodeServices = nodeServices;
    }

    // ...
}

Then reference your library from the Web API project and inject your service into a controller.
public class FooController
{
    private readonly IMyServiceFromMyLibrary myService;

    public FooController(IMyServiceFromMyLibrary myService)
    {
        this.myService = myService;
    }
}

DI takes care of putting the INodeServices instance into your class provided it is registered in your composition root, as follows.
services.AddNodeServices();
services.AddTransient<IMyServiceFromMyLibrary, MyServiceFromMyLibrary>();

If your end game is to create a reusable library rather than an application layer refer to DI Friendly Library for some techniques to make your library easier to use without the use of dependency injection.

Also how do I call the class from a unit test, what can I pass into the constructor?

For a unit test, you would just need to mock INodeServices. The simplest way is to use a mocking library, such as Moq.
var mock = new Mock<INodeServices>();
mock.Setup(ns => ns.InvokeAsync(It.IsAny<string>())).Returns(...);

var target = new MyServiceFromMyLibrary(mock.Object);
// .. Call a method on target and then assert the results

References:

Using Node Services in ASP.NET Core
Dependency injection in ASP.NET Core
Comment: Hi, thanks for the answer but It's not really helped me, the techniques for hiding DI revolve around newing up the INodeServices do you know what the constructor is?
Comment: also I suppose I meant integration test rather than strictly unit test as I want to test what the NodeServices does rather than mock it out.
Comment: Since .NET Core is open source, this is pretty easy to determine - it looks like you should be able to use [NodeServicesFactory](https://github.com/aspnet/JavaScriptServices/blob/fb19ee8923b5ef7ebb125bc6e5a1a182cfadfe88/src/Microsoft.AspNetCore.NodeServices/Configuration/NodeServicesFactory.cs). However, its dependency `NodeServicesOptions` depends on `IServiceFactory` (making it a service locator), and it looks like there are several other things that depends on.
Comment: Bottom line is that unit testing is straightforward, but integration testing not so much. See [Integration testing in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing).


If $0\neq \alpha \in E$ is algebraic over F, then $\frac{1}{a}$ is also algebraic over F.

Question: Exercise: Show that if $0\neq \alpha \in E$ is algebraic over F, then $\frac{1}{a}$ is also algebraic over F.
My first idea is to somehow use the fact that the field extension $F(\alpha)$ is isomorphic to the field $F[x]/<p(x)>$ where $p(x)$ is the minimal polynomial of $\alpha$ over $F$. However, I continuously run into $\frac{1}{0}$ which is problematic for obvious reasons. Any hints to start this proof would be very helpful.
Answer: Let $P(x)$ be a polynomial with non-zero constant term and coefficients in $F$ such that $P(\alpha)=0$.
Suppose that $P$ has shape $b_nx^n+b_{n-1}x^{n-1}+\cdots+b_0$. Then $\dfrac{1}{\alpha}$ is a root of the polynomial $b_0x^n+b_1x^{n-1}+\cdots+b_n$.  To show this, divide $P(x)$ by $x^n$.
Answer: Hint: $\frac{1}{\alpha}\in F(\alpha)$
Answer: Start with your algebraic number $a$. There is $b\in F$  so that $ab=1$. Then for any $k$, we have $a^kb^k=1$. Using the fact that $a$ is algebraic, there is some polynomial with coefficients $c_i$ that $a$ satisfies. Explicitly, we have
$$\sum_{k=1}^n c_ia^k=0.$$
Substituting in for $b$, we have
$$\sum_{k=1}^n c_i(1/b)^k=0.$$
Can you now show that $b$ is algebraic?


Android - Qual a diferença entre String e Editable?

Question: Ao fazer uso da view EditText, vi que ela retorna um tipo de dado Editable e não uma String. E possui métodos diferentes como getEditableText().
Qual a principal diferença entre String e esse outro tipo de dado Editable?
Não poderia uma EditText retornar uma simples String?
Explicações Completas são muito apreciadas
Comment: Segundo a documentaçao, a diferença é a mutabilidade, ou seja, a capacidade de alterar o dado. Strings são imutaveis, quando você concatena, é criada uma nova string com o valor antigo e o novo junto, pelo que entendi, esse Editable nao precisa disso.
Comment: Eu realmente não tinha reparado nisso, assim como comentei na resposta do ramaral. Ao editar uma String, é preciso cria uma outra nova. Isso realmente faz sentido. Obrigado Articuno!
Answer: São duas as principais diferenças

Mutabilidade
Sempre que aplica uma qualquer operação a uma String é criada uma nova, o mesmo não acontece no Editable onde a operação é aplicada na instância actual.
Possibilidade de adicionar markup objects(objetos de marcação/estilo).
A um Editable podem ser adicionados markup objects para alterar a aparência/estilo do texto, como sublinhado(UnderlineSpan), riscado(StrikethroughSpan) e bold(StyleSpan), entre outros.
Comment: Faz sentindo. Realmente ao manipular uma String definida é necessário criar uma outra String. Me pergunto se nesse caso, não seria mais conveniente retornar um StringBuilder não? Do que um outro tipo como Editable, embora pela sua explicação, ele seja útil para adicionar estilo ao texto.
De qualquer forma, muito obrigado pela resposta! Foi de grande ajuda.


Cannot upgrade awscli: no module named _internal and other errors

Question: When I try to upgrade awsli: pip install awscli --upgrade, I get the following error:
Traceback (most recent call last):
  File "/usr/local/bin/pip", line 7, in <module>
    from pip._internal import main
ImportError: No module named _internal

Following the instructions on Stackoverflow: pip: no module named _internal

Then I get the following errors:
python2.7 get-pip.py --user --force-reinstall
Collecting pip
  Using cached https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl
botocore 1.9.22 requires docutils>=0.10, which is not installed.
awscli 1.14.69 requires colorama<=0.3.7,>=0.2.5, which is not installed.
awscli 1.14.69 requires docutils>=0.10, which is not installed.
awscli 1.14.69 requires rsa<=3.5.0,>=3.1.2, which is not installed.
awscli 1.14.69 requires s3transfer<0.2.0,>=0.1.12, which is not installed.
Installing collected packages: pip
Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: '/home/porter/.local/lib/python2.7'
Check the permissions.

You are using pip version 8.1.1, however version 10.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

So, all in all it is a great mess. I don't think that upgrading to pip version 10.0.1 will do any good.
Edit:
I found the culprit: /home/porter/.local/lib/python3.5. In this folder, there are the site-packages that pip is asking about: colorama, docutils, rsa, s3 etc.
What to do now? awscli is installed at: /usr/local/lib/python2.7/dist-packages/awscli
but its dependencies are installed at: /home/porter/.local/lib/python2.7/
so upgrading awscli, even after changing the permissions, doesn't work.
Maybe it is better to deinstall awscli alltogether? But how?
Comment: Try uninstalling it and re-installing it
Answer: It appears that you have files in your home directory that aren't owned by you.  This is the common result of using the sudo command improperly at some point in the past.  Find these files with:
find $HOME -not -user $USER -exec ls -lad {} \;

and change ownership back to you with the chown command.
Answer: I got it done. It needs a few steps though.
1. I deleted the site-packages in  /home/porter/.local/lib/python2.7/
2. I then removed awscli with this command:
sudo python -m pip uninstall awscli
I had to use the python -m command. Otherwise I got the above-mentioned error:
  File "/usr/local/bin/pip", line 7, in <module>
    from pip._internal import main
ImportError: No module named _internal


The recast fun to spread the rows is omitting key columns in R?

Question: I am trying to spread my data such that months are the columns associated with both site and spx. I tried to use recast but I lose the informaton about species. What do I do to get the expected output (attached)?
set.seed(111)
month <- rep(c("J","F","M"), each = 6)
site <- rep(c(1,2,3,4,5,6), times = 3)
spA <- rnorm(18,0,2)
spB <- rnorm(18,0,2)
spC <- rnorm(18,0,2)
spD <- rnorm(18,0,2)

df <- data.frame(month, site, spA, spB, spC, spD)

df.test <- reshape2::recast(df, site ~  month)
Here is what I am getting.

  site F J M
1    1 5 5 5
2    2 5 5 5
3    3 5 5 5
4    4 5 5 5
5    5 5 5 5
6    6 5 5 5

#Expected output (It's dummy data)

site sp  J  F  M
1    A   5  6   7
1    B   2  3   4
..
6    D   1  2   3

Comment: It'a dummy data. Hmm...something is off. All the rows and columns are 1 when I run this code. Why fun.aggregate?
Answer: If the intention is not to aggregate, but just transpose, then we can use pivot_longer to reshape to long and then reshape back to wide with pivot_wider
library(dplyr)
library(tidyr)
df %>%
  pivot_longer(cols = starts_with('sp'), names_prefix = 'sp',
    names_to = 'sp') %>%
  pivot_wider(names_from = month, values_from = value)

-output
# A tibble: 24 × 5
    site sp         J      F      M
   <dbl> <chr>  <dbl>  <dbl>  <dbl>
 1     1 A      0.470 -2.99   3.69
 2     1 B     -2.39   0.653 -6.23
 3     1 C     -0.232 -2.72   4.97
 4     1 D      0.350 -0.433  0.405
 5     2 A     -0.661 -2.02   0.788
 6     2 B      0.728  1.20  -1.88
 7     2 C      0.669  0.962  3.92
 8     2 D     -1.69   2.89  -1.61
 9     3 A     -0.623 -1.90   1.60
10     3 B      0.723 -3.68   2.80
# … with 14 more rows

Or using recast - specify the id.var and then include the variable also in the formula
library(reshape2)
 reshape2::recast(df, site + variable  ~  month, id.var = c("month", "site"))
   site variable           F          J          M
1     1      spA -2.99485331  0.4704414  3.6912725
2     1      spB  0.65309848 -2.3872179 -6.2264346
3     1      spC -2.72380897 -0.2323101  4.9713231
4     1      spD -0.43285732  0.3501913  0.4046144
5     2      spA -2.02037684 -0.6614717  0.7881082
6     2      spB  1.19650840  0.7283735 -1.8827148
7     2      spC  0.96224916  0.6685120  3.9199634
8     2      spD  2.89295633 -1.6945355 -1.6123984
9     3      spA -1.89695121 -0.6232476  1.5950570
10    3      spB -3.68306860  0.7233249  2.8005176
11    3      spC  1.48394325 -1.2417162  0.3833268
12    3      spD  0.81941960  1.9564633  0.5892684
13    4      spA -0.98792443 -4.6046913 -3.1333307
14    4      spB  5.43611120  0.6939287 -3.2409401
15    4      spC  0.05564925 -2.6196898  3.1050885
16    4      spD  1.82183314  3.6117365  2.8097662
...


Doctrine DBAL versão dev

Question: Veja so a versão dev é paga :?
Falo porque está me retonando um erro:

"C:\bin\composer.bat" "--ansi" "--no-interaction" "validate"
  ./composer.json is invalid, the following errors/warnings were found:
  description : NULL value found, but a string is required
  No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.
  Concluído.

Na validação.
Meu composer.json está assim:
<code>"require": {
    "doctrine/dbal": "2.5.*@dev",
    "doctrine/orm": "2.5.*@dev",
    "doctrine/common": "2.5.*@dev"
}
</code>
Answer: O Rafael está correto, para complementar vou deixar um exemplo de um composer.json com a dependência do Doctrine Dbal
<code>  {
        "name": "empresa/projeto",
        "description": "Descrição do seu projeto",
        "require": {
            "doctrine/dbal": "2.5.*@dev"
        },
        "license": "licença",
        "authors": [
            {
                "name": "Nome do autor",
                "email": "firstname.lastname@example.com"
            }
        ]
    }
</code>
Answer: Pela mensagem de erro, faltou preencher o campo description que é um pequeno texto sobre o seu software. É obrigatório caso o pacote seja redistribuído. E além desse erro há um aviso sobre a licença do software. Se for proprietário é para utilizar a opção "proprietary".
Comment: blz. @Rafael Mena Barreto

Doctrine DBAL versão dev


How to install memcache on Ubuntu Hardy?

Question: How do I install and configure memcache on ubuntu hardy?
Answer: memcached is the package you want:
Description: A high-performance memory object caching system
 Danga Interactive developed memcached to enhance the speed of LiveJournal.com,
 a site which was already doing 20 million+ dynamic page views per day for 1
 million users with a bunch of webservers and a bunch of database servers.
 memcached dropped the database load to almost nothing, yielding faster page
 load times for users, better resource utilization, and faster access to the
 databases on a memcache miss.
 .
 memcached optimizes specific high-load serving applications that are designed
 to take advantage of its versatile no-locking memory access system. Clients
 are available in several different programming languages, to suit the needs
 of the specific application. Traditionally this has been used in mod_perl
 apps to avoid storing large chunks of data in Apache memory, and to share
 this burden across several machines.

Installation
Just make sure universe is enabled and run apt-get install memcached.
Configuration
In /usr/share/doc/ are several documents you should read on memcached as deployed by Debian packaging. In particular, README.Debian:

Memcached has two logical uses in this package, a system daemon that can be run
  from the standard /etc/init.d/ interface, or one that can be run from userland
  from a the command line such as
    /usr/bin/memcached -d
The former has been setup to run through the start-memcached script, reading in
  the configuration from /etc/memcached.conf.  The start-memcached script ignores
  certain parameters as discussed in the configuration file itself.
The latter is the binary as provided by Danga, and reads in options from the
  command line, ignoring the Debian-specific configuration file entirely.
  --Jay Bonci
  email@example.com

Reading the postinst script, it should run by default: update-rc.d memcached defaults >/dev/null
Comment: Thanks for the description but I asked how to install and configure on a Hardy box.
Comment: It's in hardy? apt-get install memcached.
Comment: This no longer works as of 2012.
Comment: Care to elaborate? It's in precise...


Permutations of Hamel bases of $\mathbb{R}$ over $\mathbb{Q}$

Question: Consider $\mathbb{R}$ with the usual addition and multiplication operations as a vector space over $\mathbb{Q}$. Do there exist a Hamel basis $\{ v_i \}_{i \in I}$ of $\mathbb{R}$ and a permutation $\phi:I \rightarrow I$ different from the identity map, such that $v_{\phi(i)}=cv_i$ for some constant $c \in \mathbb{R}$ and all $ i \in I$?
Thank you very much in advance for your help.
Comment: I don't see how to use your suggestion, prof. Ullrich. The fact that the vectors $\{ v_i \}$ are linearly independent implies that the eventual constant $c$ can't be rational. We can say more. Since $c^n \neq 1$ for every positive integer $n$, for every $v_i$ in our basis, the elements $v_i, cv_i, c^2 v_i, ..., c^n v_i$ are distinct elements of our basis, and so linearly independent over Q. This implies that $c$ cannot be an algebraic number. I cannot prove more than that. Do you have some other thing in mind?
Comment: Equivalently, you are asking whether there exists a transcendental number $c\in\mathbb{R}$ such that $\mathbb{R}$ is free as a module over $\mathbb{Q}[c,c^{-1}]$.
Comment: Hint: The vectors in a basis are linearly independent.
Comment: I suppose you want $c\neq 1$ (and independent of $i$), otherwise I've got an easy example.
Answer: Suppose you have such a basis $\{v_i\}$, permutation $\phi$, and $c\in\mathbb{R}$.  It is clear that every orbit of $\phi$ must be infinite, so $c$ is transcendental (since otherwise $c$ would have to be $-1$, but then $v_i$ is not linearly independent from $v_{\phi(i)}$).  Choose a set of representatives $B\subset\{v_i\}$ for the orbits of $\phi$.  Then the set $B$ is a basis for $\mathbb{R}$ as a module over the ring $\mathbb{Q}[c,c^{-1}]$.
However, I claim that $\mathbb{R}$ cannot be free over $\mathbb{Q}[c,c^{-1}]$.  For instance, every element of $\mathbb{R}$ is infinitely divisible by $c+1$.  But since $c$ is transcendental, no nonzero element of the ring $\mathbb{Q}[c,c^{-1}]$ is infinitely divisible by $c+1$, and hence no nonzero element of any free module can be infinitely divisible by $c+1$.  Thus no such basis exists.
More generally, this argument applies with $\mathbb{Q}\subset\mathbb{R}$ replaced by any field extension $K\subset L$ (if $L$ contains roots of unity not in $K$, you need to use the fact that the powers of a root of unity cannot be linearly independent over $K$ since their sum is $0$).
Comment: so you can just look at the decomposition of $v_1/(c+1)$ and multiply everyone by $c+1$ to get a contradiction.


Mathematical Induction in Money Multiplier

Question: An ATM (Automated Teller Machine) only provides Rp 20.000 and Rp 50.000. What kind of money multiplier which can be issued by the ATM?
Prove your answer by induction.
Note: Rp stands for Rupiah (the currency in Indonesia).
I have some trouble to clear this problem. Please help me. Regards. Notes that it doesn't mean that I don't provide you my attempt. Honestly, I have no idea where to start, the basis and induction steps can be done next.
Comment: First of all, try to guess the answer without worrying about the proof. Can you make 10000, 20000, 30000, 40000, 50000, 60000, 70000, ...? That's the very least you could do yourself.
Answer: It is clear that any amount which is not a multiple of Rp 10.000 cannot be provided, that the amount Rp 20.000 can be provided and that the amounts Rp 10.000 and 30.000 cannot be provided (in spite of the fact that 10.000 and 30.000 are multiples of 10.000).
Now, prove by indection that any multiple of Rp 10.000 starting from Rp 40.000 can be provided by the ATM.


Get id value using  with javascript and php

Question: First example:
var dbSelected = "File selected: ";
var filenamePanel = document.getElementById('filenamePanel');
filenamePanel.textContent = dbSelected + files[0].name;

var postLink = files[0].link;
document.getElementById('postLink').value = postLink;

var postName = files[0].name;
document.getElementById('postName').value = postName;

If I use <input type="hidden" name="postName" id="postName"> to send the value to another page via POST with PHP, it works.
Second example:
function onSuccessCallback(Blob){
    document.getElementById('postName').textContent = Blob.filename;
    document.getElementById('postLink').textContent = Blob.url;
    document.getElementById('results').textContent = JSON.stringify(Blob);
};

Now, If I use <input type="hidden" name="postName" id="postName"> on the second example to send the 'postName' id value to another page, the value is empty.
What changes are necessary, on the second example, so that I can send the 'postName' id value to another page using a hidden <input> field?
Answer: Use .value instead of .textContent to store the data in the hidden input field:
document.getElementById('postName').value= Blob.filename;

Comment: please accept the answer when your problem is solved.


Pulling #hashtags and displaying them on site

Question: I see that you can you the Activity Stream module to pull feeds from twitter and other social media sites. Well how could I pull a predefined #hashtag from ANY social meida site and present it in a feed on my drupal site.
Example:
Hashtag is #NCAABasketball
From bjones on Twitter:
Saw KU beat UNC's butt. Love #NCAABasketball
From jbean on Google+:
Love #NCAABasketball !
From ktghram on Instagram:
I'm at the game! "picture:" #NCAABasketball
It doesn't have to be like this, but would this be possible with out the user posting or tweeting to my account?
Any suggestions?
Answer: This is possible using the dev branches of a few modules put together:
feeds, >= 7.x-2.0-alpha8+56-dev
feeds_oauth, >= 7.x-1.0-beta3+2-dev
feeds_jsonpath_parser, >= 7.x-1.0-beta2+12-dev
I think there are a few other necessary modules you'll need to have installed, like oauth, ctools, feeds_ui.
One of the most important things is that you need to register an app at dev.twitter.com, and get an API key / secret. You put that into the feeds setup (admin/structure/feeds/FEED_NAME/settings/OAuthHTTPFetcher). When you setup your feed, you will want to choose the HTTP OAuth fetcher (oauth2 does not work) as the Fetcher type.
You create a new feed importer.
Additionally, you'll want to create a content type like "tweet" and add the fields you want to parse (like author, date, name, body, location).
Back in the feeds setup, setup your mapping, and create several jsonpath_parser maps to your respective fields. After that, click "settings" under JSONPath parser, to map your json contexts to your fields.
It should be something like this:
Context: $.statuses.*
Title: id_str
body: text
etc, etc, etc
Finally, once this is all setup, you can go to SITEURL.com/import
and input your search string, which will look like this:
https://api.twitter.com/1.1/search/tweets.json?q=%23HASHTAG
Anyway, I hope this is helpful. I realize that my answer could be better organized, but it should give the gist as to how this is done.
For my "tweet" content type, I have the default setup to be NOT published, so that I can moderate what actually shows up on my site.
One more caveat is that non UTF-8 strings (common in foreign languages for example) will error out and break your feed importer (which should run on cron automatically). Ideally you want to sanitize the input before writing it into the database anyway.
Here's the PHP you can put into a quick custom module to sanitize the input of the body field for example. You want to make sure your jsonpath_parser:ID matches the ID you setup in the node-processor settings.
<code><?php

/**
 * Implements hook_feeds_after_parse().
 */
function feeds_custom_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
//dpm($source); // look at source variables, requires devel
//dpm($result); // look at result variables, requires devel

  foreach ($result->items as $delta => $item) {
    $result->items[$delta]['jsonpath_parser:1'] = utf8_encode($item['jsonpath_parser:1']);
  }
}
</code>
Answer: You can use Twitter Pull module...
Project page says

Twitter Pull is a small module, the only purpose of which is to allow
  super-easy embedding of public twitter data like: a user timeline or
  twitter search results by hashtag or a search term. The emphasis is on
  making these very specific tasks as easy and straightforward as
  possible. The purpose of the module is not to be an end-all solution
  for Twitter.
Comment: and for other hashtags? manipulate the code ?
Comment: Wondering if you have used this module? and if you could provide instructions on how to set it up, if so?


SignalType.CANCEL ignores publishOn operator

Question: I wonder why cancel signal is handled in a different way than the others.
Anybody knows whether this is intentional?
Scheduler scheduler = Schedulers.elastic();

Disposable disposable =
   Flux.interval(Duration.ofSeconds(1))
       .publishOn(scheduler)
       .doFinally(signalType -> {
           if (signalType == SignalType.CANCEL) {
               // caller thread  - why ??
           } else {
              // elastic thread
           }
       }).log()
      .subscribe();

For example
Mono.just(1)
    .delayElement(Duration.ofSeconds(3))
    .doFinally(signalType -> {
        disposable.dispose();
     })
    .subscribe();

produces output:
14:37:36.308 [main] INFO reactor.Flux.DoFinallyFuseable.1 - | onSubscribe([Fuseable] FluxDoFinally.DoFinallyFuseableSubscriber)
14:37:36.308 [main] INFO reactor.Flux.DoFinallyFuseable.1 - | request(unbounded)
14:37:37.324 [elastic-2] INFO reactor.Flux.DoFinallyFuseable.1 - | onNext(0)
14:37:38.324 [elastic-2] INFO reactor.Flux.DoFinallyFuseable.1 - | onNext(1)
14:37:39.325 [elastic-2] INFO reactor.Flux.DoFinallyFuseable.1 - | onNext(2)
14:37:39.387 [parallel-2] INFO reactor.Flux.DoFinallyFuseable.1 - | cancel()

And
Thread.sleep(4000);
disposable.dispose();

produces output:
14:39:22.380 [main] INFO reactor.Flux.DoFinallyFuseable.1 - | onSubscribe([Fuseable] FluxDoFinally.DoFinallyFuseableSubscriber)
14:39:22.380 [main] INFO reactor.Flux.DoFinallyFuseable.1 - | request(unbounded)
14:39:23.412 [elastic-2] INFO reactor.Flux.DoFinallyFuseable.1 - | onNext(0)
14:39:24.412 [elastic-2] INFO reactor.Flux.DoFinallyFuseable.1 - | onNext(1)
14:39:25.414 [elastic-2] INFO reactor.Flux.DoFinallyFuseable.1 - | onNext(2)
14:39:26.400 [elastic-2] INFO reactor.Flux.DoFinallyFuseable.1 - | onNext(3)
14:39:26.400 [main] INFO reactor.Flux.DoFinallyFuseable.1 - | cancel()

Answer: The publishOn operator will only be invoked when a signal is emitted from the source and travels downstream.
The cancel request, however, is forwarded upstream and then the handlers are executed. A cancel signal is not emitted by the source.


Does R's glm function use randomness?

Question: Does R's glm function use randomness in any way? Exercise 8(d) in chapter 5 (section 5.4) of An Introduction to Statistical Learning (a free book) seems to indicate that it does because it has the reader change the random seed and fit a new model (with the same data).
Remark: I'm not using (and don't use) R, so I couldn't test it.
Comment: Per the documentation [1], it uses iteratively reweighted least squares (IWLS) to fit the model -- might be a place to start.

  [1]: https://stat.ethz.ch/R-manual/R-devel/library/stats/html/glm.html
Comment: Thanks @dlid. Looks like the only place where there could be any randomness is in the initial "guess" of the approximation algorithm (as in Newton's method). R has a separate IWLS function and its documentation indicates that its implementation is from a research paper, "page 46 of Suveges (2007)".  I checked that out and didn't see any obvious randomness there either. (I might've missed it.)
Comment: Try running it twice with the same inputs and see if the outputs are [identical](https://stat.ethz.ch/R-manual/R-devel/library/base/html/identical.html).
Comment: Thanks @Ben. That's what I meant I cannot do when I said "I couldn't test it."
Answer: There is no randomness in the fitting algorithm or in the initialisation for the built-in link and family.  glm accepts user-defined link/family combinations and these could in principle use randomness.

Does R's glm function use randomness?


Can $b+c$ in the pythagorean triplets $(a, b, c)$ be a prime number?

Question: If $a^2 + b^2 = c^2$, can $b + c$ be a prime number?
Comment: If $a^2+b^2=c^2$ is primitive, then $b+c=(2x-1)^2,x\in\mathbb{N}$
Answer: If the Pythagorean Triple $(a, b, c)$ is not primitive, then $b+c$ is trivially composite.  Thus, let it be primitive.  Then $$a=m^2-n^2$$ $$b=2mn$$ $$c=m^2+n^2$$ where $b$ and $a$ are interchangeable.  Then we are looking at the sum $b+c=2m^2$ or $(m+n)^2$

Looking back at this answer, the only possibility for $b+c$ to be prime is when $m=1, b=1-n^2$, and thus $b+c=2$.
Comment: No problem.  If my answer was helpful, you should check the checkmark under the arrows for my comment.  It gives me more reputation
Comment: Thanks for your help.  Appreciate it a lot.
Comment: @almagest Actually it wasn't correct.  I just corrected it.  Sorry everyone.
Answer: Hint: $a^2+b^2=c^2\implies b^2-c^2=-a^2\implies (b+c)(b-c)=-a^2 \implies b+c=\frac{a^2}{c-b}$ $ \implies b+c=a^2 \times \frac{1}{c-b}$
Comment: A lemma that will solve the problem when coupled with the hint: if $p$ is prime and $p$ divides $a^2$, then $p$, being a divisor of $a$, is less than or equal to $a$.


Groups and Identity Inequality

Question: Let's say  $g,h \in G$ where $G$ is a group. $g$ is not the identity and $g^4h = hg^5$. I seek to prove that $gh \neq hg$.
I have tried to do it by contradiction, but Ive gotten nowhere. Any way I could prove this more directly?
Comment: If $g$ and $h$ commute then $g^4h=g^5h$, so $g=1$.
Comment: You can prove the contrapositive: if $gh = hg$ then $g$ is the identity. If $gh = hg$ then the given relation rearranges to $g^4 h = g^5 h$. Can you finish it from here?
Answer: Contradiction is definitely the way to go here. Assume $gh=hg$; do you see a way to use this to change (say) the right hand side into something more similar to the left hand side?

 Think about $$hg^5=hgg^4=ghg^4=ghgg^3=...$$ This will give you $$hg^5=g^5h.$$

The equation you get by changing the right hand side accordingly, namely

 $g^4h=g^5h$,

can then be hit with one of the group axioms to get a surprising fact:

 Using the fact that inverses exist, multiply both sides by $(g^4h)^{-1}$. What do you get?
Comment: As a logic-y aside, strictly speaking this isn't proof by contradiction but rather proof by *negation* - there is a [subtle difference](https://math.stackexchange.com/questions/3104606/proof-by-contradiction-in-constructive-mathematics). But that's not really relevant here.
Comment: So nicely pedagogical that you could also use any $n$ and induction in the first spoiler.
Answer: By contradiction if $gh=hg$ then $g^4h=hg^4=hg^5$. Hence $g=1$, a contradiction.

Groups and Identity Inequality


How to use MinGW-w64 instead of Microsoft Visual C++ when pip install pytest-playwright

Question: I would like to use Playwright for Python in a non-privileged environment.
After running pip install pytest-playwright in the embedded python environment, I get the following error:
Building wheels for collected packages: greenlet
  Building wheel for greenlet (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> [90 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-312
      creating build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\__init__.py -> build\lib.win-amd64-cpython-312\greenlet
      creating build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\__init__.py -> build\lib.win-amd64-cpython-312\greenlet\platform
      creating build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\leakcheck.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_contextvars.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_cpp.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_extension_interface.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_gc.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_generator.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_generator_nested.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_greenlet.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_greenlet_trash.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_leaks.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_stack_saved.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_throw.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_tracing.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_version.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\test_weakref.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\__init__.py -> build\lib.win-amd64-cpython-312\greenlet\tests
      running egg_info
      writing src\greenlet.egg-info\PKG-INFO
      writing dependency_links to src\greenlet.egg-info\dependency_links.txt
      writing requirements to src\greenlet.egg-info\requires.txt
      writing top-level names to src\greenlet.egg-info\top_level.txt
      reading manifest file 'src\greenlet.egg-info\SOURCES.txt'
      reading manifest template 'MANIFEST.in'
      warning: no previously-included files found matching 'benchmarks\*.json'
      no previously-included directories found matching 'docs\_build'
      warning: no files found matching '*.py' under directory 'appveyor'
      warning: no previously-included files matching '*.pyc' found anywhere in distribution
      warning: no previously-included files matching '*.pyd' found anywhere in distribution
      warning: no previously-included files matching '*.so' found anywhere in distribution
      warning: no previously-included files matching '.coverage' found anywhere in distribution
      adding license file 'LICENSE'
      adding license file 'LICENSE.PSF'
      adding license file 'AUTHORS'
      writing manifest file 'src\greenlet.egg-info\SOURCES.txt'
      copying src\greenlet\greenlet.cpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet.h -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_allocator.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_compiler_compat.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_cpython_compat.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_exceptions.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_greenlet.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_internal.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_refs.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_slp_switch.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_thread_state.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_thread_state_dict_cleanup.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\greenlet_thread_support.hpp -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\slp_platformselect.h -> build\lib.win-amd64-cpython-312\greenlet
      copying src\greenlet\platform\setup_switch_x64_masm.cmd -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_aarch64_gcc.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_alpha_unix.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_amd64_unix.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_arm32_gcc.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_arm32_ios.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_arm64_masm.asm -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_arm64_masm.obj -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_arm64_msvc.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_csky_gcc.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_m68k_gcc.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_mips_unix.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_ppc64_aix.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_ppc64_linux.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_ppc_aix.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_ppc_linux.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_ppc_macosx.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_ppc_unix.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_riscv_unix.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_s390_unix.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_sparc_sun_gcc.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_x32_unix.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_x64_masm.asm -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_x64_masm.obj -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_x64_msvc.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_x86_msvc.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\platform\switch_x86_unix.h -> build\lib.win-amd64-cpython-312\greenlet\platform
      copying src\greenlet\tests\_test_extension.c -> build\lib.win-amd64-cpython-312\greenlet\tests
      copying src\greenlet\tests\_test_extension_cpp.cpp -> build\lib.win-amd64-cpython-312\greenlet\tests
      running build_ext
      building 'greenlet._greenlet' extension
      error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for greenlet
  Running setup.py clean for greenlet
Failed to build greenlet
ERROR: Could not build wheels for greenlet, which is required to install pyproject.toml-based projects

The error message says "Microsoft Visual C++ 14.0 or greater is required.", but I am forbidden to install Microsoft Visual C++.
Is it possible to install pytest-playwright using MinGW-w64 instead of Microsoft Visual C++?
I have tried the following three different methods and could not install pytest-playwright successfully.

Add PYTHONPATH\Lib\distutils\distutils.cfg and run pip install pytest-playwright.

[build]
compiler=mingw32

[build_ext]
compiler=mingw32

Install with a .zip file downloaded from GitHub using option --global-option and --compiler.

> pip install --global-option build_ext --global-option --compiler=mingw32 playwright-pytest-0.4.3.zip

Install with .whl files

> pip install greenlet-3.0.0-cp312-cp312-win_amd64.whl
> pip install pytest_playwright-0.4.3-py3-none-any.whl

My environment is as follows:

OS: Windows 10 Pro 22H2 64-bit
Python: 3.12.0 embeddable package (64-bit)
pip: 23.2.1 (installed using get-pip.py)
MinGW-w64: 13.2.0 built by MinGW-Builds project (x86_64-13.2.0-release-posix-seh-ucrt-rt_v11-rev0.7z)
Comment: I think you need mingw-patched `setuptools`; see https://stackoverflow.com/a/55554854/7976758
Comment: @phd Thank you for your comment. I appreciate your suggestion to use MSYS2. However, I am not allowed to use MSYS2 in my environment.
Answer: I solved the problem by downgrading Python from version 3.12.0 to version 3.11.6.
Thanks to everyone who commented on my question.
I will mark this question as resolved.


Invalid datetime format: 1292 Truncated incorrect DOUBLE value

Question: I am fire this sql query and then return this error.
My Error:

1292 Truncated incorrect DOUBLE value:
  '1,2,3,4,5,6,7,122,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,157,153,154,155,156'
  The SQL being executed was:

My Query:
DELETE FROM groups_module_actions
WHERE module_action_id NOT IN('1,2,3,4,5,6,7,122,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,157,153,154,155,156') AND group_id='1'

Comment: is that a list of number or a string? Which is it meant to be?
Comment: Did you try the suggestion?
Answer: Skip the quotes in the NOT IN (), its expecting datatype integer not a string.
DELETE FROM groups_module_actions WHERE module_action_id
NOT IN(1,2,3,4,5,6,7,122,8,9,10,11,12,13,14,15,16,17,18,19,20,
21,22,23,24,25,26,157,153,154,155,156)
AND group_id=1

Comment: For reasons around implicit conversion, quoted numbers result in the comparison being compared as a double. So don't quote numbers that are no being compared against strings (e.g. phone numbers).