Drupal used as a project management tool

Question: I have been working with drupal for the past 2 years and I'm well aware of its power and extensibility.
I have been thinking for a long time, but has anyone been successful been using drupal as a project management tool.
What modules should be used for making drupal a  project management tool.
Please keep in mind, we are not looking at some very advanced features, just basic set of features, to get you started.
Answer: Open Atrium is ready drupal system for you (it's free of course). At least, you can investigate modules and theme used there (.\profiles\openatrium folder)...
Comment: We're using OpenAtrium alongside with time_tracker module for about six months, and that's workin' well.
Comment: Open Atrium would be you best place to start. Alternatively you can build your own using [Og](http://drupal.org/project/og), [Spaces](http://drupal.org/project/spaces), [Features](http://drupal.org/project/spaces).
Comment: This is one too cool. I wonder why I never came across this.
Answer: Everyone over designs project management systems. They end up not being used, or used marginally with only the minimal features. Plus they waste tons of time simply by being confusing. Although I've not used Open Atrium, I've looked into others and found them lacking. Seriously, terribly lacking.
I've had great success with the following zero-budget solution:
1) Use the Node Comments module to promote comments to full nodes.
2) Use CCK to make your comment Content Type contain additional fields, such as "start time", "end time", "time worked", "supported by [team members]" and so on.
3) Each "Project" is simply a Page with the project description. Each comment is someone's contribution to the project, with any tracking fields you cared to add to the comment Content Type.
4) Additional "reporting" logic in a custom module that looks at these "time record" comments and generates useful aggregate summaries.
Butt simple.
Total time to get system working: 1 day.
Total time to get company using system: same fricking day!
Feeling of control over their environment by client company: total.
Answer: For Drupal 6, there exists the Project module can be extended for providing Bug Tracking as well.
Answer: Things are moving forward in the Drupal community and now there is a complete distribution for project management called ERPAL. See http://erpal.info for more details. ERPAL has full functionality for project management, with invoicing and expense tracking, gantt charts, timetracking, requirements management an much more.
Answer: The list of modules for Drupal 7 that are in the category of project management are visible in this page; both the Project module, and the Case Tracker module are absent in the list.
If you need to use a module that has been already ported to Drupal 7, then I would suggest you to use one of the modules listed in that page.
If you can wait, then I would suggest to wait until Case Tracker will be ported to Drupal 7; between Case Tracker and Project, Case Tracker is probably the module that will first have a Drupal 7 version.
Answer: I would use Storm and its associated modules. It can also be used with Open Atrium.
Comment: I found Storm to be great in principle but in practice required an inordinate amount of time to create a work flow and was generally impossible to explain to non-technical staff members how to use.
Answer: Check out this page http://groups.drupal.org/node/17948 for a comparison of Project Management / Ticket Tracking Systems
Answer: Just to note for completeness, the Storm module, which was mentioned in one of the comments has now changed its name to Project Management. The name change is active for the Drupal 7 version onwards.


Python Tkinter open multiple windows within a function

Question: I have an inbuilt calculator within my program. My main program was designed to be somewhat similar to Microsoft Bob. Now when the user presses the 'Calculator' Button in the main focus, it opens up the part of the calculator where you define your 2 numbers and the operator. When you press 'Results' the answer does not appear in any shape of form until my main program is closed. Any help? Attached is the calculator code sample, and more than happy to change the second window to something else. BTW this is for a school project.
def Calculator():
        calculator = Tk()
        Number1 = DoubleVar()
        Number2 = DoubleVar()
        Operator = IntVar()
        Operator.set(1)
        Entry(calculator,textvariable=Number1,justify="c").grid()
        Entry(calculator,textvariable=Number2,justify="c").grid()
        Radiobutton(calculator,text="Add",variable=Operator,value=1).grid()
        Radiobutton(calculator,text="Subtract",variable=Operator,value=2).grid()
        Radiobutton(calculator,text="Multiply",variable=Operator,value=3).grid()
        Radiobutton(calculator,text="Divide",variable=Operator,value=4).grid()
        Radiobutton(calculator,text="Square",variable=Operator,value=5).grid()
        Radiobutton(calculator,text="Square root",variable=Operator,value=6).grid()
        Button(calculator,text="results",command=calculator.destroy,width=16).grid()
        Number1=Number1.get()
        Number2=Number2.get()
        Operator=Operator.get()
        if Operator==1:Results=Number1+Number2
        if Operator==2:Results=Number1-Number2
        if Operator==3:Results=Number1*Number2
        if Operator==4:Results=Number1/Number2
        if Operator==5:Results=math.pow(Number1,Number2)
        if Operator==6:Results=Number1*(1/Number2)
        Results = "The answer is "+str(Results)
        Answer = Tk()
        Answer.geometry("150x150")
        Label(Answer, text=Results).place(relx=.5,rely=.5,anchor="center")
        Answer.mainloop()

Answer: You can't have multiple Tk objects with their own mainloops.
Or, rather, you can, but whichever one is currently running mainloop, none of the others (and none of their children) gets to do anything until that mainloop finishes.
What you want is to have multiple Toplevel widgets, with the same Tk as their master. (If you just have one Tk, as you usually do, you can leave that as the default.)

But you have another, equally serious problem here.
You're creating a Calculator with a bunch of Tk vars attached, then immediately trying to read those vars and do something with them. You can't do that.
What you need to do is to put all of that in the callback to some kind of user event, like clicking the Results button.

You have one more problem in your code that makes things a bit harder:
Number1=Number1.get()

What you really want here is two separate variables, one the Tk var, and the other an int. And then you need to make the Tk var accessible in the results callback in some way. The obvious way is to move all of this to a class, and store all your Tk vars as instance attributes. If you don't know how to do that, you can always use globals. (Not ideal, but until you learn classes, it's fine.) Then the actual numbers are just local to the callback function.

Putting it all together:
def Calculator(root):
    global Number1, Number2, Operator
    calculator = Toplevel()
    Number1 = DoubleVar()
    Number2 = DoubleVar()
    Operator = IntVar()
    Operator.set(1)
    Entry(calculator,textvariable=Number1,justify="c").grid()
    Entry(calculator,textvariable=Number2,justify="c").grid()
    Radiobutton(calculator,text="Add",variable=Operator,value=1).grid()
    Radiobutton(calculator,text="Subtract",variable=Operator,value=2).grid()
    Radiobutton(calculator,text="Multiply",variable=Operator,value=3).grid()
    Radiobutton(calculator,text="Divide",variable=Operator,value=4).grid()
    Radiobutton(calculator,text="Square",variable=Operator,value=5).grid()
    Radiobutton(calculator,text="Square root",variable=Operator,value=6).grid()
    Button(calculator,text="results", command=lambda event: calculate(calculator), width=16).grid()

def calculate(calculator):
    n1=Number1.get()
    n2=Number2.get()
    op=Operator.get()
    if op==1:Results=n1+n2
    if op==2:Results=n1-n2
    if op==3:Results=n1*n2
    if op==4:Results=n1/n2
    if op==5:Results=math.pow(n1,n2)
    if op==6:Results=n1*(1/n2)
    Results = "The answer is "+str(Results)
    calculator.destroy()

    Answer = Toplevel()
    Answer.geometry("150x150")
    Label(Answer, text=Results).place(relx=.5,rely=.5,anchor="center")

root = Tk()
# Presumably your real code has some top-level stuff, where the
# user can ask you to open a calculator, like a button whose
# command calls the Calculator function? But here, we'll just:
Calculator(root)
root.mainloop()

Comment: Thanks for your help, i had to change only the name of the Tk() and it worked beautifully.


.NET corrigir URL enviada num POST Request

Question: Boa tarde Amigos!
Estou com um problema ao receber uma Url com o método POST.
Eu faço uma requisição ajax conforme abaixo:

$('#ajaxButton').on('click', function () {
            const data = document.referrer.toString();

            $.ajax({
                url: "/negociar-valores.aspx",
                data: data,
                type: "POST",
                success: (data) => {
                    console.log("deu bom:" + data);
                    window.location.href = "/negociar-valores.aspx";
                },
                error: (data) => {
                    console.log("deu ruim:" + data);
                }
            });

        });

NEGOCIAR VALORES

A constante "data" com o método document.referrer.toString() tem o seguinte valor: "http://localhost:46729/cotacao-resultados/?destino=194&periodo=17-08-2019%2C22-08-2019&idade=20&idade=&idade=&idade=&idade="
Porém na página negociar-valores.aspx, quando solicito o valor da url:
NameValueCollection coll;
coll=Request.Form;
System.Diagnostics.Debug.WriteLine(coll.ToString());

Invés de receber a url da forma como descrevi acima, recebo desta forma:
"http%3a%2f%2flocalhost%3a46729%2fcotacao-resultados%2f%3fdestino=194&periodo=17-08-2019%2c22-08-2019&idade=20&idade=&idade=&idade=&idade="
Minha dúvida é a seguinte; existe alguma maneira de converter esse valor recebido para a url correta? substituindo esses "%3a" por ":" e "%2f" por "/" para que eu possa utilizar este dado?
Agradeço desde já!
Answer:
Minha dúvida é a seguinte; existe alguma maneira de converter esse valor recebido para a url correta? substituindo esses "%3a" por ":" e "%2f" por "/" para que eu possa utilizar este dado?

Sim! Use a função UnescapeDataString da classe Uri:
string url = @"http%3a%2f%2flocalhost%3a46729%2fcotacao-resultados%2f%3fdestino=194&periodo=17-08-2019%2c22-08-2019&idade=20&idade=&idade=&idade=&idade=";

Console.WriteLine(Uri.UnescapeDataString(url));

Comment: Muito obrigado! funcionou!


Liferay service builder: is there a practical limit for max number of entities in a webapp?

Question: I wonder if there is a practical limit on the number of entities you can really use in a single webapp? Are there any empirical guidelines to recommend? (Fictitious example: "Do not use more than 30 entities if your main memory on the server is below 1 GB").
Some background: I observed that the number of cross-references in the generated java files grow quadratically, because in one of the directories
(in the src/.../base), each java file/mapped entity imports every other entity.
I have 58 entities currently.
To illustrate, the file service/ClpSerializer.java (which is always generated) has 17000 lines. My war file containing only generated code (and no business logic yet) has 8MB compressed, and 43 MB uncompressed. Yes, my tables are big and have many columns.
Answer: Rather than putting all in one service.xml , why dont you use Module Specific ??
Comment: One service.xml for each table? One service.xml for every 10 tables, say?


Proving $mn = 0$ implies $m = 0$ or $n=0$ for all $m, n \in \mathbb{N}$ using Peano Axioms

Question: I tried using induction on the set
$$S = \{ n \in \mathbb N : m \cdot n = 0 \implies m = 0 \vee n = 0, \forall m \in \mathbb N \}$$

Base step: $0 \in S$ because $m \cdot (0) = 0$ using the definition of multiplication of natural numbers. Then $n$ would be 0.
Inductive step: If $m \cdot n = 0 \implies m = 0 \vee n = 0$, then $m \cdot n^+ = 0 \implies m = 0 \vee n^+ = 0$.

Should I consider both cases when trying to prove the inductive step? I'm not even sure if that is what I should be proving or if the definition of $S$ is even right. Would a proof by contradiction be more appropriate?
Comment: You need to universally quantify $m$ in $S$ and make the appropriate changes to the proof.
Answer: Do it by contra-positive: suppose $m\neq 0\neq n$. There exist $k,l\in \Bbb N$ such that $m=k^+$ and $n=l^+$, (why?).
Thus $mn=ml^+=ml+m=ml+k^+=(ml+k)^+$.
Comment: $m = k^+$ and $n = l^+$ for some $k, l \in \mathbb N$ by the third axiom.
That's a nice and straightforward proof. Thank you.


Discussão sobre arquitetura de software

Question: Eu estou reescrevendo uma aplicação para melhor estruturação da mesma e me surgiram algumas dúvidas.
A aplicação é um sistema de gerenciamento de apostas de futebol e conta com um app web para o gerenciamente e um app mobile para as apostas serem feitas. Então, esta aplicação atualmente é usada por três clientes diferentes e certamente mais usarão no futuro.
Eu gostaria que, diferente do cenário atual, eu não precisasse repetir código pra cada uma das aplicações. Eu gostaria de ter um domínio e identificar qual usuário está fazendo uso do aplicação baseado no subdomínio usado. Por exemplo: usuario1.meudominio.com. Então eu saberia que o usuário à acessar o sistema é o usuário 1 e usaria um token para acessar dados do mesmo em um banco comum à todos os usuários diferenciando os registros por tokens.
Seria arriscado misturar dados?
Eu também pensei em fazer realmente três sistemas separados e até cheguei à fazer o rascunho na imagem abaixo. O Banco API é uma API que vai me fornecer dados de partidas, times, campeonatos e etc.
Eu imaginei o Banco Master como sendo o banco que tem todos os dados em comuns entre todos as diferentes instâncias do sistema, no caso seria tudo que vai vir da API. E os outros três bancos sendo os bancos de cada uma das instâncias. Abri este tópico para ouvir opiniões e compartilhar experiências de como eu posso implementar da melhor forma esta arquitetura.
O que posso mudar?
Agradeço à todos que puderem contribuir.
Obs: Pretendo usar PHP + CodeIgniter para desenvolver o sistema web e o app mobile será escrito com Apache Cordova e o banco usado será MySQL.
Comment: Guilherme, vc está publicando a ideia do seu app. Recomendo ediar a pergunta de modo a proteger sua ideia e continuar deixando sua dúvida escclarecida.
Answer: Legal sua maturidade em enxergar conflitos de responsabilidades entre projetos/softwares. Espero conseguir usar essa sua desconfiança para te recomendar uma proposta de arquitetura.

Identificação e separação de responsabilidades

Identifique os serviços de sua solução. Mas tente enxergar apenas o negócio de cada uma, e fique cego para parte tecnológica - como códigos, dominios, bancos de dados, etc.

Administrador da plataforma - criar clientes, gerir acessos, planos, dashboards, etc;
Clientes - cada cliente será um clienteN.seudominio.com.br.

Cada um desses dois é um projeto independente. Não compartilham códigos, classes, bancos de dados, nada. Isso pq elas devem ter autonomia. Sua administração deve funcionar mesmo se não houver nenhum cliente, e seus clientes devem funcionar mesmo se vc tirar toda sua adminstração do ar - web e banco de dados.

Como as aplicações - administração e clientes - se comunicam?

Em uma primeira analisada, eu faria da seguinte maneira:

Toda atualização de plataforma que é feita da administração para o cliente deve ser feita via Message Queue.
Toda informação que a plataforma deve coletar do cliente:

Algumas informações, o cliente é quem irá informar suas atualizações à administração, via Message Queue.
Outra, mais real time,  administração deverá consumir uma API do cliente.

IMPORTANTE: Uma aplicação - seja admin ou cliente - nunca deve acessar diretamente o banco de dados uma da outra. Isso cria uma super acoplagem, e é uma péssima prática.

Seria arriscado misturar dados?

SIM. E voce já sabia disso, mas perguntou por prudência, e isso é saudável: +1 pra você.
Cada cliente seu deve ser uma instância totalmente isolada. Cada um de seus clientes deve ter uma instância da aplicação web/api, sua própria instância de banco de dados, e sua própria área de storage file - não me vá colocar arquivos dos cliente na famosa pasta upload junto aos códigos da sua aplicação, heim?.

Devo repetir código para cada uma das aplicações?

Óbviou que NÃO. Todos os seus clientes devem rodar o mesmíssimo código fonte, com a última atualização e tudo mais. E esse código deve ser totalmente parametrizável. Desde configurar cores, títulos, imagens, logos, também como credenciais, connectionstrings, storage locations, e por ultimos toggles para habilitar ou não features, recursos, etc.

One Server to rule them all?

Vi no seu desenho que vc tem um servidor hospedado de tudo - aplicação web, api, bancos de dados, etc. Isso não é legal. O ideal é um servidor por responsabilidade. Um para hospedar aplicações web - preferencialmente um para sua administração e outro para os clientes  - outro para sua base de dados, e outro para seu storage file. Esse tipo de approche chamase Cloud First, desenvolva sua solução para que seja já moldada para ser hospedada em nuvem.
Comment: Só agora eu pude ver a resposta e agradeço pela mesma. Você poderia me recomendar o que estudar para desenvolver aplicações com esse aspecto? Pesquisei algumas coisas por conta própria mas quanto mais melhor. Agradeço novamente. Abraço!
Comment: Bom, vou jogar algumas temas. Leia cada um superficialmente e depois aprofunde de acordo com necessidades. Domain Driven Design, Bounded Context, CQRS, Event Source, Message Queue.

Discussão sobre arquitetura de software


Prove $\pi(x) \geq k$

Question: This is the problem 12 in section 2.2 from LeVeque's Fundamentals of number theory.
If $1 < a_1 < a_2 < \dots < a_k \leq x$ and no $a_i$ divides the product of the rest then prove $\pi(x) \geq k$ (where $\pi(x)$ denotes the number of primes less than or equal to $x$).
The hint is to associate a unique prime to each $a_i$.
The case $k=1$ is trivial so assume $k > 1$ from now on.
I tried to show that there is a prime $p_i$ such that $p_i\mid a_i$ and $p_i\nmid a_j$ for all $j \neq i$, i.e., $p_i \mid a_i$ and $p_i \nmid \prod_{j\neq i} a_j$ for all $i$, but I could not find an argument that worked for all $k$.
However I did observe that  if one proves the result for the case where $\operatorname{gcd}(a_1,a_2,\dots,a_k) = 1$ then it is sufficient.
For if $\operatorname{gcd}(a_1,a_2,\dots,a_k) = d > 1$, then we cannot have $a_1=d$ since that violates $a_1 \nmid a_2 \dots a_n$. So we must have $1 < b_1 < b_2 < \dots b_k < x$ where $b_i = \dfrac{a_i}{d}$. We have $\operatorname{gcd}(b_1,\dots,b_k)=1$ and we also have $\dfrac{\prod_{j\neq i} b_j}{b_i} = \dfrac{1}{d^{k-2}}\dfrac{\prod_{j\neq i} a_j}{a_i}$ is not an integer since $\dfrac{\prod_{j\neq i} a_j}{a_i}$ is not.
Comment: $a_i \nmid \prod_{j\neq i} a_j$ means there is a prime $p$ with $v_p(a_i) > \sum_{j \neq i} v_p(a_j)$.
Comment: Yes. Is that sufficient to show, there is a prime with $v_p(a_i) > 0$ and $v_p(a_j) = 0$ for $ j \neq i$? I am probably missing something obvious.
Comment: No, it isn't. $a_1 = 12,\, a_2 = 45,\, a_3 = 50$ satisfies the conditions, but every prime dividing one of the three divides two. But it is sufficient to find an injective map from $\{a_1,\dotsc,a_k\}$ to the set of primes $\leqslant x$.
Answer: We cannot always find a prime $p_i$ dividing $a_i$ but none of the other $a_j$. For example with $k = 3$, $a_1 = 12$, $a_2 = 45$, and $a_3 = 50$, none of the $a_i$ divides the product of the other two, each of $2,3$, and $5$ divides exactly two of the $a_i$, and no other prime divides any of the three.
But we can associate distinct primes to the $a_i$. The condition
$$a_i \nmid \prod_{j \neq i} a_j$$
means there is a prime $p$ such that
$$v_p(a_i) > \sum_{j \neq i} v_p(a_j).$$
If we let $p_i$ any such prime, then $p_i \leqslant a_i \leqslant x$, and for $i \neq j$ we have $p_i \neq p_j$. Thus $\pi(x) \geqslant k$.

Prove $\pi(x) \geq k$


How to reduce image creation time of an image php GD

Question: Using GD functions changing color of an image. Due to several iteration it taking large time to create. As mention below scripts pink(255,0,255) and near about color replace with other dynamic colors. Script output is correct but as mention it taking large time to create a output image.

Is it possible to reduce creation time of an image with color
  changeable functionality or can we change any section of code?

 function changeImageColor($oldColorTriplet, $newColorTriplet, $hueError = 0.4){
        if (!$this->isImageCreated())
            return false;

        $oldColorHSL = $this->RGBtoHSL($oldColorTriplet[0], $oldColorTriplet[1], $oldColorTriplet[2]);
        $newColorHSL = $this->RGBtoHSL($newColorTriplet[0], $newColorTriplet[1], $newColorTriplet[2]);
        $cx = $this->width();
        $cy = $this->height();
        for ($x = 0; $x < $cx; $x++) {
            for ($y = 0; $y < $cy; $y++) {
                $pixel = imagecolorsforindex($this->handle, imagecolorat($this->handle, $x, $y));

                $currentColorHSL = $this->RGBtoHSL($pixel['red'], $pixel['green'], $pixel['blue']);

                if (($currentColorHSL[0] >= $oldColorHSL[0] - $hueError)
                    && ($oldColorHSL[0] + $hueError >= $currentColorHSL[0])) {
                    //$color = $this->HSLtoRGB($newColorHSL[0], $newColorHSL[1], $currentColorHSL[2]);
                    $color = $newColorTriplet;
                    $color = imagecolorallocatealpha($this->handle, $color[0], $color[1], $color[2], $pixel['alpha']);
                    imagesetpixel($this->handle, $x, $y, $color);
                }
            }
        }

        return true;
    }

function RGBtoHSL( $r, $g, $b ){
        $r /= 255;
        $g /= 255;
        $b /= 255;
        $max = max( $r, $g, $b );
        $min = min( $r, $g, $b );
        $l = ( $max + $min ) / 2;
        $d = $max - $min;
        if( $d == 0 ){
            $h = $s = 0;
        } else {
            $s = $d / ( 1 - abs( 2 * $l - 1 ) );
            switch( $max ){
                case $r:
                    $h = 60 * fmod( ( ( $g - $b ) / $d ), 6 );
                    if ($b > $g) {
                        $h += 360;
                    }
                    break;
                case $g:
                    $h = 60 * ( ( $b - $r ) / $d + 2 );
                    break;
                case $b:
                    $h = 60 * ( ( $r - $g ) / $d + 4 );
                    break;
            }
        }
        return array( round( $h, 2 ), round( $s, 2 ), round( $l, 2 ) );
    }

    function HSLtoRGB( $h, $s, $l ){
        $c = ( 1 - abs( 2 * $l - 1 ) ) * $s;
        $x = $c * ( 1 - abs( fmod( ( $h / 60 ), 2 ) - 1 ) );
        $m = $l - ( $c / 2 );
        if ( $h < 60 ) {
            $r = $c;
            $g = $x;
            $b = 0;
        } else if ( $h < 120 ) {
            $r = $x;
            $g = $c;
            $b = 0;
        } else if ( $h < 180 ) {
            $r = 0;
            $g = $c;
            $b = $x;
        } else if ( $h < 240 ) {
            $r = 0;
            $g = $x;
            $b = $c;
        } else if ( $h < 300 ) {
            $r = $x;
            $g = 0;
            $b = $c;
        } else {
            $r = $c;
            $g = 0;
            $b = $x;
        }
        $r = ( $r + $m ) * 255;
        $g = ( $g + $m ) * 255;
        $b = ( $b + $m  ) * 255;
        return array( floor( $r ), floor( $g ), floor( $b ) );
    }

Comment: You could try to use the fxImage routine http://phpimagick.com/Imagick/fxImage however that is not guaranteed to be quicker.
Answer: I got some other way to reduce image creation time :

While uploading an image I get all pixels that are near to rgb(255,0,255) and store in DB.
Than call only those pixel that to
replace colour and implemented above code at only these positions.
Means suppose a image, have 10,000 pixel 1000 pixels are
rgb(255,0,255) than I save this 1000 pixel positions and while apply
colour I send only these 1000 pixel to change the colour.
Answer: I am no expert on PHP+GD but it looks to me like you are taking all pixels within a band either side of some HSL colour and replacing them by a solid colour - if so, you can do that pretty quickly with ImageMagick in PHP. I'll try and show the concept at the command line and you can then benchmark it as ImageMagick is installed on most Linux distros and is available for OSX and Windows.
First let's make a gradient image, called swatch.png, for testing, that includes some pink colour:
convert -size 100x100 gradient:blue-pink gradient:pink-blue -rotate -90 +append swatch.png

Now, let's see what ImageMagick thinks pink looks like in HSL coordinates:
convert xc:pink -depth 8 -colorspace hsl txt:
# ImageMagick pixel enumeration: 1,1,255,hsl
0,0: (63628,65535,57440)  #F8FFE0  hsl(349.524,100%,87.6478%)

So, that makes the Hue component 63628/65535, or 349.524/360 or 97%
Now, if we take the swatch and copy it, then go into the copy and convert to HSL colourspace, separate out the H,S &L channels, and delete the Saturation and Lightness, we will just have the Hue channel present. If we now make everything less than 96% turn black and then make blacks transparent and everything more than 98% turn white and then make whites transparent we will only have any opacity in our image where the hue is between 96-98%, i.e. around our pink colour. If we now fill the image with lime green and overlay it on top of the original, we will see we have replaced the pink hues with lime green.
convert swatch.png                                 \
  \( +clone -colorspace hsl -separate -delete 1,2  \
     -black-threshold 96% -transparent black       \
     -white-threshold 98% -transparent white       \
     -fill lime -colorize 100%                     \
  \) -compose overlay -composite result.png

If we widen the lower-end tolerance to 90% on the Hue:
convert swatch.png \( +clone -colorspace hsl -separate -delete 1,2 -black-threshold 90% -transparent black -white-threshold 98% -transparent white -fill lime -colorize 100% \) -compose overlay -composite result.png

And if we narrow the upper-end tolerance on the Hue:
convert swatch.png \( +clone -colorspace hsl -separate -delete 1,2 -black-threshold 96.0% -transparent black -white-threshold 97.0% -transparent white -fill red -colorize 100% \) -compose overlay -composite result.png

There are other ways of doing this with ImageMagick, but this should give you an idea and you can test it out at the command line before going to the effort of implementing any PHP.


For any integer n⩾1, how do you show that $\sum_{k=1}^{n} \frac{2^k}{\sqrt{k+0.5}}\leqslant2^{n+1}\sqrt{n+1}-\frac{4n^{\frac{3}{2}}}{3}$

Question: For any integer $n\geqslant1$, how do you show that:
$$\sum_{k=1}^{n} \frac{2^k}{\sqrt{k+0.5}}\leqslant2^{n+1}\sqrt{n+1}-\frac{4n^{\frac{3}{2}}}{3}$$
Do you need to find the formula of the partial sum of $\sum_{k=1}^{n} \frac{2^k}{\sqrt{k+0.5}}$ first before moving on to proof whether the inequality is true?
I could not find a suitable way of writing the formula of the partial sum, since this is a divergent series, or is there a way to do so?
Comment: Have you tried induction?
Comment: Have you tried integral comparison ?
Comment: Actually, this is supposed to be a high school contest math question...
Answer: Consider the following upper bound
$$\sum_{k=1}^n \frac{2^k}{\sqrt{k+1/2}} \leq \sum_{k=1}^n 2^k \leq 2^{n+1}.$$
This hints that the required inequality holds for sufficiently large $n$. We now show that it holds for all $n\geq 1$, i.e., for all $n\geq 1$
$$2^{n+1}\leq 2^{n+1}\sqrt{n+1}-4n^{1.5}/3.$$
First observe this holds for $n=1$. Then the claim follows since for all $n\geq 2$
$$\sqrt{n}\leq 2\cdot (\sqrt{n+1}-1) \quad \text{and}\quad 4\cdot n \leq 3\cdot 2^{n}.$$
The following manipulations prove the claim
\begin{align}
\sqrt{n}&\leq 2\cdot (\sqrt{n+1}-1)\\
2^{n}\sqrt{n}&\leq 2^{n+1}\cdot (\sqrt{n+1}-1)\\
4n^{1.5}/3&\leq 2^{n+1}\cdot (\sqrt{n+1}-1)\\
2^{n+1}&\leq 2^{n+1}\sqrt{n+1}-4n^{1.5}/3.
\end{align}


ASP.NET authentication timeout and Logout Events

Question: From my understanding after Googling the issue, the authentication ticket used by ASP.NET for user authentication expires after a set amount of time at which point any postback or page loads will cause the user to be redirected to a login page. However, there is no event that gets triggered when the ticket times out. Therefore, if I wish to implement a logout event, it won't get triggered when the ticket expires.
My question is: Is there anyway to circumvent this issue? I need to log when users log out of my website but if the ticket times out and the user gets redirected to the login page and thinks that they've been logged out so they just close the browser, I will never have a record of when they log out.
Thanks
Comment: There is no guaranteed way to know if the user has been logged out, since there are many things that can happen that would interfere.  For instance, if the worker process was reset or recycled.  Since "login" is not an actual event and is not tracked in asp.net, neither is logout.  The best you can do is timeout, either in Application_EndSession or something else.  You should also know that closing the browser does not "log out", since the authentication cookie is still valid.  The user could re-open the browser and navigate to the page again and still be "logged in".
Comment: My advice is to forget about this "feature", because it's impossible to make sure it's accurate.
Comment: Unfortunately this is what I was afraid of. I guess I will have to come up with a workaround.
Answer: I saw this kind of behavior done by putting the custom object to asp.net cache. You set the cache timeout to the same time-frame as session and you refresh it every time user comes to the website. When cache timeout method is fired you know that user session ended.
This is dirty approach though, application can be restarted, user can return, session is ended, but it does not mean that user is logged out.


With Schema Validation enabled on the HTTP Trigger, can I customise the error message returned on failure?

Question: I'd like to validate the (JSON) input to a Logic App, which I can do using the Schema Validation option:

Can I customise the error message this sends back? My API design has a particular format for the body of a non-success response that we would like to conform to.
I tried setting a response action immediately after the trigger and specifying "Run After" as Failed but the designer won't allow this.
Comment: Could you implement it now?
Answer: The schema validation in HTTP trigger couldn't modify the message, so maybe you could don't validate the json data in trigger.
You could use Parse JSON action to parse the data to json and validate it. For details you could refer to this blog: Validating Json Schema in Azure Logic Apps. The create the response action and set it run after Parse JSON has failed.
You could custom the status code and the response body. I test with outputs('Parse_JSON')['errors'][0]['message'] it will send the Parse_JSON action error message. With this way, you could use parallel branch to create actions after the Parse_JSON success.
Comment: Thanks. This is not the ideal solution as I have a trigger with a validation feature that I am not using and instead have to apply a second action and a conditional, which seems like unnecessary work, when it could all just sit in the trigger. But this is good enough.


Data transformation before forecasting with ARIMA

Question: I have couple of questions in times series forecasting.

If the time series is nonstationary, should we make it to stationary for running auto.arima OR will this function automatically convert it?
How to optimise the auto.arima?
If we take log of a time series to make it stationary, the forecasted values are in the log format. How do we convert them to the original scale?
Comment: what do you mean by "optimise"?
Comment: auto.arima achieves stationarity through differencing, which usually faces the problem regarding trends.. You transform data to control the variance, so that is on yourself. I would suggest the use of boxcox function to find the propert transformation.

Furthermore you can then specify the lambda found in your call to arima and it will automatically convert your data to the original scale
Comment: @Ferdi, I mean if we input the timeseries to auto.arima without making it stationary, assuming auto.arima converts it stationary, without giving any parameters like auto.arima(ts) and if the output is not satisfactory. How do we optimze, i mean which parameters i should tweak?. Pardon my ignorance, i am very much few to the forecasting.
Answer: Be careful the presence of outliers will often cause the box-cox test to incorrectly suggest a power transformation that is uneeded . The box-cox test When (and why) should you take the log of a distribution (of numbers)? can often be misleading and should be used when the required assumptions are met i.e. no pulses , no seasonal pulses ; no level shifts and no trends in the residuals and of course no deterministic change points in error variance at particular points in time.
For more on this please see http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.469.7176&rep=rep1&type=pdf and in particular the section 7 on the "Effect of outliers and influential cases"
Comment: don't know why someone downvoted your answer
Comment: have no clue either ... just trying to throw some light on the applicability of box-cox
Comment: It's very informative to me!
Answer:
If the time series is nonstationary, should we make it to stationary for running auto.arima OR will this function automatically convert it?

auto.arima will automatically convert it. arima, is so-called "auto-regression integrated moving average", there is a parameters "d" which is used for the order of first-differencing.

How to optimise the auto.arima?

auto.arima doing this automatically optimise using the stepwise algorithm.

If we take log of a time series to make it stationary, the forecasted values are in the log format. How do we convert them to the original scale?

If you manually log the time series, then you should manually convert the forecast values to the original scale.


$A\cong B$ then $Th(A)=Th(B)$

Question: question: $A\cong B$ then $Th(A)=Th(B)$
answer: $\phi \in Th(A)$ then $A\vDash \phi$ and $A\cong B$ so we have $B\vDash \phi$
then $\phi \in Th(B)$ and $Th(A)\subseteq Th(B)$ and we could prove $Th(B)\subseteq Th(A)$
and so $Th(A)=Th(B)$.
is this answer true?
Comment: Yes.$\!\!\!\!\!$
Answer: Yes, you've given a complete argument.
One might argue that it's nicer to use proper sentences, not connecting them with a string of "and"s, but the essence is flawless.

$A\cong B$ then $Th(A)=Th(B)$


Effect of nonlinear transformations on the mean

Question: Suppose I have a continuous random variable $X$ and a random variable $Z = f(X)$, where $f$ is a nonlinear monotonic transformation. How can I prove the following relation between the mean and the median if $Z$ is from a Gaussian distribution:
$X^{median} = f^{-1}(Z^{mean})$ ?
I found it in this paper: Warped Gaussian Processes, but I don't see why this is obvious.
Thank you!
Comment: You can't prove this without additional assumptions.  The likeliest one is that for $Z$ "the median and mean lie at the same point" (see the text of the paper preceding equation 9).
Comment: it is true for the median, so, it is also true for the mean only if they coincide
Comment: Thanks! I've edited my question since I'm mainly interested in the Gaussian case and I still don't know how to prove this
Comment: I think I understand now. thank you!
Answer:
Any monotonic transformation doesn't changes the ranks of the data (this directly comes from the definition of monotonicity: if $x_1 < x_2$ then $f(x_1) \le f(x_2)$)
Hence, for any monotonic transformation $f$, the median of $f(X)$ is $f(median_X)$.
For any invertible monotonic transformation $f$, its inverse $f^{-1}$ is also monotonic (as above, this also is directly implied by the definition of monotonicity)
For gaussian distributions, the mean and the median coincide.

Here you are: $f(X)$ is not gaussian, so you can't know anything about its mean, but its median is $f(mean_X)$, because $X$ is gaussian and its mean and median coincide.
Comment: I believe your definition in the first bullet point is in error (or there are different definitions of monotonicity). Shouldn't it read "If $x_1 < x_2$ then $f(x_1) \leq f(x_2)$?" In other words "Non-decreasing" does not necessarily mean "increasing," and vice versa. As an example, in a monotonic function with horizontal regions, for certain values of $x_1 < x_2, f(x_1) = f(x_2)$. Also, this definition seems to apply only to monotonically *increasing* functions. For a monotonically decreasing function, I would expect if $x_1 < x_2$, then $f(x1)\ge f(x_2)$.
Comment: added the equality condition, but I never wanted to provid a full proof, just to make my point clearer, extending that reasoning to decreasing functions is easy enough so that I can gloss over it.
Comment: $f()$ is a natural notation for anyone who has spent more time on calculus than on statistics. For any one the other way round, $f()$ is likely to seem bespoke as notation for probability density function. I suggest $T()$ as generic notation for a transformation, although no notation suits all (some economists would want to underline that time runs $t = 1, \dots, T$).
Answer: This certainly doesn't hold in general. For instance, assume that $X$ is lognormal with log-mean 0 and log-sd 1. Then its median is $e^0=1$, but the mean of $X^2$ (look in the "Properties" section of the Wikipedia page) is $e^2$.


Weighted Quick Union Find

Question: I am taking an algorithms course where they go over weighted quick union find.  I am confused about why we are concerned about the size of a tree as opposed to the depth?
When I tried writing out the code, my code looked different than the solution provided.
From my understanding, the size of the tree (total number of nodes in a tree) is not as important as the depth of the tree when it comes to the run time of the union function (lg n) because it is the depth that will determine how many look ups are needed to get to the root of a node?
Thanks
<code>My code:
public void union(int p, int q) {
    int root_p = root(p);
    int root_q = root(q);

    // If the two trees are not already connected, union them
    if(root_p != root_q) {

        // The two trees aren't connected, check which is deeper
        // Attach the one that is more shallow to the deeper one
        if (depth[root_p] > depth[root_q]) {
            // p is deeper, point q's root to p
            id[root_q] = root_p;
        } else if (depth[root_q] > depth[root_p]) {
            // q is deeper, point p's root to p
            id[root_p] = root_q;
        } else {
            // They are of equal depth, point q's root to p and increment p's depth by 1
            id[root_q] = root_p;
            depth[root_p] += 1;
        }
    }
}

Solution code provided:

public void union(int p, int q) {
    int rootP = find(p);
    int rootQ = find(q);
    if (rootP == rootQ) return;

    // make smaller root point to larger one
    if (size[rootP] < size[rootQ]) {
        parent[rootP] = rootQ;
        size[rootQ] += size[rootP];
    }
    else {
        parent[rootQ] = rootP;
        size[rootP] += size[rootQ];
    }
    count--;
}
</code>
Answer: You are correct that the depth (actually height) is more directly related to the run time, but using either one will result in O(log N) run time for union and find.
The proof is easy -- Given that when we begin (when all sets are disjoint), every root with height h has at least 2(h-1) nodes, this invariant is maintained by union and find operations.   Therefore, if a node has size n, then its height will be at most floor(log2(n))+1
So either one will do.  BUT, very soon you will learn about path compression, which makes it difficult to keep track of the height of roots, but the size will still be available.  At that point you will be able to use rank, which is kind of like height, or continue to use the size.  Again either one will do, but I find the size easier to reason about so I always use that.

Weighted Quick Union Find


Linear Relationship vs Correlation

Question: I am new to machine learning, and I'm trying to cover some of the basics. One of the assumptions of linear regression is a linear relationship.
However on Reddit I was told today that no machine learning model requires a correlation between any of the predictors and the output.
My question is is there a difference between correlation, and a linear relationship?
Comment: Regarding the connection between simple linear regression and correlation, there are some useful answers on SE. See e. g. the answers to [this Q](https://stats.stackexchange.com/q/2125/136579) and [this answer](https://stats.stackexchange.com/a/133331/136579).
Answer:
One of the assumptions of linear regression is a linear relationship.

There is a fairly common confusion on this matter that makes the scope of linear regression look narrower than it actually is.  In regression analysis, we model the expected value of a response variable $Y_i$ conditional on some regressors $\mathbb{x}_i$.  In general, we write the response variables as:
$$Y_i = \mathbb{E}(Y_i|\mathbb{x}_i) + \varepsilon_i \quad \quad \quad \varepsilon_i \equiv Y_i - \mathbb{x}_i,$$
where the first part is the true regression function and the second part is the error term.  (This model form implies that $\mathbb{E}(\varepsilon_i | \mathbf{x}_i) = 0$.)  In a linear regression we assume that the true regression function is a linear function of the parameter vector $\boldsymbol{\beta} = (\beta_0,...,\beta_m)$.  This gives us the model form:
$$Y_i = \sum_{k=0}^m \beta_k x_{i,k}^* + \varepsilon_i \quad \quad \quad x_{i,k}^* \equiv f_k(\mathbf{x}_i).$$
You can see from this model form that we can transform the original regressors $\mathbf{x}_i$ via any transform we want (including a non-linear transform).  Hence, tThe important thing to notice about this is that linear regression does not necessarily assume linearity with respect to the regressor variables.  The "linear" in linear regression comes from the fact that the model is linear with respect to the parameters in the regression function.  Nonlinear regression occurs when the regression function has one or more parameters that cannot be linearised.

...is there a difference between correlation, and a linear relationship?

Correlation is a measure of the strength of a linear relationship between two variables.  It occurs as a special case of linear regression.  If we have use a simple linear regression model under standard assumptions then we have a single regressor $x_i$, with no transformation of this variable.  The simple linear regression model is:
$$Y_i = \beta_0 + \beta_1 x_{i} + \varepsilon_i \quad \quad \quad \varepsilon_i \sim \text{N}(0, \sigma^2).$$
If we fit the simple linear regression model using ordinary least squares (OLS) estimation (the standard estimation method) then we get a coefficient of determination that is equal to the square of the sample correlation between the $y_i$ and $x_i$ values.  This gives a close connection between simple linear regression and sample correlation analysis.
Comment: Hmm... Even though this answer is interesting, linear regression (in most basic stats undergrad courses) does assume that the relationship is linear. Here you are describing Generalized Linear Models (GLMs), which do relax some assumptions and have a link function (here `f`) which is non linear
Comment: The above would be considered within the scope of linear regression.  GLMs encompass linear regression as a special case.

Linear Relationship vs Correlation


PostgreSQL query written millions of times to the log file when using temp files

Question: When a query create temporary files, it writes two entries for each one in the log file. The first one contains the information of the temporary file itself, the second one has the full SQL query. Something like this:
2020-05-08 11:02:32 EDT 2020-05-08 10:17:04 EDT 19297 60/837 0 LOG:  temporary file: path "base/pgsql_tmp/pgsql_tmp19297.3079949", size 297
2020-05-08 11:02:32 EDT 2020-05-08 10:17:04 EDT 19297 60/837 0 STATEMENT:      SELECT ...

Sometimes, a query will write millions of small temporary files (for whatever reason it doesn't create a big one). But then the SQL query will be logged all those millions of times in my postgresql-10-main.log file and fill the logs file system.
Is there a way to tell Postgres to log the statement only upon the creation of the first temporary file? I don't want to completely disable this logging as it is quite helpful in identifying and addressing queries that use too much temp space.
My current log configuration is as follows:
log_timezone = 'localtime'
log_statement = 'none'
log_duration = off
log_min_duration_statement = 5000
log_line_prefix = '%t %s %p %v %x '
log_checkpoints = on
log_connections = on
log_disconnections = on
log_lock_waits = on
track_functions = all
log_temp_files = 0
log_autovacuum_min_duration = 0

Thank you!
Answer: You cannot configure PostgreSQL to log only first temporary file creation but you can set a temporary file size parameter (note that the log entry is created when the file is deleted and not when it is created).
https://www.postgresql.org/docs/9.5/runtime-config-logging.html says

log_temp_files (integer)
Controls logging of temporary file names and sizes. Temporary files can be created for sorts, hashes, and temporary query results.
  If enabled by this setting, a log entry is emitted for each temporary
  file when it is deleted. A value of zero logs all temporary file
  information, while positive values log only files whose size is
  greater than or equal to the specified amount of data. If this value
  is specified without units, it is taken as kilobytes. The default
  setting is -1, which disables such logging. Only superusers can change
  this setting.
Comment: Thank you for your answer. I'm aware of that but then I won't be able to tell, from the log file, the right amount of temporary space used by a query.
Comment: You can try to use auto_explain extension with the right setting with `auto_explain.log_analyze = true`: temporary space should be displayed. Note also that if you have a lot of temporary space used by queries it likely means that `work_mem` setting is too small.
Comment: Ok, thanks. I was hoping there would be some direct way of controlling this, but I'll limit it using log_temp_files as you suggest. I will rely on pg_stat_statement to analyze temp space usage by queries. Thank you for the bonus suggestion about work_mem, I'll look into that!
Comment: @MauricioPeccorini "I won't be able to tell, from the log file, the right amount of temporary space used by a query"  Your proposal to log only the first file also prevents you from telling that, doesn't it?
Comment: @jjanes, no, I was proposing to log the query line only once not the line with the temporary file information
Comment: @MauricioPeccorini OK.  That does seem like a useful idea.  I'm not sure how to go about implementing it in a way that would be likely to be accepted, though.
Comment: @jjanes I don't really know the technical details that would be required, but the logic would be something like "If the query 'starts' using temporary files, log the temporary file creation (respecting the rule for minimum temp file size) AND log the statement", after that, log only the temporary file creation (again respecting the rule of size)


Validação in_array com Ç

Question: Tenho um array:
$enderecos  = array( 'Endereço', 'Endereco', 'Endereço ' );

Uso a função fgetcsv para ler meus CSV, eu faço a verificação no header do csv comparando se o header está incluso no array.
    if(in_array($colunas_csv, $enderecos))
    {
        $endereco_posicao = $key;
    }

Onde $colunas_csv é o retorno do header, o que ocorre é que se o header retornado for Endereco a verificação ocorre, mas, se for Endereço não ocorre, devido ao Ç.
Comment: Mas o `$colunas_csv` está em UTF-8? Se não, qual é a codificação utilizada?
Answer: Você pode se basear nesse exemplo:
<?php
        $arr = ["Endereco","Endereço","Não", "Olá"];
        $decode = implode(' ', $arr);
        $Format = array();
        $Format['a'] = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜüÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿRr"!@#$%&*()_-+={[}]/?;:.,\\\'<>°ºª'; //Pega tudo que tiver acento
        $Format['b'] = 'aaaaaaaceeeeiiiidnoooooouuuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr                                 '; //Todos os itens do Format['b'] vão ser substituidos por esses
        $Data = strtr(utf8_decode($decode), utf8_decode($Format['a']), utf8_decode($Format['b'])); //Faz a substituição
        $Final = trim(strip_tags($Data)); //Limpa a string de espaços iniciais e finais e de codigos html/JS/PHP
        echo $Final;

?>

O que vai ser impresso: Endereco Endereco Nao Ola
Tentei explicar com comentários pra ficar mais fácil entender.

Validação in_array com Ç


Which user is hogging the MySQL database server's CPU?

Question: I maintain webhosting servers and more often than not sometimes a server slows up as a result of increase in load or a large amount of CPU resources used up. I've observed that its the MySQL usage which results in the large increase in the load and the server coming to a crawl, however I'd like to find out which user is responsible for the high MySQL usage ?
Comment: Before you blame the users, make sure your database and the server on which it runs are halfway decently tuned.
Comment: @MichaelHampton Is absolutely right. We constantly see the default query caches and such on MySQL deployments. Depending on your application tweaking the `my.cnf` may prove useful.
Answer: This can be done with a fairly basic SHOW PROCESSLIST; from the MySQL CLI as a MySQL Administrative user.
If there's a process that needs to be terminated, a simple KILL <query Id>; should take care of that.
There's nothing going on for this dev box, but it's an example of what you'd see in the output:
mysql> show processlist;
+----+------+-----------+--------+---------+------+-------+------------------+
| Id | User | Host      | db     | Command | Time | State | Info             |
+----+------+-----------+--------+---------+------+-------+------------------+
|  7 | root | localhost | wikidb | Query   |    0 | NULL  | show processlist |
+----+------+-----------+--------+---------+------+-------+------------------+

As you can see, it displays useful information about the database running the query, runtime, query status, and the content of the query.
Answer: I do agree with @Michael Hampton and @Adrian's responses, but I'd like to add my own suggestion- Try logging into the server and running the following:
[~]# watch mysqladmin pr

That should give you the databases that are being accessed and the queries that are executed, and the addition of 'watch' will monitor and refresh the list. If any database is overloading the server, you can try running the following:
service mysql stop

myisamchk -r /var/lib/mysql/dbname/*.MYI

service mysql start

If the issue persists after restart, you might need to optimize your queries or limit user access to MySQL server resources.
Answer: Another good suggestion is to enable query logs / set the slow query time low and take a peak at those / use a tool such percona-toolkit to parse them.
We personally utilize the MariaDB build of MySQL which has the userstats patch applied which modifies the information_schema to include useful data such as CPU time used, busy time and so forth.
Example:
+------------------+----------+-----------+--------------+--------------+
| USER             | CPU_TIME | BUSY_TIME | ROWS_FETCHED | ROWS_UPDATED |
+------------------+----------+-----------+--------------+--------------+
| xxx_agaipdf |   208850 |    219735 |    372405321 |       950924 |
| xxx_pdfseus |   179626 |    196981 |    145208779 |       771474 |
| xxx_gopdf   |   177303 |    191366 |    323861619 |       653246 |
| xxx_nextuse |   140624 |    153672 |     37374285 |       425618 |
| xxx_gospel  |   135814 |    142874 |     65301676 |       491579 |
+------------------+----------+-----------+--------------+--------------+


True or false: if $(a_n)_{n=1}^\infty \subseteq \{ -1, 1 \}$ then almost certainly $\sum_{n=1}^\infty \frac{a_n}{n}$ converges

Question: Suppose we choose a random sequence of signs $a_n \in \{ -1, 1 \}$, with the distribution being according to uniform Lebesgue measure on $\{ -1, 1 \}^\omega \simeq [0, 1]$.  I wonder if it's true or false that almost certainly, $\sum_{n=1}^\infty \frac{a_n}{n}$ converges (with the series obviously being either conditionally convergent or divergent in any case).
I'm leaning towards true, with a random sequence almost surely having roughly equal numbers of positive and negative entries as $n \to \infty$.  On the other hand, it wouldn't shock me too much to find out the statement is false, or even that the series is almost surely divergent.
(Note this isn't a homework problem or anything, the problem just occurred to me.)
Comment: Does "almost certainly" mean here "except for a set (of sequences) with measure zero", or what?
Comment: That's true, of course, for the reason you suspected. It can be made a bit more explicit using the law of iterated logarithm for the partial sums $a_1+\ldots+a_n$ and Abel partial summation.
Comment: @DonAntonio Yes, or equivalently does $\sum_{n=1}^\infty \frac{a_n}{n}$ converge for almost every sequence $(a_n)$.
Comment: @ProfessorVector You could also just apply [Kolmogorov's three-series theorem](https://en.wikipedia.org/wiki/Kolmogorov%27s_three-series_theorem) for a very straightforward proof.
Comment: @Michael Lee I could also use the martingale convergence theorem, for instance, but I wanted an argument confirming the thoughts of the OP.
Answer: See Kolmgorov's three series theorem

Theorem Let $(X_n)_{n\in\mathbb N}$ be independent random variables. The random series $\sum_{n=1}^\infty X_n$ converges almost surely in $\mathbb R$ if and only if the following conditions hold for some $A > 0$:
  i. $\sum_{n=1}^\infty \mathbb P(|X_n| ≥ A)$ converges.
  ii. Let $Y_n:= X_n\;1_{\{|X_n| ≤ A\}}$, then $\sum_{n=1}^\infty \mathbb E(Y_n)$, the series of expected values of $Y_n$ , converges.
  iii. $\sum_{n=1}^\infty \mathrm{var}(Y_n)$ converges

Now let's consider what happens in this example.  $X_n = \frac{a_n}{n}$ where the $a_n$ are i.i.d. random variables with each value $+1,-1$ occurring with probability $1/2$.
Take $A = 2$.  Then $|X_n| \ge A$ has probability $0$ for all $n$.  So (i) is trivial.
Next, $Y_n = X_n$ and $\mathbb{E}(Y_n) = 0$, so
(ii) is trivial.
Finally, $\mathrm{var}(Y_n) = 1/n^2$, and $\sum\frac{1}{n^2}$ converges.  So (iii) is true.
Therefore, the series $\sum X_n$ converges a.s.
[In fact, this precise example is used to illustrate the three series theorem on that Wikipedia page.]
Comment: Wow, I wasn't expecting something so closely dependent on how fast $\frac{1}{n}$ is decreasing.  So, I think the theorem would say $\sum_{n=1}^\infty \frac{a_n}{\sqrt{n}}$ doesn't almost surely converge?  Do you know whether $\sum_{n=1}^\infty \frac{a_n}{\sqrt{n}}$ almost surely diverges?
Comment: @Daniel Schepler Convergence or divergence don't depend on any finite initial segment of the sequence $a_k$. Such events always have probability $0$ or $1$. So yes, it will a.s. diverge.
Comment: @ProfessorVector Assuming the event is measurable in the first place, right?  (Which it is in this case, since convergence is equivalent to $\forall n, \exists N, \forall a, b \ge N, |\sum_{k=a+1}^b \frac{a_k}{k}| < \frac{1}{n}$ which therefore gives a Borel set.)
Answer: With the partial sums $\displaystyle s_n=\sum^n_{k=1}a_k$ and $s_0=0$, we have
$$\sum^n_{k=1}\frac1k(s_k-s_{k-1})=\sum^n_{k=1}\frac{s_k}k-\sum^{n-1}_{k=1}\frac{s_k}{k+1}=\sum^n_{k=1}\frac{s_k}{k(k+1)}+\frac{s_n}{n+1}.$$
The law of the iterated logarithm says
$$\limsup_{n\to\infty}\frac{s_n}{2\sqrt{n\ln\ln n}}=1\quad\mbox{a.s.},$$ so the first term of the RHS converges a.s. for $n\to\infty$, and so does the second one due to the law of large numbers. That's because with the measure described in the question, the $a_k$ are iid random variables with mean $0$ and variance $1$.
Comment: If I'm not mistaken, the central limit theorem should suffice to show $\frac{s_n}{(n+1)^p} \to 0$ almost certainly and so $\sum_{n=1}^\infty \frac{a_n}{n^p}$ almost certainly converges if $p < \frac{1}{2}$.  Is that correct?
Comment: @DanielSchepler Surely you meant $p>1/2$...
Comment: @DavidC.Ullrich Ah, yes, of course.
Answer: Just for fun let's see how this follows from a bit of basic real analysis, with no fancy probability theory needed.
The Rademacher functions give a concrete realization of a sequence of iid random variables uniformly distributed on $\{-1,1\}$. (The definition at that link is concise but a little slick; to understand what's going on you should check that$$r_1=\chi_{(0,1/2)}-\chi_{(1/2,1)},$$ $$r_2=\chi_{(0,1/4)}
-\chi_{(1/4,1/2)}+\chi_{(1/2,3/4)}-\chi_{(3/4,1)},$$ etc, almost everywhere.)
So the assertion is that the sum $\sum\frac1n r_n(t)$ converges for almost every $t\in(0,1)$. Since the $r_n$ are orthonnormal it's clear that the series converges in $L^2$, but that doesn't a priori imply convergence almost everywhere. (For example, if $\sum|a_n|^2<\infty$ then $\sum a_ne^{int}$ converges almost everywhere, but this is a monstrously difficult theorem of Carleson.)
Let $$f(t)=\sum\frac1n r_n(t),$$converging in $L^2$.
Now for each $t$ define a sequence of intervals $I_n(t)$ by the conditions $t\in  I_n(t)$ and $$I_n(t)=[j2^{-n},(j+1)2^{-n})\quad(j\in\Bbb Z).$$
The Lebesgue differetiation theorem says that $$f(t)=\lim_{n\to\infty}\frac1{|I_n(t)|}\int_{I_n(t)}f$$almost everywhere.
But the cool thing about the Rademacher functions here is that $\frac1{|I_n(t)|}\int_{I_n(t)}f$ is the $n$-th partial sum of the series.
Comment: So, as another way to view it: the Lebesgue differentiation theorem translated to $\{ -1, 1 \}^\omega$ would say for almost all $t$, $2^{-n} \int_{\{ x | x_i = t_i \forall i \le n \}} f \to f(t)$ as $n \to \infty$.
Comment: @DanielSchepler Yes. (Didn't quite follow the notation at first. Was clear what you meant; the $t_i$ looks like $t,$ here...)


Why odds ratio in logistic regression

Question: I'm a bit confused about odds ratio in logistic regression (LR). In a logistic regression textbook (pdf), it says that the odds ratio (OR) is $OR = \exp(\beta_0 + \beta_1X)$. But, I don't understand how the $\exp(\beta)$ is linked with the odds ratio.
This is my intuition about LR. The equation of the LR is:
\begin{align}
\ln\bigg(\frac{p}{1-p}\bigg) &= \beta_0 + \beta_1X  \\[5pt]
&\quad\text{or}  \\[5pt]
\frac{p}{1-p} &= \exp(\beta_0 + \beta_1X)
\end{align}
Suppose that $p$ is the probability of winning a lottery, $\frac{p}{1-p}$ is then the odds of winning the lottery. Therefore, ${\rm Odds}_{{\rm win}} =  \exp(\beta_0 + \beta_1X)$. So can anyone explain how it is then linked to the OR?
Comment: Hi, I was looking at a few places, for example, http://web.pdx.edu/~newsomj/da2/ho_logistic.pdf. It says "The odds ratio is equal to exp(B),"
Comment: What "logistic regression textbook" says this? Can you quote the passage?
Answer: You are right.  If the book said that, it is wrong.  I do wonder if it is a typo or a poorly phrased passage that lends itself to misunderstanding, though.  As you show, $\exp(\beta_0 + \beta_1X)$ is the odds of 'success' predicted by the model.  The odds ratio associated with a $1$-unit change in $X$ is $\exp(\beta)$.  You can also think of is as the factor by which you would multiply the odds  of 'success' associated with $x_i$ to get the odds associated with $(x_i + 1)$ (these are the same, phrased differently).
Since $p$ is the probability of success, $p/(1-p)$ is the odds of success by definition.  Imagine $X=0$, then the right hand side simplifies to $\exp(\beta_0)$, but the left hand side is unchanged.  Thus we can see that $\exp(\beta_0)$ is the odds of success when $X=0$. Now imagine we move to where $X=1$, then we can rewrite the RHS as $\exp(\beta_0)\times\exp(\beta_1)$ using the rules for exponentiation.  Thus we can see that $\exp(\beta_1)$ is the factor by which you would multiply the odds of success to determine the odds of success associated with a $1$-unit increase in $X$.
I think the pdf you link to is sloppily written.  At one point it says, "Odds Ratio. The odds ratio is equal to exp(B)", but there are no subscripts, whereas above that the intercept and the coefficient on X are differentiated by subscripts.  That sets up the reader for a misunderstanding here.
Comment: @user1480478, that's the gist of it: $\exp(\beta)$ is the odds ratio when holding all else constant.
Comment: Aha, I think it is my wrong interpretation. I thought $\exp(B)$ is for the whole term i.e. $\beta_0 + \beta_1X$. So based on what you answer, the result of the equation is the odds and the exponential of the coefficient is the OR. Is this correct?
Comment: Thank you so much I totally got it now from what you edited. Say odds of success given X=0 is $\exp(\beta)$ and the odds of success given X = 1 is $\exp(\beta) * \exp(\beta_1)$. Then the odds ratio of success to failure given the factor X is $\frac{\exp(\beta) * \exp(\beta_1)}{\exp(\beta)}$ which is equal $ \exp(\beta_1)$. Now that is my linkage from odds to odds ratio!
Comment: You're welcome, @user1480478.

Why odds ratio in logistic regression


CFA: should I remove highly correlated items?

Question: I want to Run CFA model (N=400), but I have a question about the correlation between items. I know I should have high correlation between items that make up one factor (cor>.3). I have two factors Anx ( first 4 items) and Eff ( the rest). Anx items looks good, but
some of my efficacy items has correlations >0.8.
should I remove those?
I looked at VIF s scores :
<code>##   Anx_1.post   Anx_2.post   Anx_3.post   Anx_4.post Eff.1_1.post Eff.1_2.post
##         2.71         2.55         2.58         3.11         4.62         2.78
## Eff.1_3.post Eff.1_4.post Eff.1_5.post Eff.2_1.post Eff.2_2.post Eff.2_3.post
##         5.51         6.02         5.57         4.58         4.83         6.29
## Eff.2_4.post
##         1.83
</code>
Comment: Why do you think you should remove them ? What is your research question ? Please provide further details about your study and the data
Comment: Hi Robert, thanks a lot for your reply. I am trying to come up with a some sort of score that represent test anxiety (4 survey questions) and self efficacy (9 questions) to use in the models to explain differences in grades. So I decided to do EFA and CFA to determine which questions to use .

I have an issue with highly correlated items as  I just wondering if items are highly correlated , let say .9, does it mean they measuring almost exactly the same thing, this dropping off one of them remove that redundancy
Comment: I also try to see why my model have quite good TLI and CFI scores but poor rmsea
Comment: Isn't the objective of doing factor analysis is to find "common factors" that can explain several measured events that are often times correlated?
Answer: You should not remove items of them is correlated highly with another unless you have good reason to believe that they are measuring exactly the same thing and the only difference in the scores for those items is measurement error. If they are measuring the same thing different ways, then by removing one (or using an average is another common mistake) then you are losing information.
Be guided by the underlying theory of what is driving the data generating process along with expert knowledge.
Comment: thanks a lot. And how can i then explore the multicollinearity? according to this source : strong correlation is strong sign of multicollinearity (https://www.edupristine.com/blog/detecting-multicollinearity) cor .90 that we would need to begin worrying about multicollinearity at (according to Knekta).
Comment: That link is talking about regression. You are doing factor analysis.


Selecionar resto de união entre tabelas

Question: Tenho duas tabelas, CLIENTES e VENDAS.
Gostaria de saber quais clientes não tem nenhuma venda, sendo que armazeno na tabela vendas o ID do cliente.
Tentei isso mas sem sucesso:
SELECT *
FROM cliente
RIGHT JOIN vendas ON (vendas.id_cliente = cliente.id)
WHERE vendas.id_cliente IS NULL

Answer: Use a cláusula NOT EXISTS
SELECT * FROM cliente
WHERE NOT EXISTS(SELECT vendas.id_cliente FROM vendas WHERE vendas.id_cliente = cliente.id)

Se a subquery não retornar registos é porque não existe esse id de cliente na tabela vendas, isso faz que EXISTS seja falso, o NOT torna-o verdadeiro e esse cliente é retornado pelo SELECT.
Comment: Exato, o melhor caminho, assim acaso ele use um sistema de paginação ele não terá dificuldade em usar o `LIMIT offset, ...`
Answer: Tenta com o LEFT JOIN, assim:
SELECT *
FROM cliente
LEFT JOIN vendas ON (vendas.id_cliente = cliente.id)
WHERE vendas.id_cliente IS NULL

Comment: Left join ele traz os dados tbm. Mais não é obrigatorio.
Se ele tiver alguma venda traz do mesmo jeito.
Comment: Concordo com você que o LEFT JOIN vai trazer tudo, mas por isso usamos "WHERE vendas.id_cliente IS NULL" vai filtrar só quem não tem venda. -1 por isso?
Comment: Pela lógica não temos vendas sem clientes, e podemos ter clientes sem vendas. vo retirar o -1
Answer: Olá, Tente isto:
SELECT *
FROM cliente
RIGHT JOIN vendas ON (vendas.id_cliente = cliente.id)
WHERE vendas.id_cliente = NULL

Comment: Podes explicar porque esta solução pode resolver o problema. Assim o AP (autor da pergunta) vai perceber o que estava errado e como resolver o problema...

Selecionar resto de união entre tabelas


Matrix that transforms the vector components inverse of the matrix that transforms the basis vectors

Question: I'm starting to learn about tensors and my textbook (Riley, Hobson and Bence, 3rd) states that the matrix that transforms the vector components must be the inverse of the matrix that transforms the basis vectors, without an explanation whatsoever.
If we introduce a set of basis vectors $\mathbf e_1, \mathbf e_2,\mathbf e_3$, then we can describe any vector $\mathbf x$ in terms of its components $x_1, x_2, x_3$ with respect to this basis: $$\mathbf x = x_1 \mathbf e_1+ x_2 \mathbf e_2+ x_3 \mathbf e_3 = x_i\mathbf e_i$$
where we have used the summation convention to write the sum in a more compact form.
If we now introduce a new basis $\mathbf e'_1, \mathbf e'_2,\mathbf e'_3$ related to the old one by
$$\mathbf e'_j = S_{ij}\mathbf e_i$$ where the coefficient $S_{ij}$ is the $i$th component of the vector $\mathbf e'_j$ with respect to the unprimed basis, then we may write $\mathbf x$ with respect to the new basis as  $$\mathbf x = x'_1 \mathbf e'_1+ x'_2 \mathbf e'_2+ x'_3 \mathbf e'_3 = x'_i\mathbf e'_i\ .$$
Now, my question.

If we denote the matrix with elements $S_{ij}$ by $S$, then the
components $x_i'$ and $x_i$ in the two bases are related by $$x_i' =
 (S)^{-1}_{ij}x_j\ .$$

How does it follow that the matrix that transforms the vector components must be the inverse of the matrix that transforms the basis vectors?
This Wikipedia article on contravariant vectors says the same, without explanation:

the matrix that transforms the vector components must be the inverse of the matrix that transforms the basis vectors.
Comment: You may use the equation $e_j'=S_{ij}e_i$ to decompose $x_j$ in base $j$ into base $i$ yourself.
Answer: Here's a proof. By definition, the matrix $S$ satisfies
$$
\mathbf e_i' = S_{ji}\mathbf e_j.
$$
With the definition of the inverse, it follows that
$$
\mathbf e_i = (S^{-1})_{ji} \mathbf e_j'.
$$
With that, we have
$$
\mathbf x = x_j \mathbf e_j = x_j (S^{-1})_{ij}\mathbf e_i' = \left[(S^{-1})_{ij} x_j\right] \mathbf e_i'.
$$
So indeed, $\left[(S^{-1})_{ij} x_j\right]$ is the coefficient of $\mathbf e_i'.$


Why would this piece be called "Adagio in D minor" when it's in E minor?

Question: I have very little theoretical knowledge, but AFAICT this piece is not in D minor, but in E minor?
Adagio in D minor, by John Murphy from the soundtrack of Sunshine:

An easier version to analyse, still in the same key, would be:

My rudimentary analysis tells me this mainly uses a very straight forward progression of I vi iii V (and a little bit of variation) in Em. But why would it be called "Adagio in D minor" then? I mean, is there something I'm overlooking, from a theoretical POV?
(I assume the most logical answer would be that John Murphy actually first wrote it in D minor on e.g. piano and then transposed it to E minor for piano & orchestra w/o bothering to rename it?)
Comment: It's been used in over 30 different situations. Have you found them all to be in key Em?
Comment: Did some research and, at the very least, the movie OST version and the remastered version the composer released are both in E minor. Granted, I have heard several organ pieces played on a North German organ that plays music one whole tone *above* the notated key, with a claim that Baroque North German tuning put the A above Middle C a whole tone above where we put it today....
Comment: @Tim I don't know, does that matter? It was written for the movie, and only became an ubiquitious icon afterwards.
Answer: The last post in this earlier thread discussing precisely the OP's question, https://www.gearslutz.com/board/songwriting/722231-theory-question-adagio-d-film-sunshine.html, contains a post from that thread's OP claiming this:

Official Answer from John Murphy it is in E minor it was written before the film and transposed to E minor as in his words it sounded better for the film as it gave more hope..

Unless we can actually find the interview or post in question, I'd treat this answer with a grain of salt.
Other people on web pages like https://www.reddit.com/r/musictheory/comments/i52rqo/adagio_in_d_minor_john_murphy_but_why_d_minor/ that ask the same question often assume that this answer means that the original, unpublished piece was in D minor and the film version is in E minor.


Piano Sheet Music Symbols of Long Diagonal Lines

Question: I know sometimes piano sheet music will have elongated bold lines running from a note(s) in the treble clef to a note(s) in the bass clef or vice versa, indicating that you should play the note(s) with the opposite hand. The two lines form a large V or upside down V.

What is the proper/formal name of these solid boldfaced diagonal lines?
Comment: I took a picture of the sheet music and uploaded it to the question.  Hopefully, this will help.
Comment: Any kind of fingering notation is completely optional.
Comment: I suspect we have to do with a glissando.  Do the lines in question resemble the ones in this question ? http://music.stackexchange.com/questions/41971/what-does-a-straight-line-connecting-notes-on-different-clefs-mean/42538#42538
Comment: For me this looks like a poorly typeset score. It would make more sense, if a constant number of voices were assigned to each hand, but in your example the lines seem quite arbitrary. Don't mind and play however you like it most.
Comment: I'm more curious about the horizontal bracketed line in the last bar. Presumably, a sustain pedal indication (without the usual "Ped" annotation), though that would have a slightly dissonant c6 (then again, that c is a melody note, so that may work).
Answer: Assuming you're talking about an image like this...then it just the composer telling you what clef the melody is moving to. This is helpful because a lot of times you're going to want to play the melody louder.
This doesn't mean you have to switch hands at all.
From @patrx2 this notation does not seem to have a formal name.
Edit: Adding an image in case the above link doesn't work:
Comment: I do not believe this is a glissando. But I also don't know of a specific name for this. "Voice leading line", maybe? Usually there is a reason for notation in a piece of music. But ultimately it is optional if it doesn't work for you.
Comment: Given the utterly vague nature of the question, this is a good attempt to help, and downvoting it seems wrong. So I upvoted.
Comment: Nope, not a glissando. Glissando has a very specific meaning, namely to play very rapidly all the notes between the notes on each end of the line, either the white keys, or the black keys, or a full chromatic run. Good notational practice usually starts the glissando with a partial run of beamed notes to specify the scale used, then the line with *gliss.* over it as a shorthand for the remainder of the run (to the end note). *This* particular use of a diagonal line has no formal name that I am aware of. It is, as @jomki says, an optional aid to understanding.
Comment: Jeremy W, thank you for your photo and response.  I believe that in some situations the composer shows the change in melody.  Thank you for your clarifiation.  However, could you please see the new picture I added to my original question?  This pic is taken from a Disney piano solo and I believe the purpose of these lines is different. In this situation, the composer is intending for the change of hands.  Do you agree?
Comment: @Margaret Yes, this score tries to tell you "Keep playing the upper chord with your right hand even though it's written in the lower system". It uses voice leading lines to express this (but it would have been better to simply write "mano destra" or "right hand"). It's definitely not a glissando. Chord glissandi are way to difficult for a fun play-along score like this.
Comment: I don't see how the lines in this notation show anything useful. It should be obvious to anybody with the slightest knowledge of keyboard playing that the chords in the final bar are best played with both hands (so adding MS/MD or LH/RH are also pointless). And if you look up the lines on the internet and decide wrongly that they mean "glissando", they are positively misleading you. But they do have the function of filling up some otherwise empty space, and thus making the score look a bit prettier.
Answer: In the image you've now posted, the arranger is telling you to use your left hand to play the F in the bass clef, followed by the bottom three notes in the arpeggiated chord, followed by the Bb and the F in the bass clef.
This is very similar to the answer posted by @Jeremy, but it's not specifically telling you where the melody is going. It's asking you to move your hand.
It's required, because it's rather difficult to play a seven note chord with just one hand, without using your nose. The arranger has decided to make this transition clearer by using the lines you refer to.
Comment: FYI, I originally attempted to add this as a comment, but I can't right now. If it's too close to Jeremy's answer, I'm happy to delete it.
Comment: The lines are *not* for suggestion which hand has to play what: the stems of the chords  (when in the same clef) do that here. The lines are really just to indicate the voicing.
Comment: I agree that an experienced player would automatically interpret the stem direction in that way, but it's not immediately obvious. If the piece is intended for 'beginner' players (whatever that means), I think the notation is intended to make the hand movement obvious. Particularly considering that the downstems in the previous measures do not imply 'play me with your other hand'.
Comment: True, it may help beginners (whether it's intended as such, I don't know). Though "LH" and "RH" would have been more helpful & clearer. I guess I should tell the editor that, not you ;-).
Comment: I shall send a strongly worded thought bubble in their direction ;-). Honestly, I assumed that a Disney piano solo book was probably targeted towards a beginner, and went from there.
Comment: Does anyone know the name of these lines used in this Disney song picture?
Answer: As others have supposed, there is no formal name for these lines. In Elaine Gould's Behind Bars, which is the standard reference for music notation, she just refers to them as "diagonal lines":

A middle part may move between staves according to which hand plays it.... A diagonal line may trace the progression between staves.... A dotted line is most conspicuous; a solid line can look like a glissando.... (page 307)

When a voice with an independent contrapuntal line moves stave ..., it is usual to show the voice-leading with a thin diagonal line (solid or dotted) between the notes. (page 475)
Comment: Nice find, and thanks for posting an answer that actually addresses the question rather than focusing on the function of the lines.  I agree, however, with Margaret's assessment of their function, namely that they indicate the hands moving from one staff to another.  It may be more common for such lines to be used to indicate details of inner voices, but that's clearly not what's going on here.
Answer: These thin (not boldface) diagonal lines indicate that notes in a "voice" (not necessarily a hand) in one staff is moving to the other staff.
They are often solid, but are sometimes dashed to distinguish them from glissandi or something else.  They can (and should) be avoided when beams connecting notes in each staff can be used instead.
I don't think there is formal name for these lines, but I would propose "staff changing lines", "voice following lines", or something similar.
Comment: If someone would like to offer an explanation for the down vote, I would appreciate that.


why this error has come ? "static declaration of function follows non-static declaration"?

Question: I am learning about static function and as per rule if i declare function as
a static function then i can't access this function into other c file and if i try to access then there should be an error "undefined reference to `fun"
so i declare and define static function into add.c and add.h file and call that function into main.c file but i am getting different error i.e "static declaration of 'fun' follows non-static declaration"strong text
so my question is that why this error has come ????
please forgive me for my poor English !!!!
<code>/************** main.c****************/
    #include <stdio.h>
    #include <stdlib.h>
    #include "add.h"

    int main(void)
    {
      printf("%d ", fun());
      printf("%d ", fun());
      return 0;
    }

/***************add.c*************/

    #include <stdio.h>
    #include "add.h"

    static int fun(void)
    {
      int a=5,b=4;
      return a+b;
    }

/*********************add.h*************/

    #ifndef ADD_H_
    #define ADD_H_

    static int fun(void);

    #endif /* ADD_H_ */
</code>
Comment: Since static functions are file-local, it makes no sense at all to put static function declarations in header files.  In this case, you can't make `fun` static in `add.c` if you want to call it from `main.c`.  Different files, right?  So decide:  either (a) static, one file only, not in header file, or (b) non-static, in header file, callable from any file.  Choose.
Comment: Hey tom thanks for understanding this
!!!!
Comment: I am tempted to reopen this question because it is not a duplicate of the purported original. This question asks why OP gets an error message stating "static declaration of function follows non-static declaration", and that is not explained in the original. However, it does not seem the code in the question should generate that message, so there is probably a mismatch between the code and the question. The question should have been clarified or closed with a different reason, such as no longer reproducible or unclear what you are asking.
Answer: A static variable or a function is seen only in the file where it is declared.
C11 standard

18.104.22.168
If the declaration of a file scope identifier for an object or a
  function contains the storage-class specifier static, the
  identifier has internal linkage.


Are $\sigma_{70\%} = cte * \sigma /\sqrt{N}$, & $\sigma_{\bar x_{70\%}} = cte * \sigma /\sqrt{N}$ valid with non-normal distributions?

Question: My working population is non normally distributed and from time to time I need to take a sample of it.  Sometimes my sample exists of 100 units, at other times of 150 units. Of my sample I calculate the mean, $\mu$, and with bootstrapping I determine the SE, $\sigma_{\bar x}$. Since $\sigma_{\bar x} = \sigma /\sqrt{N}$, I calculate $\sigma$.  So far so good, by using control charts ($\mu,\sigma$) I can now see if there is anything happening to worry about.
By use of deviation calculation rules you can prove quite easily that the formula  $\sigma_{\bar x} = \sigma /\sqrt{N}$ also can be used for non normal distributions.
I play with the idea to make control charts using the trimmed mean and the 70%-value.  Now I am not so sure anymore. (Frankly, I have my doubts whether you can do this for normal distributions as well.) Can I use the same simple trick to remove the $n$ from my equation?
Let me put it like this:  Is what I am writing valid?
$$\sigma_{70\%} = cte * \sigma / \sqrt{N}$$ with a $cte$ independent of the value of N?
$$\sigma_{\bar x_{70\%}} = cte * \sigma /\sqrt{N}$$
with a $cte$ independent of the value of $N$?
To use my control charts I don't need to know the value of my $cte$.  For my s-chart I can just plot out $cte* \sigma$ in function of my sample number.  But I really need to get rid of the $N$!
I hope you understand what I am getting at.  I would already be happy with a yes or a no, you can not do that anymore.  If you can direct me to a place where I can find more information about this problem I would be even more grateful.
Comment: If you're going to invent a new control charting procedure, then there are more fundamental questions to ask: you need to ascertain the quality control analogs of false positive and false negative error rates. These are measured by the expected lengths of in-control runs when the system is in control and out of control, respectively. So I don't think it's productive to ask whether you can "do that;" instead, think in terms of how to achieve good run length properties for your procedure so that it works as intended.
Answer: No.  The reason the square root of n works for standard deviations is because the variance of a sum is the sum of variances.  So for the sample mean,
var ({X$_1$+X$_2$+...+X$_n$}/n)= [var(X$_1$)+var(X$_2$)+...+var(X$_n$)]/n$^2$= n σ$^2$/n$^2$ = σ$^2$/n.  Hence the standard error is σ/√n.  The same result does not hold for trimmed means or percentiles of estimates.


IE11 doesn't send a form if cookie is undefined

Question: I have a webform which has asking for some cookie settings:
<code>par=Cookies.get('demo'); // => 'value'
</code>
Cokies are set after part1 of current Form  filled out.
If to fill Form1 and than to fill current Form everything works well however if I open a page directly by weblink with no Form1 was fillled out (cookie 'demo' is undefined) than Form is not submitting.
No errors, no message. Button is processing but data is not sending out. How to fix it?
THE ISSUE HAPPENS ON IE11 Only.
Comment: `par=Cookies.get('demo') || '';` The `|| ''` at the end defaults the value to an empty string if undefined.
Comment: @JM-AGMS Thank you, it works in my case! Appreciate your support!
Comment: @ JM-AGMS, I suggest you to post your suggestion as an answer. @ J.First Coder, I can see that your issue was solved. So you can try to mark the answer for this thread when JM-AGMS post the answer.
Answer: par=Cookies.get('demo') || ''; The || '' at the end defaults the value to an empty string if undefined. – JM-AGMS 12 hours ago


What is the correct name to give to a taxonomy term page template file?

Question: I have a taxonomy term page, which is not a view. It just lists all the content for the taxonomy. I would like to customize this page, and I have tried all permutations and combinations of names for the template file. The template file just won't work.
I have tried page--taxonomy--term--5.tpl.php, page_taxonomy_term__5.tpl.php.
What is the right filename to give to the template file, in this case?
I am using Drupal 7.
Answer: I use, for instance,
page--taxonomy--term--6.tpl.php
Make sure you clear the cache in Configuration > Performance > Clear all caches after creating your template.
Answer: I found that template.php file also needed a preprocess function for this to work:
function THEMENAME_preprocess_page(&$variables) {
 if ( arg(0) == 'taxonomy' && arg(1) == 'term' ) {
   $term = taxonomy_term_load(arg(2));
   $variables['theme_hook_suggestions'][] = 'page__taxonomy__term__' . $term->tid;
    }
}

then page--taxonomy--term--5.tpl.php works for a specific term
Comment: Thx, keva. That worked!
Answer: You can use the theme developer module to find any template name or theme function. Just enable the module and point and click on the thing you like to theme differently.


Is it a boundary or overthrows?

Question: Consider a scenario where a fielder is chasing a ball that is running away to the boundary. He puts in a dive, gets a hand to the ball but it runs over the boundary ropes. The umpire signals a boundary and 4 runs are awarded to the batting side.
Now, consider a scenario where two fielders are chasing a ball that is running away to the boundary. The first fielder slides, stops the ball and passes it to the second fielder who throws it back to the wicket keeper. The batting side is only awarded the number of runs that they run between the wickets.
My question is based on this third scenario. Two fielders are running behind the ball. The first slides, stops the ball and wants to pass it to the second fielder. But his throw misses the second fielder and the ball rolls over the boundary ropes.
How many runs will the batting side be awarded in this scenario?
Answer: Though in both, the first and third scenario's, the ball comes off the fielder's hand and goes to the boundary, they are treated differently. This is because in the first scenario, the fielder never had control of the ball that he was trying to stop where as in the third, the fielder had total control of the ball before he chose to throw it to this teammate. Therefore, these two cases are treated differently when it comes to runs awarded.
Law 19.7 states that,

Overthrow or wilful act of fielder
If the boundary results from an overthrow or from the wilful act of a fielder the runs scored shall be
(i) any runs for penalties awarded to either side and
(ii) the allowance for the boundary and
(iii) the runs completed by the batsmen, together with the run in progress if they had already crossed at the instant of the throw or act.

The third scenario of the question is treated as overthrows and the batsman will be awarded the combined runs of scenario 1 and scenario 2. In effect, he will score the number of runs run between the wickets plus a boundary.

Is it a boundary or overthrows?


Proving the Chinese Remainder Theorem using the Pigeonhole Principle

Question: I am trying to prove a version of the Chinese Remainder Thoerem using the pigeonhole principle.
The theorem that was provided:
If $n$ and $m$ are relatively prime, then for all integers $0 ≤a< n$ and $0 ≤ b < m,$ there is an integer solution to the equation set $x\equiv a\pmod n$ and $x\equiv b\pmod m$.
Note that those are equal signs and not congruency, but in this case, I don't think that should impact it. I started with trying to rearrange the statements to maybe make more sense of them (so it became $x-nc=a$ which became $x=a+nc$ where $c$ is whatever constant needed to satisfy the equation due to the definition of modulo), however, from here I'm stuck.
Specifically with the pigeonhole theorem, I'm unsure how to use it in this case. I was also given the hint to consider the sequence $b, b+m, b+2m, ..., b+(n-1)m,$ but unsure how to consider it.
Thanks for any help you can give.
Comment: That finite sequence is a complete residue class modulo $n$. So $b+km \text{ mod } n = a$ for some $k$, but by construction equals $b$ modulo $m$
Comment: By  the Theorem [here](https://math.stackexchange.com/a/767456/242), $\,\gcd(n,m)=1\Rightarrow  f(x) = mx+b \pmod{n}\,$ is $1$-to-$1$ so onto, by Pigeonhole.
Answer: From the hint:
$$b, b+m, b+2m,..., b+(n-1)m$$
forms a complete residue class modulo $n$. To see this, first consider the sequence
$$0,m, 2m, 3m, ..., (n-1)m$$
Since $(m,n)=1$, we have $xm \equiv ym \text{ mod n} \iff x \equiv y \text{ mod n}$, since $m$ has a mutiplicative inverse modulo $n$. Hence each of these elements in the sequence are unique. Adding $b$ does nothing more than cyclically permute the residue class.
By the pigeonhole principle, for any $0\le a < n$, we must have $b+km=a \text{ mod n}$ for some $k\in\{0,...,n-1\}$. Then $x=b+km$ satisfies the property you want.
Answer: This is a particular and a "partial" case of the Chinese Remainder Theorem. The problem also appeared in the book "Topics in Algebra " by I.N Herstein in the chapter of Ring Theory. But we can do it in a much elegant way. Here is a basic solution to the problem:
We consider the numbers $a,a+2m,a+3m,\cdots,a+(n-1)m.$
We note that this is a complete residue system congruent modulo $n.$

Definition: A set $S$ of integers is called a complete residue system congruent modulo $n$ (, where $n\in\Bbb Z$) if  every $y\in \Bbb Z$ is congruent to one and only one numbers from the set $S.$ For example, $S=\{0,1,2,...,n-1\}$ is a complete residue system congruent modulo $n$ as, ever integer $y$ leaves a remainder $r\in S$ when divided by $n$ i.e $y=nq+r$ so, $y\equiv r(\in \Bbb Z)\pmod n.$ Also, as this $r$ is unique( for a number cannot leave two different remainders!) so, this proves that $S$ is a complete residue system. Also, this set $S$ is not unique. The set, $S'=\{1,2,...,n\}$ may also serve as a complete residue system modulo $n.$ (Why?)

Lemma: A set of $n$ integers is called a complete residue system congruent modulo $n$ iff no two of those $n$ numbers are congruent to each other modulo $n.$ (Prove!)

(For a more detailed discussion on these above facts please refer to Chapter -2 of the book, "An Introduction to the Theory of Numbers" by Niven,Zuckerman and Montgomery.)

Ok, so we come back to the problem. The set $a,a+2m,a+3m,\cdots,a+(n-1)m $  is a complete residue system congruent modulo $n.$  This is because, it satisfies the lemma above.
To prove this, we need to show that no two of these $n$ numbers are congruent modulo $n.$ Let us assume the contrary, for the sake of contradiction.
Say, $p=a+k_1m,q=b+k_2m\in \{a,a+2m,a+3m,\cdots,a+(n-1)m\}$ and $p\neq q$(i.e $k_1\neq k_2$). If $p\equiv q\pmod n$ then it means that $$a+k_1m\equiv a+k_2m\pmod n\implies n|m(k_1-k_2)\implies n|(k_1-k_2),$$ as $\gcd (a,m)=1.$ But $k_1,k_2\in\{0,1,...,n-1\}$ so this pissible only if, $k_1=k_2$, a contradiction.
So, indeed, $a,a+2m,a+3m,\cdots,a+(n-1)m $  is a complete residue system congruent modulo $n.$ So, each of these $n$ numbers leaves a remainder of $\{0,1,2,...,n-1\}$ in some order.
Given, $a,b\in \Bbb Z$ so, $b\equiv a+km(=x)\pmod n,$ where $k\in\{0,1,2,...,n-1\}.$ This means, $x=a+km=b+nk'$ where $k'\in\Bbb Z.$
Now, we observe, that, $x=a+km$ is a solution to $x\equiv a\pmod m$ and $x\equiv b\pmod n.$ This completes the proof.


Refresh some jquery on browser window resize

Question: I am using a third party carousel which adds in-line widths and heights styles on the fly. The site uses media queries to resize the carousel container when the browser size is reduced. My issue is that the page has to be refreshed for the media query to come in. So can I have the jQuery function refresh on resize so it re-work out its widths/heights?
Here's the jQuery:

Answer: Use the resize() function on the window object:
$(window).resize(function(){
    $("#carousel").featureCarousel({
        // include options like this:
        // (use quotes only for string values, and no trailing comma after last option)
        carouselSpeed:700,
        smallFeatureWidth:0.8, smallFeatureHeight:0.8, sidePadding:0, topPadding:0
    });
});

Then you can use $(window).height() and $(window).width() to get your new size and adjust from there.
Answer: Strangely enough I was searching for refreshing on window re-size for the exact same reason. I have a logo scroller in a responsive design and the images are stacking on top of each other when the window re-sizes. The best solution for this is the following:
1-place the scroller in an iframe
2-add a class to the iframe with the logo scroller on the parent page and use java to refresh the iframe on window resize.


Deleting a list of entries LDAP PHP

Question: I want to be able to delete multiple different DNs (entries) from my LDAP server on a single call request by providing all the DNs as an array using PHP. How can I manage that? So far I only found a way to delete a single entry, so I can iterate over the array of the DNs and call make different requests to the server, for every DN.
I need a better and more efficient way to delete multiple entries on one call to the LDAP server please.
Answer: You can't. This is a limitation of LDAP, not PHP. LDAP only allows one DN per request. So any request can only affect one object in the directory.
For example, the LDAP documentation for a delete operation doesn't allow any way to specify more than one DN.
So you will have to loop through all the DNs and use PHP's ldap_delete on each.
Comment: Yeah, if you look at [the source code for `ldapdelete`](https://github.com/openldap/openldap/blob/master/clients/tools/ldapdelete.c#L198), it just does a loop and makes one delete request per DN.
Comment: Thank you for your answer (:
I saw this page:
https://docs.ldap.com/ldap-sdk/docs/tool-usages/ldapdelete.html

and it made me think, perhaps there is a way to make the query in the link above, as a raw command, from PHP?
Comment: Oh I see, thank you.
By the way, do you know if this is something that's about to change?
Comment: I doubt it. The LDAP specification hasn't changed since 2006. Keep in mind that deleting multiple objects in one request would introduce other complications. Say that you send 20 DN's to delete, and the 10th one fails. What should happen? Should it roll back the deletion of the first 9? Should it just stop processing them and leave the next 10 alone? Should it continue trying to delete the rest? As it is, you have control of how to handle any errors.
Comment: I see. Thank you (:
(It could work like the SQL WHERE IN, "DELETE FROM  WHERE  IN (a1, a2... a_n)")

Deleting a list of entries LDAP PHP


Kernel panic - not syncing: VFS: Unable to mount root

Question: I uploaded a centos 6.2 VMDK to s3 and then converted it to volume using ec2 import volume.
Then i took the snapshot of the volume and deleted it.Now I am trying to create a instance from the snapshot and keep getting following error:
"Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(8,1)"
Even i dont know which AKI to use while restoring the snapshot...Currently i am trying to restore using default values.
Full system log is as follows:
<code>Linux version 2.6.16-xenU (root@ip-10-204-118-8) (gcc version 4.0.2 20051125 (Red Hat 4.0.2-8)) #14 SMP Wed Nov 23 08:48:06 EST 2011

BIOS-provided physical RAM map:

Xen: 0000000000000000 - 0000000026f00000 (usable)

0MB HIGHMEM available.

623MB LOWMEM available.

NX (Execute Disable) protection: active

Built 1 zonelists

Kernel command line: root=/dev/sda1 ro 4

Enabling fast FPU save and restore... done.

Enabling unmasked SIMD FPU exception support... done.

Initializing CPU#0

PID hash table entries: 4096 (order: 12, 65536 bytes)

Xen reported: 1795.672 MHz processor.

Console: colour dummy device 80x25

Dentry cache hash table entries: 131072 (order: 7, 524288 bytes)

Inode-cache hash table entries: 65536 (order: 6, 262144 bytes)

Software IO TLB disabled

vmalloc area: e7800000-f53fe000, maxmem 2d7fe000

Memory: 618496k/637952k available (1970k kernel code, 11016k reserved, 628k data, 156k init, 0k highmem)

Checking if this processor honours the WP bit even in supervisor mode... Ok.

Calibrating delay using timer specific routine.. 3593.73 BogoMIPS (lpj=17968651)

Mount-cache hash table entries: 512

CPU: L1 I cache: 32K, L1 D cache: 32K

CPU: L2 cache: 256K

CPU: L3 cache: 20480K

Checking 'hlt' instruction... OK.

Brought up 1 CPUs

migration_cost=0

Grant table initialized

NET: Registered protocol family 16

Brought up 1 CPUs

xen_mem: Initialising balloon driver.

VFS: Disk quotas dquot_6.5.1

Dquot-cache hash table entries: 1024 (order 0, 4096 bytes)

Initializing Cryptographic API

io scheduler noop registered

io scheduler anticipatory registered (default)

io scheduler deadline registered

io scheduler cfq registered

i8042.c: No controller found.

RAMDISK driver initialized: 16 RAM disks of 4096K size 1024 blocksize

Xen virtual console successfully installed as tty1

Event-channel device installed.

netfront: Initialising virtual ethernet driver.

mice: PS/2 mouse device common for all mice

md: md driver 0.90.3 MAX_MD_DEVS=256, MD_SB_DISKS=27

md: bitmap version 4.39

NET: Registered protocol family 2

IP route cache hash table entries: 32768 (order: 5, 131072 bytes)

TCP established hash table entries: 131072 (order: 8, 1048576 bytes)

TCP bind hash table entries: 65536 (order: 7, 524288 bytes)

TCP: Hash tables configured (established 131072 bind 65536)

TCP reno registered

TCP bic registered

NET: Registered protocol family 1

NET: Registered protocol family 17

NET: Registered protocol family 15

Using IPI No-Shortcut mode

netfront: device eth0 has copying receive path.

Registering block device major 8

XENBUS: Device with no driver: device/console/0

md: Autodetecting RAID arrays.

md: autorun ...

md: ... autorun DONE.

Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(8,1)
</code>
Please help me...struggling to fix this from last 4 days.
Answer: I was receiving this error because of selecting the wrong AKI id while launching the instance. As soon as i selected the correct id, this error disappeared and instance started working fine.