Music intervals graphic with TIKZ

Question: I am drawing a picture showing how to position segments for the natural music scale. My trigonometry lessons are long ago forgotten, so I apologize for this is going to be a very dummy question.
Consider the followintìg tikz picture. I need to place the segment re-D so that its measure will be 8/9 the measure of the segment ut-C. Now I just placed it at a random distance of 8/9 between ut and ut'.
What mathematical function should I use (sen, cos...???) and how do I write it down for tikz?
<code>\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}

\begin{tikzpicture}[scale=2]

\coordinate (o) at (0,0);
\coordinate [label=below:ut] (ut) at (2,0);
\coordinate [label=below:ut'] (ut') at (4,0);

\coordinate [label=above:C] (C) at (2, 2.4);
\coordinate [label=above:c] (c) at (4, 1.2);
\coordinate (O) at ($ (c)!2!(C) $);

\draw (ut) -- (ut');
\draw (ut) -- (C);
\draw (C) -- (c);
\draw (ut') -- (c);

\coordinate [label=below:re] (re) at ($ (ut)!8.0/9!(ut') $);

\coordinate [label=above:D] (D) at ($ (C)!8.0/9!(c) $);

\draw (re) --(D);

\node [fill=black, inner sep=1pt] (c') at ($ (ut)!1.0/6!(C) $) {};
\node [fill=black, inner sep=1pt] (c') at ($ (ut)!2.0/6!(C) $) {};
\node [fill=black, inner sep=1pt] (c') at ($ (ut)!3.0/6!(C) $) {};
\node [fill=black, inner sep=1pt] (c') at ($ (ut)!4.0/6!(C) $) {};
\node [fill=black, inner sep=1pt] (c') at ($ (ut)!5.0/6!(C) $) {};

\node [fill=black, inner sep=1pt] (c') at ($ (ut')!1.0/3!(c) $) {};
\node [fill=black, inner sep=1pt] (c') at ($ (ut')!2.0/3!(c) $) {};
\draw (ut') -- (c);

\end{tikzpicture}
\end{document}
</code>
Thank you,
A
Answer: If you are still interested, here is an answer to your question.
In the following code, I assumed that c is always half as high as C on the diagram. You may change the fraction for the position of D. Right now it is set at 8/9. No trigonometry was required. I removed the code defining the origin (o). It was not used in any way.
<code>\begin{tikzpicture}[scale=1]

\newlength{\height}\setlength{\height}{2.4cm}
\newlength{\width}\setlength{\width}{4cm}
\def\fraction{0.889} %8/9

\coordinate [label=below:ut] (ut) at (0,0);
\coordinate [label=below:ut'] (ut') at (\width,0);

\coordinate [label=above:C] (C) at ($(ut) + (0,\height)$);
\coordinate [label=above:c] (c) at ($(ut') + (0,0.5\height)$);

\draw (ut) -- (ut') -- (c) -- (C) -- cycle;

\draw let
  \p{C} = (C),
  \p{c} = (c),
  \n{y_D} = {\fraction*\y{C}},
  \n{x_D} = {\x{c}*2*(1-\fraction)}
  in
  (\n{x_D},\n{y_D}) coordinate[label=above:D] (D) -- (\n{x_D},0) coordinate[label=below:re] (re);
  %you could replace the previous line by
  %(\n{x_D},\n{y_D}) -- (\n{x_D},0);
  %because (D) and (re) aren't used later

\foreach \x in {1,...,5}{
\fill[black]  ($ (ut)!\x/6!(C) - (1pt,1pt)$) rectangle ++(2pt,2pt);
}
\foreach \x in {1,2}{
\fill[black]  ($ (ut')!\x/3!(c) - (1pt,1pt)$) rectangle ++(2pt,2pt);
}

\end{tikzpicture}
\end{document}
</code>
Comment: Thank you, I have finished this file months ago, but your solution looks fine to me.

Music intervals graphic with TIKZ


Material design CSS styling issue

Question: I have a hyperlink that opens a modal dialog:
{{Modal}}

The styling makes it appear as a button while I want it as a plain text. IF I remove class="waves-effect waves-light btn modal-trigger", the text disappear completely. Replacing it with a different class
.txt {
    color: white;
 }

did not work - text still disappears. Can anyone tell me why?
Comment: Did you try to just keep the `modal-trigger` class like this : `{{Modal}}` ?
Comment: Its not disappearing mate, do you have any styles which already exist for `` tags?
Comment: removing everything except `modal-trigger` did not work - it removed the text as well. On the contrary, removing `btn` part worked great. Now the only issue is extra spacing
Answer: Remove the waves-effect waves-light btn classes. This should leave you with:
{{Modal}}

This will remove the button styling and leave you with simple text that triggers your modal.
Comment: removing everything except `modal-trigger` did not work - it removed the text as well. On the contrary, removing `btn` part worked great. Now the only issue is extra spacing

Material design CSS styling issue


Why use a mixture model with RNN instead of just directly predictive real values?

Question: Alex Graves created a model to generate hand writing sequences which use an LSTM (kind of Recurrent Neural Network) to predict the parameters for an mixture model. The mixture model is then used to predict the next x,y coordinate and whether the pen is up or down.
Generating Sequences With Recurrent Neural Networks
Demo of the above
Why not just use the LSTM to directly predict the pen offsets (x,Y) and up/down flag.  Why bother with the mixture model?
Comment: you could send an email and ask Alex  I really don't know the answer.  If I were doing this, I would use a mixture model if there multiple modes.  In character recognition each character is a single mode.  All lower-case "c" letters belong in the same stack.
Comment: I changed the title from "Why does Alex Graves use a mixture model with his RNN instead of just directly predictive real values?" In principle, there is  nothing to stop Alex Graves answering the question himself, but particularly after 2 years of being posted, the more general question in the revised title seems more suitable for CV. (I have no idea what the answer is!)
Comment: Do we have an answer yet? Or has anyone tried to remove the mixture model?
Answer: I am very new in the area so please take my comments with care !
I saw a lecture from Alex in this youtube channel https://www.youtube.com/channel/UC0z_jCi0XWqI8awUuQRFnyw
In this video, the first objective of Alex was to build a simulation model. Therefore, I think that the output of the model which is searched for is a random variable.
With this, every time you ask the model a simulation, you will have different results (unless you set the variance to 0 as he does in the end of the presentation under the "biases samples").
I also think that if you do have direct output (such as actually telling move the pen right 10 pixels), since in the structure (both inputs and NN structure) there is no stochastic components you could end with the same results in all cases.


nginx rewrite not working?? it simply ignores it

Question: i have a wierd problem with nginx, it doesn't want to rewrite...
I have this configuration and i need to pass a hash (40 chars) to a php file
it works with apache mod_rewrite but with nginx it isn't
i even tried to do simple rewrites, it simply doesn't work
server {
.........
        location / {
            rewrite ^aa$ /downloadTORRENTZ.php break;
            root   /usr/share/nginx/html;
            index  index.html index.htm;
            rewrite  "^([A-Z0-9]{40})$" /file.php?ddl=$1 break;
        }
}

Comment: From @staafl: What OS are you using? I'm sorry for not commenting, but I don't have the rep.
Answer:
Remove "" from your regexp
request usually start with / so your regexp should look like
rewrite  ^/([A-Z0-9]{40})$ /file.php?ddl=$1 break;
Is your hash ALLCAPS? Maybe you should use [a-zA-Z0-9]
40 characters... It looks like sha1 hash. May be you should simplify regexp to [0-9A-F]
Comment: Yep, was missing a preceding `/`


Centos BIND server: Unable to start named daemon

Question: I've installed a fresh Centos server and installed bind and bind-utils to it.
The content of /etc/named.conf is:
# create new
 options {
    directory "/var/named";
    allow-query { localhost; 10.1.2.0/24; };
    allow-transfer { localhost; 10.1.2.0/24; };
    recursion yes;
};
controls {
    inet 127.0.0.1 allow { localhost; } keys { rndckey; };
};
view "internal" {
    match-clients {
        localhost;
        10.1.2.0/24;
    };
    zone "." IN {
        type hint;
        file "named.ca";
    };
    zone "amadeus.netvision" IN {
        type master;
        file "amadeus.netvision.lan";
        allow-update { none; };
    };
    zone "0.0.10.in-addr.arpa" IN {
        type master;
        file "0.0.10.db";
        allow-update { none; };
    };
    zone "localdomain" IN {
        type master;
        file "localdomain.zone";
        allow-update { none; };
    };
    zone "localhost" IN {
        type master;
        file "localhost.zone";
        allow-update { none; };
    };
    zone "0.0.127.in-addr.arpa" IN {
        type master;
        file "named.local";
        allow-update { none; };
    };
    zone "255.in-addr.arpa" IN {
        type master;
        file "named.broadcast";
        allow-update { none; };
    };
    zone "0.in-addr.arpa" IN {
        type master;
        file "named.zero";
        allow-update { none; };
    };
};
view "external" {
    match-clients { any; };
    allow-query { any; };
    recursion no;
    zone "amadeus.netvision" IN {
        type master;
        file "amadeus.netvision.wan";
        allow-update { none; };
    };
};
include "/etc/rndc.key";

# allow-query ⇒ query range you permit
# allow-transfer ⇒ the range you permit to transfer zone info
# recursion ⇒ allow or not to search recursively
# view "internal" { *** }; ⇒ write for internal definition
# view "external" { *** }; ⇒ write for external definition
# For How to write for reverse resolving, Write network address reversely like below.
# 10.1.2.0/24
# network address⇒ 10.1.2.0
# range of network⇒ 10.1.2.0 - 10.0.0.255
# how to write⇒ 0.0.10.in-addr.arpa
# 172.16.0.80/29
# network address⇒ 172.16.0.80
# range of network⇒ 172.16.0.80 - 172.16.0.87
# how to write⇒ 184.108.40.206.in-addr.arpa

When I try to start the named daemon i get the following error:
[root@srv ~]# service named restart
Stopping named:                                            [  OK  ]
Starting named:
Error in named configuration:
/etc/named.conf:9: unknown key 'rndckey'
                                                           [FAILED]
[root@srv ~]#

I don't understand what I'm doing wrong, I've created the rndc.key using the next command:
rndc-confgen -a -c /etc/rndc.key and it created the key but I still get the same error.
The file is present in the correct path: /etc/rndc.key and it's included in the /etc/named.conf file.
Comment: I bet it's an ordering issue.  Try moving the `include "/etc/rndc.key";` line to the top of the file.  I think that at the time you're trying to reference the key it has been defined yet.
Comment: What does /etc/rndc.key look like? (you may want to blank out the secret)
Answer: I just experienced the above symptom.
While my case was slightly different and this isn't the exact answer to the above question, hopefully this might help someone out...
In my case I had specified the key inside of the options block which is incorrect.
The key statement must be defined outside of any other statement (like the options statement block) in the named.conf config file.
ie the following is incorrect:
options {
    ...
    include "/etc/rndc.key";
};

The following is correct:
options {
    ...
};
include "/etc/rndc.key";

Answer: Check the file /etc/rndc.key and see which is the name of the key. For example:
key "rndc-key" {

This name should be be specified in named.conf
keys { rndc-key; };

Comment: Do I have to create zone files or are they created automatically?
Comment: For localhost they may be installed with bind but for your domain you have to create zone files.


A stationary process defined by a really weird stochastic integral.

Question: A post here: Distribution of integral with respect to Brownian motion described a really weird stationary process.
Let us make it simpler, by only considering for $n\in\mathbb{Z}$, $$X_{n}:=\int_{0}^{2\pi}\cos(nx)Z(dx),$$ where the orthogonal stochastic measure $Z(dx)$ as described in the post has the property $$\mathbb{E}Z=0\ \text{and}\ Var(Z(dx))=\rho(dx)=dx,$$ where $\rho$ is the structure measure of $Z$, which coincides with the spectral measure of $X_{n}$.
Then, following the post, I tried to compute the variance function, covariance function, mean, etc.
For the mean, recall that $\mathbb{E}[Z(d\lambda)]=0$, so we have $$\mathbb{E}X_{n}=\mathbb{E}\Big(\int_{0}^{2\pi}\cos(n\lambda)Z(d\lambda)\Big)=\int_{0}^{2\pi}\cos(n\lambda)\mathbb{E}[Z(d\lambda)]=0.$$

However, the covariance function is really weird. Below is my computation:
\begin{align*}
\mathbb{E}(X_{n}\overline{X_{n+k}})&=\int_{0}^{2\pi}\cos(n\lambda_{1})\cos((n+k)\lambda_{2})\mathbb{E}[Z(d\lambda_{1})\overline{Z(d\lambda_{2})}]\\
&=\int_{0}^{2\pi}\cos(n\lambda)\cos[(n+k)\lambda]d\lambda\\
&=\dfrac{1}{2}\dfrac{\sin[2\pi(k+2n)]}{k+2n}+\dfrac{1}{2}\dfrac{\sin(2\pi k)}{k}.
\end{align*}
The final answer can be easily computed using WolframAlpha.
So, the covariance function depends not only on $k$ but also on $n$ ???? Then the process cannot be stationary.. right?

To verify my computation, I changed a way to compute it by using Herglotz Theorem: $$c(n)=\int_{0}^{2\pi}e^{in\lambda}\rho(d\lambda),$$ but $\rho(d\lambda)=d\lambda$, so that for $n>0$, $$c(n)=\int_{0}^{2\pi}e^{in\lambda}d\lambda=\int_{0}^{2\pi}\cos(n\lambda)d\lambda+i\int_{0}^{2\pi}\sin(n\lambda)d\lambda=\dfrac{\sin(2\pi n)}{n}+i\dfrac{2\sin^{2}(\pi n)}{n}.$$
This times, $c(n)$ depends on $n$ but we create some complex number...Also, you can see that the case has to be discussed differently if $n=0$, or $n<0$.

So the process is complex-valued?? What is the exactly this process? I am really confused....
Thank you!
Answer:
So, the covariance function depends not only on k but also on n ???? Then the process cannot be stationary.. right?

Note that $\sin 2\pi m = 0$ for integer $m$, so
$$
\mathbb{E}(X_{n}\overline{X_{n+k}}) = 0, k\neq 0,
$$
and
$$
\mathbb{E}(|X_{n}|^2) = \pi.
$$
Therefore, the process is (wide-sense) stationary.

So the process is complex-valued?

The answer depends on whether your $Z$ is complex-valued or not (which is not completely clear from your question).
Comment: oh. By the way, is there any further description you could give for $X_{n}$? say, distribution, etc?
Comment: I'd like to describe $X_{n}$ as much as possible.
Comment: I agree with everything you said, but a weird thing is that $$\mathbb{E}|X_{0}|^{2}=\int_{0}^{2\pi}d\lambda=2\pi,$$ seems not consistent with our computation.
Comment: @JacobsonRadical, you are right, $X_0$ should be divided by $\sqrt{2}$. Concerning the distribution, it depends on that of $Z$. Say, if $Z$ is Gaussian, then $X$ is too.
Comment: Concerning the distribution, since we have $Z$ is Gaussian, then $X$ is also Gaussian, but each $X_{n}$ is uncorrelated and thus independent. But we know that for $n\neq 0$, we have $0$ mean and $\pi$ variance, so this is a Gaussian process with i.i.d components? but $X_{0}$ is differently distributed?
Comment: About $X_{0}$. The formula we computed gives the covariance function $c(s,t)=0$ if $s-t\neq 0$ and $c(s,t)=\pi$ if $s-t=0$. But then $c(s,t)\neq c(s-t)$, since $Cov(X_{0}, X_{0}=2\pi$... I am wondering this since my definition of wide-sense stationary needs me to have $c(s,t)=c(s-t)$. I understand it is enough to show $c(s,t)$ is a function of $s-t$. But the $X_{0}$ case really worries me.....
Comment: I am sorry. let me first accept your answer and reward the points. I cleared out my mind and saw why I had confusion. The computation for $k=0$ is $$\mathbb{E}(X_{n}\overline{X_{n}})=\mathbb{E}(|X_{n}|^{2})=Var(X_{n})=\int_{0}^{2\pi}\cos^{2}(n\lambda)d\lambda=\dfrac{\sin(4\pi n)}{4n}+\pi=\pi,$$ but note that the denominator has $n$, so we also need to require $n\neq 0$. Thus, we actually have three cases. $k\neq 0$, $k=0,n=0$, and $k=0,n\neq 0$. But then the covariance function also depends on $s$ and $t$, not only on $s-t$.
Comment: The situation with $X_0$ is this: under the link, there is $e^{in\lambda}$, and $B$ is complex-valued, so the imaginary part also contributes to the variance, which gives the same variance for $X_0$ (where $\sin = 0$). Here, you have only $\cos$, so one needs to take account of this.
Comment: Yes. You are correct. Thank you so much!


How does using a correlated topic model effect the distribution of topics?

Question: Correlated Topic Models are a great advance on the original topic model - see Blei and Lafferty 2007 for more info.
My question is this - how does a Correlated Topic Model impact the overall distribution of topics across all documents when compared with a normal topic model? With a normal topic model (with a symmetric Dirichlet prior) the distribution of topics can be remarkably uniform, which is not always appropriate. As discussed by Wallach et al. having asymmetric priors is key to having better model fit and interpretability - it would be great if the Correlated Topic Model implicitly addressed this issue by creating a topic distribution which is less uniform.
Answer: In normal topic models (i.e. Latent Dirichlet Allocation), for document $d$, we draw a topic proportion $\theta_d$ from $Dir(\alpha)$, although $\theta_d$ is a vector sums to one, each element in $\theta_{d}$ is quite independent. As a result, a word's probability of being assigned to different topics are almost independent. (This is a big drawback, intuitively, if a word has a high probability of being assigned to the "baseball" topic, then we expect it should also have a high probability of being assigned to the "sports" topic, as those two topics are correlated.)
Correlated Topic Models addresses this by drawing $\theta_d$ from a multivariate Gaussian distribution, then each element of $\theta_d$ is correlated to each other by the covariance matrix. Of course, in Gaussian distribution, there is no guarantee that $\theta_d$ will sum to 1, so CTM also normalizes it.
I would not worry about symmetry in CTM, as each topic entangles with other topics in its own ways.


Closed form of series $z^n/n$.

Question: Let $z\in\mathbb{C}$. In other question is answered precisely where $\sum\limits_{n=1}^{\infty} \frac{z^n}{n}$ converges.
I have been looking for an expression of
$$\sum\limits_{n=1}^{\infty} \frac{z^n}{n}$$
without infinite sum. I mean, a closed expression of this simple hypergeometric sum, similar to, for example,
$$\forall |z|<1 , \ \sum\limits_{n=1}^{\infty} z^n = \frac{1}{1-z}.$$
Is there any closed form of the hypergeometric series $z^n/n$?
Answer: The sum is $-\log(1-z)$, where $\log$ is the main logarithm.
Comment: Integrate both sides of the equality$$\frac1{1-z}=1+z+z^2+z^3+\cdots$$and you get that$$-\log(1-z)=z+\frac{z^2}2+\frac{z^3}3+\frac{z^4}4+\cdots$$
Comment: Can you please explain why or give some reference?
Comment: Consider the function $z\mapsto-\log(1-z)$. Obviosuly, it maps $0$ into $0$. And if you differentiate it, you get $\frac1{1-z}=1+z+z^2+z^3+\cdots$.

Closed form of series $z^n/n$.


Alternar Classes CSS

Question: Agora venho com outra dúvida pois sou iniciante em javascript.
Bom, tenho essa função que quando se clica na aba tarefas cadastradas aparece uma div com um select(combobox).
Como eu faço para quando eu clicar em tarefas recebidas a div desapareça novamente. Ela só desaparece quando eu clico novamente em tarefas cadastradas.
Pode até ser bem básico mas estou ainda engatinhando em js.
Quem puder ajudar agradeço.

window.onload = function(){
var div = document.querySelector('div#minhaDiv');
var section = document.querySelector('section#secao');

section.addEventListener('click', function() {
    var aberto = div.classList.contains('teste');
    div.classList.toggle('teste2');
});
}
.teste {
    display: none;
}

.teste2 {
    display: block;
}

    Filtro busca2:
    <select name="" onchange="" id="">
        <option value="0">...</option>
        <option value="1">Prazo decrescente</option>
        <option value="2">Prazo crescente</option>
        <option value="3">Título A - Z</option>
        <option value="4">Título Z - A</option>
    </select>

        Tarefas Realizadas

                    A Tarefa
                    Funcionário
                    Setor
                    Status
                    Prazo
                    Nível Urgência
                    Dia Fechamento
                    Editar
                    Excluir

        Tarefas Cadastradas

                    A Tarefa
                    Funcionário
                    Setor
                    Status
                    Prazo
                    Nível Urgência
                    Dia Fechamento
                    Editar
                    Excluir

Answer: Boa tarde Lucas, abaixo uma forma de desaparecer com a DIV quando clicar em Tarefas Realizadas, é basicamente o mesmo código, o método toggle recebe como parâmetro true/false para exibir ou não.

window.onload = function(){
  var div = document.querySelector('div#minhaDiv');

  var secao = document.querySelector('section#secao');
  var title = document.querySelector('section#secTitle');

  secao.addEventListener('click', function() {
      div.classList.toggle('teste2', true);
      div.classList.toggle('teste', false);
  });

  title.addEventListener('click', function() {
      div.classList.toggle('teste2', false);
      div.classList.toggle('teste', true);
  });
}
.teste {
    display: none;
}

.teste2 {
    display: block;
}

    Filtro busca2:
    <select name="" onchange="" id="">
        <option value="0">...</option>
        <option value="1">Prazo decrescente</option>
        <option value="2">Prazo crescente</option>
        <option value="3">Título A - Z</option>
        <option value="4">Título Z - A</option>
    </select>

        Tarefas Realizadas

                    A Tarefa
                    Funcionário
                    Setor
                    Status
                    Prazo
                    Nível Urgência
                    Dia Fechamento
                    Editar
                    Excluir

        Tarefas Cadastradas

                    A Tarefa
                    Funcionário
                    Setor
                    Status
                    Prazo
                    Nível Urgência
                    Dia Fechamento
                    Editar
                    Excluir

Comment: Muito Obrigado pela solução! @Daniel Mendes.

Alternar Classes CSS


Calculate new average from two other averages with its respective totals/counts

Question: I have the next film named Blade Runner and it has two version (director cut and theatrical cut) and I rate the director cut with a 7 and the theatrical cut with a 8, so the average would be:
(7 + 8) / 2 = 7.5
I have another average of all films (the 7 and 8 scores are of blade runner, the 9 and 10 scores are from other films) as below:
(7 + 8 + 9 + 10) / 4 = 8.5
Knowing ONLY the total of scores (2) and the average (7.5) (without the scores) of Blade Runner, I want remove it of the average of films (Also, knowing only its total scores (4) and average (8.5) of all films). Is Possible do it? Or I need to know the scores of all films to calculate the new average?
Comment: So you want to know what the average is without the effect of the Blade Runner scores? If so, you need to also know how many Blade Runner versions are in there (actually there are five versions :P)
Answer: Yes, I think it's possible based on my understanding of your question:
$$
\text{New average} = \frac{\underbrace{8.5 \times 4}_{\text{sum of all ratings}} - \underbrace{7.5 \times 2}_{\text{sum of Blade runner ratings}}}{\underbrace{4-2}_{\text{number of films without Blade Runner}}} = 9.5
$$
Comment: Thanks you very much!! It's just what I wanted! :D


binary back to List

Question: I have written a list of values to a binary file using the binary writer.
I was wondering if someone could show me how I could extract the list of int16 values back from this binary file?
Thanks in advance
using (var file = File.Create(fileName))
using (view.IncidentWriter = new BinaryWriter(file))
{
    foreach (short dataItem in view.Data)
    {
        view.IncidentWriter.Write(dataItem);
    }
}

Comment: How **exactly** did you write them? any preamble such as item count?
Comment: using the following, I edited above post to include the way it was written
Answer: The binary reader is binary writer's friend, you can make it yours
Answer: The easiest way to do this is to prefix the data with the expected count:
        var list = new List<short>{1,2,3,4,5};
        using (var file = File.Create("my.data"))
        using (var writer = new BinaryWriter(file))
        {
            writer.Write(list.Count);
            foreach(var item in list) writer.Write(item);
        }

        using (var file = File.OpenRead("my.data"))
        using (var reader = new BinaryReader(file))
        {
            int count = reader.ReadInt32();
            list = new List<short>(count);
            for (int i = 0; i < count; i++)
                list.Add(reader.ReadInt16());
        }

Otherwise, you have to detect EOF, which is easy enough with a Stream, but a pain with a BinaryReader.

binary back to List


Write "true"/"false" to an INI file based on task selection in Inno Setup

Question: In the [Tasks] section I have:
[Tasks]
Name: "userexpericeneimprovement"; \
    Description: "{cm:JoinUserExpericeneImprovement}"; \
    GroupDescription: "{cm:AdditionalIcons}"; MinVersion: 0.0,5.0;

and in [INI] is this specific command:
[INI]
FileName: "{app}\ceip.ini"; Section: "General"; Key: "enabled"; \
    String: "{code:GetUserJoin}";

My aim is to check the selected task and then the [Code] {code:GetUserJoin} part will do the filling in the ceip.ini file as "true" or "false" whichever is checked or unchecked.
Answer: This is trivial enough to be implemented even without any Pascal Script with use of Tasks parameter:
[INI]
FileName: "{app}\ceip.ini"; Section: "General"; Key: "enabled"; String: "true"; \
    Tasks: userexpericeneimprovement
FileName: "{app}\ceip.ini"; Section: "General"; Key: "enabled"; String: "false"; \
    Tasks: not userexpericeneimprovement

If you want to use the Pascal Script, the implementation is also trivial with use of WizardIsTaskSelected function:
[INI]
FileName: "{app}\ceip.ini"; Section: "General"; Key: "enabled"; \
    String: "{code:GetUserJoin}";

[Code]
function GetUserJoin(Param: string): string;
begin
  if WizardIsTaskSelected('userexpericeneimprovement') then Result := 'true'
    else Result := 'false';
end;

Comment: thank you very much! i have run this code successfully...  you are so enthusiastic and kind!...


What does an NFL salary cap department do?

Question: I sometimes hear about NFL GMs being "cap experts" rather than player-evaluators. And I just saw this headline: "John Idzik joining Jags as consultant". The article goes on to say, "Idzik, who was fired by the Jets in late December, will not have a role in player evaluation but will work with the team's salary-cap department, the source said" (emphasis mine). Sure the salary cap rules aren't simple, but how do they justify an entire department?
Answer: This interview by FiveThirtyEight of Paraag Marathe, the 49ers' cap specialist, states:

We've got four or five folks, whether helping scouts better evaluate players, helping coaches, as well as the salary cap.

Basically, the "salary cap department" is code for "analytics".  Not only are they working on actual salary cap issues - which is undoubtedly more than one person's full time job, for the same reason as even a small company needs a full time accountant; keeping in compliance with every small detail is important - but they're doing other similar analytic tasks, such as analyzing player performance, finding players who fit their cap space and also are predicted by their statistical models as good candidates, etc.


Eight distinct integer values between $1$ and $8$ satisfy six simple conditions ($D+E=F$, etc). Find which value is which.

Question:
I have 8 variables; $A$, $B$, $C$, $D$, $E$, $F$, $G$, and $H$.
What are they all equal to?
Rules:

All the variables are equal to integer values between one and eight.

None of the variables are equal to each other.

$D + E = F$

$B + C = D$

$B + H = A$

$C + G = F$

$E + G = H$

$B + E = G$

I know that $1$ and $2$ both must be either $B$, $C$, or $E$ since there is no $0$ so $1$ must be a letter that does not have an equation answer. For $2$ I know that there is no equation that is the a variable plus itself.
Comment: @RedGuy11: You should [edit the question](https://math.stackexchange.com/posts/3358449/edit) to include what you know (and how you know it!). Comments are easily overlooked, so your question could accumulate down-votes and close-votes for not demonstrating any effort on your part. (The community is here to *help* you, and it likes some assurance that you aren't simply trying to get them to do your homework for you. Plus, including your own thoughts saves people from wasting time (theirs or yours) telling you things you already know.)
Comment: What have you tried so far?
Comment: Is this your homework?
Comment: "*I know B C or F have to be 1*"  But $D+E=F$.  Remembering that $D\geq 1$ and $E\geq 1$ and $D\neq E$ and that these are integers implies that $F\geq 3$.  You probably meant "B, C, or E" instead.
Comment: This doesn't seem related to random variables, but more along the lines of linear algebra.
Comment: I can't think of how to start...
Comment: I know b c or f have to be 1
Comment: Did you try to use Gaussian elimination?
Comment: This is a **puzzle**. You are not supposed to start working according to some standard textbook method.
Answer: As given in the post ${B,C,E}$ contains the numbers $1$ and $2$. Similarly ${A,F}$ contains 8.
The equations give $A=2(B+E),H=B+2E,G=B+E$. $A$ must therefore be either $6$ or $8$.
If $A=6$, then $B=1,E=2, F=8,G=3,H=5$ or $B=2,E=1,G=3,F=8,H=4$.
If $A=8$, then $B=1,C=2,E=3,G=4,H=7$ or $B=3,C=2,E=1,G=4,H=5$.

The actual solution is $A=6,B=2,C=5,D=7,E=1,F=8,G=3,H=4$.
Answer: Some hints:
Since $8$ cannot occur on the left hand side of an equation, we know that either $A=8$ or $F=8$.
From equations $1$ and $2$ we know that $B+C+E=F$. So $F=6,7$ or $8$.
From equations $5,7,8$ we know that $A=B+H = B+E+G=2G$. Since $G \ge 3$ we have either $G=3, A=6$ or $G=4, A=8$.
Suppose $G=3$. Then $A=6$ and so $F=8$. From equation $8$ we know that $B$ and $E$ are $1$ and $2$ (either way round), so $C=5$ (because $B+C+E=F=8$). Since $E+G=H$ we know that $E$ cannot be $2$ (otherwise $H=C=5$) so $E=1$ and $B=2$.
This should be enough for you to find one solution.
You should also consider the case "Suppose $G=4$ ..." to see if there are any other solutions.
Comment: @RedGuy11 Why ? There is nothing in our answering guidelines about posting hints as comments, and my hints were too long to put into a comment. You said "I can't think of how to start" so I suggested an approach.


How many bars can a clarinet sustain?

Question: Apologies if the question is too silly (my profile might explain why I don't know the answer).
I am writing a piece and at some point I want a clarinet to hold a note until the performer runs out of air (diminuendo). Now, how many bars is it reasonable to ask in the score?
I write music mainly for my own enjoyment and the computer (Sibelius) plays it for me. It seem to be that Sibelius can hold a clarinet note indefinitely, but I prefer if the scores I write are actually playable.
Moreover, what is the right thing to write on the score? A text saying 'play until run out of air' and have the corresponding diminuendo? Since I don't know how many bars is too much I am not sure where to end the diminuendo sign and to put the ppp.
Thank you.
Comment: Actually playing till you run out of air is not good, your sound goes all tacky towards the end.
Comment: @RedSonja Why was the clarinet designed like that?
Comment: Ah, you need to learn to play a reed instrument to understand. The clarinet is the way it is so it will have the sexiest sound on the planet (when played correctly). I may be prejudiced.
Answer: My response will be in part influenced by the information I gathered from reading your profile.
My first suggestion to you is to strongly encourage you to learn an instrument.  If you're serious about writing music and about having it played by live performers, having a working knowledge of the instruments is important.  It is paramount to be technically proficient on at least 1 instrument in order to understand how sound is produced and general performance characteristics.
Before I answer your question, I want to clarify that the term diminuendo also known as decrescendo means to gradually decrease in volume, not to "hold until you run out of air."  In considering the answer to your question, there are many variables to consider:

The proficiency of the performer (professional / college / high school / etc.  different levels will be able to provide different amounts of breath support.)
The range you are asking the performer to play in.
The tempo of the music.
The dynamic of the pitch in question.
The time signature being used.
The context of the note (whether it is the held note at the
beginning / end of a phrase or if it is stand-alone, etc.)
Whether or not the performer can circular breathe.

As you can see, it is impossible to give a simple answer to this question, as the length is contingent upon the variables I outlined above.  Sibelius will be able to hold the note indefinitely because it is a computer and therefore does not need to breathe.
Having a dynamic of "ppp" is different than having the performer physically play until they run out of air - the composer will find different sounds for each of these.
I believe your real question is something to the effect of "what is the clearest way to notate a performer holding a note until they run out of breath?"  To which my simple answer would be: it depends on the context of the piece.
That said, in a general sense, a clear way to notate that would be to have a fermata over the note in question with a diminuendo ending not in a dynamic, but with "n" which stands for "nothing."  You could also put a note above the staff saying "fade until nothing" in which case the performer would automatically adjust as necessary.
Hope that helps.
Comment: @RedSonja Yes, you can circular breath on almost any instrument.  Haven't tried flute personally, but I could imagine it would be very difficult.  Clarinet definitely works.
Comment: @RedSonja circular breathing on a piano haha
Comment: Thank you very much! I learned from you about circular breathing. Didn't know that was possible. I just read the Wikipedia article. And the, probably useful, notation "n". Haven't learned that one before.
Comment: About learning an instrument. I imagine piano and violin are the typical, but I am very very old to learn any of these. Is there some other instrument that is relatively simpler to learn and that is also meaningful for composing music. I could write this in a separate question to have more space for a response. Well, I am doing it.
Comment: Not a problem Franklin VP - glad to help.  I posted an answer to your other question that I hope you find helpful.  Cheers.
Comment: Yes, depends very much on the player. A profi can hold a note much longer. I am no profi, but since I started playing bari sax I can play the clarinet for whole lines without taking a breath, much to the astonishment of the flutes.
Comment: Can you do circular breathing on a clarinet? ! I have seen trumpets do it, but had no idea I could try this too. This evening I shall try it.
Answer: With a fast enough tempo, it could be quite a few! :-)
Necessarily, you would need to time it out at your score's tempo to find a number, but the clarinet in general has a lot of resistance compared to other wind instruments, so the amount of airflow is relatively small.
Depending on the range of the instrument in which this note occurs, a good clarinetist that's prepared for it could probably sustain 30 seconds or more, but it is more difficult to achieve a measured decrescendo while doing the same thing.
That said, I wouldn't notate this with a set number of bars. I would have the bar with the sustained clarinet repeat, tying the note in the bar to itself, OR use a fermata symbol without repeats. I would also include a written instruction to hold for as long as possible and decresc. to silence, or al niente.
You could notate the dynamic either with a written decresc. al niente or the regular decrescendo hairpin with an italic lowercase n at the right side point.
Comment: Well met NReilingh, it appears we have the same thinking.
Comment: Right. I forgot to say the tempo. Right now the metronome mark is an eigth-note=100 (I don't know how to say that properly).
Answer: I can generally hold a note for 16 counts at quarter note = 60. It leaves me huffing though. I've known other players who can do more and most young players can do far less.
Comment: Yes. And in this case it also means seconds :)
Comment: Count means beat?
Answer: There is a technique known as circular breathing ( do a google search ) that in principle allows a clarinet player to sustain a note indefinitely.
example: https://www.bing.com/videos/search?q=clarinet+round+breathing&view=detail&mid=95E560FB96E1939AD71495E560FB96E1939AD714&FORM=VIRE
Answer: The clarinet can technically hold for ever/a very long time, you just need enough breath to sustain the note. There is no barrier that cuts off the note after 20 counts, and no reason that if it can hold for 17 beats that it can't hold 170.
Comment: This is like saying "there's no reason people can't step over the English Channel, they just need to have long enough legs."

How many bars can a clarinet sustain?


Elegant way to prove that the space must be infinite dimensional?

Question:
Let $F(S,V)$ be the set of all functions from S to a vector space V,
  assume that $V\ne\{0\}$, and that S contains infinitely many elements, then we must have that $F(S,V)$ is infinite-dimensional.

Is there an easy way to prove this? In order to show this I had to do a lot of work, first reduce the problem to the case where S is countable, and then consider some functions on the countable space etc.. It seems like such a simple fact that there should be a very simple proof?
Answer: Let $y_0$ be some nonzero element of $V$. Take a sequence of elements of $S$, call it $x_i$. Let $e_i(x)=y_0$ if $x=x_i$ and $0$ otherwise. Prove that the $e_i$ for $i=1\dots,n$ are linearly independent and yet do not span $F(S,V)$.
Comment: +1.  I think it might be (very slightly) tidier not to introduce the sequence.  Just define $e_s$ for each $s\in S$; then $\{e_s : s\in S\}$ is linearly independent, so $\dim F(S,V)\ge\operatorname{card} S$.  Introducing the sequence may prompt foundational questions (can we choose a sequence from any infinite set?  does this need the axiom of choice?)  which, though interesting, obscure the matter at hand.
Comment: You should replace $1$ with a nontrivial element from $V$.
Comment: @Dominik Thanks.


Resolve Function in Overloading

Question: The case is I have the following class, for example:
public class SendFile
{
     public SendFile(Uri uri) { /* some code here */ }
     public SendFile(string id) { /* some code here */ }
}

Then, We know that if I want to resolve the constructor, I can't do it likes the following:
// some string defined which are called "address" and "id"
var sendFile = new SendFile(String.IsNullOrEmpty(address) ? id : new Uri(address));

My question is How can I resolve this issue in a clean way, without creating an "if" branch in the code? likes the following:
SendFile sendFile;
if(String.IsNullOrEmpty(address))
{
     sendFile = new SendFile(id);
}
else
{
     sendFile = new SendFile(new Uri(address));
}

Answer: In your version above you get the compilation error of:

Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.Uri'

When reading MSDN documentation it states:

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

As string and Uri do not have an implicit conversion between each other (which you also do not want as if you did why have two different constructors..),
to use the conditional operator you should do it a bit differently:
var sendFile = String.IsNullOrEmpty(address) ? new SendFile(id) :
                                               new SendFile(new Uri(address));

Comment: I really needed to fix the compilation error:
`var sendFile = new SendFile(String.IsNullOrEmpty(address) ? (dynamic)id : new Uri(address));`. But really, DON'T use this :) Gilad proposed a way cleaner solution.
Answer: One option might be to add a static 'factory' method to SendFile and take care of it there:
public class SendFile
{
    public SendFile(Uri uri) { /* some code here */ }
    public SendFile(string id) { /* some code here */ }

    public static SendFile Create(string url, string fallbackId = null)
    {
        return string.IsNullOrEmpty(url)
            ? new SendFile(fallbackId)
            : new SendFile(new Uri(url));
    }
}

The parameter naming should make clear that fallbackId is only used if url is not provided.
Comment: See link about [Factory Method](http://www.dofactory.com/net/factory-method-design-pattern) design pattern

Resolve Function in Overloading


How to make JFileChooser open showing current working dirctory irrespective of Operating System used?

Question: I need to use a JFileChooser in my simple Quiz game to load and save 'Question /Answer' sets ,
when the FileChooser window opens i want it to be in the current working directory, i want this to work in Linux,Windows and OSX, i am doubtful if the "user.dir" mehtod works in all platforms , Can someone help out , Code Below...
For loading
public class openMenuItemListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
nextButton.setEnabled(true);
JFileChooser fileChooser=new JFileChooser();
fileChooser.showOpenDialog(frame);
loadFile(fileChooser.getSelectedFile());
}
}

For Saving:
class saveMenuListener implements ActionListener
    {
    public void actionPerformed(ActionEvent e)
    {
    JFileChooser fileSave=new JFileChooser();
    fileSave.showSaveDialog(frame);
    saveFile(fileSave.getSelectedFile());

    }
    }//class ends

Comment: *"I need to use a JFileChooser in my simple Quiz game to load and save 'Question /Answer' sets , when the FileChooser window opens i want it to be in the current working directory, i want this to work in Linux,Windows and OSX, i am doubtful if the "user.dir" mehtod works in all platforms"*  It won't *ever* work for *any* OS for *any* application launched using Java Web Start, which would be the usual way that desktop apps. are distributed.  In those apps. the directory of the app. (where it is installed) is deliberately hidden from the app. itself.  ..
Comment: .. What form exactly are these quizzes stored in (text, HTML, serialized `String` objects..)?
Comment: *"its working now thanks"*  It's easy enough to get many things working on a single development machine.  It is at time of deployment to anyone else that you'll then need to deal with problems like I was describing.  But then, why is the app. offering a `JFileChooser` as opposed to simply a `JList` of available quizzes?  Do you supply all the quizzes, or can the end user design new ones?
Comment: @AndrewThompson I have two applicatios, a quiz builder to build a quiz ,save as text file ,  then load and play it from a quizplayer , its just a toy application I'm using as I'm learning java io,nothing much
Comment: @AndrewThompson I think you are mislead, i dont have any installers ,.jar files , web deployement etc , no need to access folders etc, i have just 2 .java Files which i run from the terminal ,Its that Simple!,Anyway thanks for the useful Hints
Answer: This gets you a `JFileChooser' referencing the current working directory (i.e. application startup location) on any system:
new JFileChooser(".");


Cannot setCurrentItem(0) on CirclePageIndicator

Question: If you have this code in Activity onCreate():
mViewPager = new ViewPager(this, null);
mPagerAdapter = new PagerAdapter(this);
mViewPager.setAdapter(mPagerAdapter);
mCirclePageIndicator.setViewPager(mViewPager);
mCirclePageIndicator.setOnPageChangeListener(onPageChangeListener);

Then launch an AsyncTask and want to change the current page in it's onPostExecute() with the page 0, then it won't work. It works with any other page != 0, but with 0 it just retains the current position.
mCirclePageIndicator.setCurrentItem(0);

If anybody comes up with an idea, feel free to share. Thanks !
Answer: Workaround:
First set another page as the current page, then set to page 0. Yes, I know, it's retarded, but I still haven't found an explication as to why it isn't working in the first place. I've tried posting it in a Handler, even with a delay, but nothing. Nada.
mCirclePageIndicator.setCurrentItem(1);
mCirclePageIndicator.setCurrentItem(0);

Comment: I would assume its because the indicator assumes its at page 0 to start with.
Comment: After adding new items in the adapter and also changing the position on screen ? Don't think so...
Comment: Really cool you got this working.  I've been trying to figure it out for a while now.  Would be interesting to understand the mechanics a bit more.
Answer: i found out that the CirclePageIndicator.java has a bug, it did not want to fill the selected page circle when i first start my Fragment, but when i just touch my ViewPager, every thing is ok ... the bug was there :
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    mCurrentPage = position;
    mPageOffset = positionOffset; // error here
    invalidate();

    if (mListener != null) {
        mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
    }
}

the positionOffset returned Nan when i initialized my views in onCreate, which caused onDraw() not to draw the filling of my selected circle
the solution is to check for the positionOffset value before assigning it, like :
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    mCurrentPage = position;
    mPageOffset = (positionOffset > 0) ? positionOffset : 0;
    invalidate();

    if (mListener != null) {
        mListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
    }
}

Answer: What worked for me is setting indicator.onPageSelected(0) after calling setCurrentItem(0). Taking a look at the code, what that does is set the mSnapPage to the position, which is otherwise not done.
@Override
public void onPageSelected(int position) {
    if (mSnap || mScrollState == ViewPager.SCROLL_STATE_IDLE) {
        mCurrentPage = position;
        mSnapPage = position;
        invalidate();
    }

    if (mListener != null) {
        mListener.onPageSelected(position);
    }

This is terribly hacky though. I hope they fix it :/


Simplify sqrt-Inequality to prove monotonicity of a series

Question: In order to prove, that the series $a_n = \sqrt[3]{n+1} - \sqrt{n}$ is monotone, I tried to prove $a_n > a_{n+1} ~\forall n \in \mathbb{N}_{\geq 1}$.
I want to know, if there is a neat, less chaotic approach than mine.
My approach goes as follows:
$$
a_n > a_{n+1}
\iff \sqrt[3]{n+1} - \sqrt{n} > \sqrt[3]{n+2} - \sqrt{n+1}
\iff \sqrt[3]{n+1} - \sqrt[3]{n+2} > \sqrt{n} - \sqrt{n+1}
$$
Now using that $a^2 - b^2 = (a+b)(a-b)$ and $a^3 - b^3 = (a-b)(a^2+ab+b^2)$, we obtain
$$
\iff \frac{(n+1) - (n+2)}{(n+1)^{\frac{2}{3}} + ((n+1)(n+2))^{\frac{1}{3}} + (n+2)^{\frac{2}{3}}} >
\frac{n - (n+1)}{\sqrt{n} + \sqrt{n+1}}
$$
$$
\iff \frac{-1}{(n+1)^{\frac{2}{3}} + ((n+1)(n+2))^{\frac{1}{3}} + (n+2)^{\frac{2}{3}}} >
\frac{-1}{\sqrt{n} + \sqrt{n+1}}
$$
$$
\iff \sqrt{n} + \sqrt{n+1} < (n+1)^{\frac{2}{3}} + ((n+1)(n+2))^{\frac{1}{3}} + (n+2)^{\frac{2}{3}}
$$
The last equality hold true for all positive n because all root functions are monotone $(*)$ and so we have for all positive n that
$$
(n+2)^{\frac{2}{3}} \overset{(*)}{\geq}
(n+1)^{\frac{2}{3}} \geq
\sqrt{n+1} \overset{(*)}{\geq} \sqrt{n}
$$
Comment: $(n+1)^\frac 23 + (n+1)^\frac13(n+2)^\frac 13 + (n+2)^\frac 23 > 3(n+1)^\frac 23 > 2(n+1)^\frac 12 > n^\frac 12 + (n+1)^\frac 12$
And
$\forall n \ge 0, \frac {(n+1)^\frac 23}{(n+1)^\frac 12} = (n+1)^\frac 16 > \frac 23$
Comment: Perhaps showing that the derivative of $f(x)=(n+1)^{1/3}-n^{1/2}$ is always negative for positive values is easier?
Answer:
$\sqrt[3]{n+1} - \sqrt[3]{n+2} > \sqrt{n} - \sqrt{n+1}$

If some calculus is allowed, $\,\sqrt[3]{n+2} - \sqrt[3]{n+1}=\dfrac{1}{3\sqrt[3]{a^2}}\,$ for some $\,a \in (n+1,n+2)\,$  by the mean value theorem, and $\,\sqrt{n+1} - \sqrt{n} = \dfrac{1}{2 \sqrt{b}}\,$ for some $\,b \in (n,n+1)\,$. It then follows that:
$$
\sqrt[3]{n+2} - \sqrt[3]{n+1} = \dfrac{1}{3\sqrt[3]{a^2}} \lt \underbrace{\dfrac{1}{3\sqrt[3]{(n+1)^2}} < \dfrac{1}{2 \sqrt{n+1}}}_{\text{because}\; n+1 \,\gt\, 1 \,\gt\, (2/3)^6 \;\text{}} \lt \dfrac{1}{2 \sqrt{b}} = \sqrt{n+1} - \sqrt{n}
$$
Comment: @ViktorGlombik The inequality can be written as $\,\dfrac{2}{3} < \dfrac{\sqrt[3]{(n+1)^2}}{\sqrt{n+1}} = \sqrt[6]{\dfrac{(n+1)^4}{(n+1)^3}}= \sqrt[6]{n+1}\,$.
Comment: @ViktorGlombik P.S. `Where did I go wrong?` At the third step where you subtract the exponents $\frac{2}{3}-\frac{1}{2}=\color{red}{+}\frac{1}{6}$.
Comment: I understand the MVT bit but can you please share the reasoning behind the inequality with the bracket? I tried to show it and this is my work: $\frac{1}{3 \sqrt[3]{(n+1)^2}} < \frac{1}{2\sqrt{n+1}} \iff 2\sqrt{n+1} < 3 \sqrt[3]{(n+1)^2 \iff \frac{2}{3} < (n+1)^{-\frac{1}{6}} \iff (n+1) < \left( \frac{3}{2} \right)^6$. Where did I go wrong?


How to make field label as node reference link?

Question: If I have field label as Links and type is a node reference link to Page Title. And its displayed like this:
Links: Page Title
How to make the label is the link to the node without showing Page Title like this:
Links
Answer: I propose to do so (if you have a module Display Suite):
Go to ../admin/structure/ds/view_modes
Add a view mode: name is "label" and entities: "Node"
Then go to ../admin/structure/types/manage/your-content-type/display and on "Custom display settings" tab check the "Label" mode
Now go to ../admin/structure/types/manage/your-content-type/display/label select "Reset" (ds_reset) Layout, then make visible only the "Read more" and customise it: "Link text" - "See details" for example...
Then on referenced content type select "Rendered entity", and "View mode" - "Label"
Done!
Comment: In our projects, I always use this module, try it for yourself, it is extremely flexible and provides many opportunities. Why are only "custom layouts",  "block as field" or other "extra" features.
Comment: I haven't give Display Suite much of credit, as I blindly prefer sticking to templates files, but this helping! Thanks
Answer: You'll need to alter how it is rendered using a field template file (fieldname.tpl.php).
Comment: That's a reasonable start, but `print $item` won't give you the link.  Install the Devel module and start by using dpm($item) so it shows you what's in the variable.
Comment: Thanks for the tip, I've tried this `` but that is seems wrong, any idea?


Within-subjects contrasts in repeated measures anova with unbalanced design

Question: I would like to reproduce the standard output of a repeated measures anova in SPSS with R. For a balanced design (i.e. equal group sizes) I can exactly reproduce the SPSS output of the within-subjects contrasts. But when using an unbalanced (i.e. different group sizes) the results of the within-subjects contrasts are not exactly the same, especially for the main effect of the within-subject factor.
Create a test dataset: (un)comment the line cond to create (un)balanced dataset
set.seed(1234)
t <- 4
idmax <- 40

myData <- data.frame(PID = rep(seq(from = 1, to = idmax, by = 1), t),
                 #cond = rep(c(rep(c("A"), 20), rep(c("B"), 20)), t), #BALANCED
                 cond = rep(c(rep(c("A"), 22), rep(c("B"), 18)), t), #UNBALANCED
                 time = rep(x = 1:t, each = idmax),
                 acc = sample(x = 1:100, size = idmax*t, replace = TRUE)
)

myData <- within(myData, {
                 PID   <- factor(PID)
                 cond <- factor(cond)
                 time <- factor(time)
                 acc <- acc/100
})

Using the ezAnova function of the ez package I can exactly reproduce the standard SPSS output of the Between-Subject Effects and the Within-Subject Effects for both balanced and unbalanced designs.
library(ez)
ezANOVA( data = myData, dv = acc, wid = PID, within = c("time"), between = cond, type = 3)

But I cannot reproduce the Within-subjects Contrasts table of the SPSS output for unbalanced designs.
For a balanced design I can reproduce the results using the aov function.
time.L <- C(myData$time, poly, 1)
time.Q <- C(myData$time, poly, 2)
time.C <- C(myData$time, poly, 3)
mdl_balanced <- aov(acc ~ cond*time + Error(factor(PID)/(time.L + time.Q + time.C)), data = myData)
summary(mdl_balanced)

R Output:
Error: factor(PID)
          Df Sum Sq Mean Sq F value Pr(>F)
cond       1  0.128 0.12826   1.524  0.225
Residuals 38  3.198 0.08416

Error: factor(PID):time.L
          Df Sum Sq Mean Sq F value Pr(>F)
time       1 0.2999 0.29993   4.213 0.0471 *                   <--1
cond:time  1 0.0000 0.00003   0.000 0.9842
Residuals 38 2.7055 0.07120
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: factor(PID):time.Q
          Df Sum Sq Mean Sq F value Pr(>F)
time       1  0.553  0.5534   6.210 0.0172 *                   <--2
cond:time  1  0.014  0.0135   0.152 0.6992
Residuals 38  3.386  0.0891
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: factor(PID):time.C
          Df Sum Sq Mean Sq F value Pr(>F)
time       1 0.1208 0.12079   1.507  0.227                     <--3
cond:time  1 0.0259 0.02588   0.323  0.573
Residuals 38 3.0454 0.08014

SPSS output
Tests of Within-Subjects Contrasts
Measure:   MEASURE_1
Source      time    Type III SS df  Mean Square    F    Sig.
time        Linear      ,300    1   ,300       4,213    ,047   <--1
            Quadratic   ,553    1   ,553       6,210    ,017   <--2
            Cubic       ,121    1   ,121       1,507    ,227   <--3
time * cond Linear  2,812E-005  1   2,812E-005  ,000    ,984
            Quadratic   ,014    1   ,014        ,152    ,699
            Cubic       ,026    1   ,026        ,323    ,573
Error(time) Linear     2,706    38  ,071
            Quadratic  3,386    38  ,089
            Cubic       3,045   38  ,080

But if I run the same aov code for the unbalanced design. The results in the R output for the within-subject factor time clearly differ from the SPSS output (indicated with <--). The R output for cond:time match the SPSS output.
Error: factor(PID)
          Df Sum Sq Mean Sq F value Pr(>F)
cond       1  0.114 0.11398   1.348  0.253
Residuals 38  3.213 0.08454

Error: factor(PID):time.L
          Df Sum Sq Mean Sq F value Pr(>F)
time       1 0.2999 0.29993   4.229 0.0466 *                   <--1
cond:time  1 0.0106 0.01063   0.150 0.7009
Residuals 38 2.6949 0.07092
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: factor(PID):time.Q
          Df Sum Sq Mean Sq F value Pr(>F)
time       1  0.553  0.5534   6.202 0.0172 *                   <--2
cond:time  1  0.009  0.0093   0.104 0.7491
Residuals 38  3.391  0.0892
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Error: factor(PID):time.C
          Df Sum Sq Mean Sq F value Pr(>F)
time       1 0.1208 0.12079   1.527  0.224                     <--3
cond:time  1 0.0649 0.06486   0.820  0.371
Residuals 38 3.0064 0.07912

SPSS output
Tests of Within-Subjects Contrasts
Measure:   MEASURE_1
Source      time    Type III SS df  Mean Square    F    Sig.
time        Linear      ,286    1   ,286       4,030    ,052   <--1
            Quadratic   ,562    1   ,562       6,301    ,016   <--2
            Cubic       ,103    1   ,103       1,297    ,262   <--3
time * cond Linear      ,011    1   ,011        ,150    ,701
            Quadratic   ,009    1   ,009        ,104    ,749
            Cubic       ,065    1   ,065        ,820    ,371
Error(time) Linear     2,695    38  ,071
            Quadratic  3,391    38  ,089
            Cubic      3,006    38  ,079

So, my question is: How can I compute the correct F-values for polynomial contrasts for the factor time in an unbalanced repeated measures anova design using R?
PS. I can use a linear-mixed effects model for the unbalanced design in combination with fit.contrast, but this produces t-values for the contrasts instead of F-values.
options(contrasts = c("contr.sum", "contr.poly"))
library(nlme)
model.lme <- lme(acc ~ cond*time, random = ~ 1 | PID, data = myData)
anova(model.lme, type="marginal")

library(gmodels)
fit.contrast(model.lme, "time", t(contr.poly(4, c(1, 2, 3, 4))))

         Estimate Std. Error  t-value    Pr(>|t|)
time.L 0.08495364  0.0448776 1.893008 0.060892471
time.Q 0.11915404  0.0448776 2.655089 0.009063148
time.C 0.05090443  0.0448776 1.134295 0.259050482

Comment: I suspect you would get better responses on StackOverflow or R-help
Answer: I'm not familiar with the R package ez, but I can offer an alternative approach with the R package afex:
require(afex)
fm <- aov_car(acc ~ cond+Error(PID/time), data = myData)

Then you have the results that match up your SPSS output:
require(phia)
testInteractions(fm$lm, custom=list(time=contr.poly(4, c(1, 2, 3, 4))[,1]), idata = fm$data[["idata"]])

         Value Df test stat approx F num Df den Df  Pr(>F)
time1 0.084954  1  0.095882   4.0299      1     38 0.05185 .

testInteractions(fm$lm, custom=list(time=contr.poly(4, c(1, 2, 3, 4))[,2]), idata = fm$data[["idata"]])

        Value Df test stat approx F num Df den Df  Pr(>F)
time1 0.11915  1   0.14223   6.3011      1     38 0.01644 *

testInteractions(fm$lm, custom=list(time=contr.poly(4, c(1, 2, 3, 4))[,3]), idata = fm$data[["idata"]])

         Value Df test stat approx F num Df den Df Pr(>F)
time1 0.050904  1  0.033005    1.297      1     38 0.2619

Comment: Many thanks for your answer @bluepole. That's exactly what I needed. Do you know if I can also use this to compute the polynomial contrasts for the `time * cond` interaction. Would be nice if I can compute the polynomial contrast for `time` and `time * cond` with the same function.


Change the default image based on certain condition

Question: I wonder if I could provide two default images -one for boys & other for girls.
In the registration form they can choose their sex from a Boolean field.
Is it possible with conditional fields ? How?
I'm not  a programmer, so please make your answer detailed.
Comment: http://drupal.stackexchange.com/questions/37511/how-can-i-assign-users-different-profile-pictures-upon-registration-based-on-gen might help you
Answer: I would suggest using Rules as follows:
You can either include Conditional Rules for a single Rule, or use two rules:
Event: After user registration
Condition: image field is empty (only want it to run if they don't upload an image)
Condition: sex field is girl
Action: set image field to url location of girl default image
New Rule:
same as above except for the condition of sex changes to boy

The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.
Comment: Sorry........I just couldn't make it.

can you please say the exact condition & action to select?

So far, I've used this & couldn't find what action would let me put the default image url.

Event: After saving a new user account
Conditions: Data value is empty (Parameter: Data to check: [account:field-profile-pic])

& Data comparison (Parameter: Data to compare: [account:field-sex], Data value: Male)

Action: Set a data value ?
Comment: that looks correct - how is it not working?  try to add an action to set a message (any message just for testing) - this will tell us if the problem is with the event and conditions or the action - could also start only with a message action and event, try it, then start adding conditions until it fails (if its a condition problem)
Comment: Showing a message is easy as there is a clear action for this. But, I don't see any appropriate action to divert the default image to a certain url.

So far I can found 'set a Data value'   then, it ask for a 'data selector' where I can choose 'account:field-profile-pic' ,,, then it ask for  data value, but it forcing for the  same 'account:field-profile-pic' to select . There are no field where I can put the url.

if you can-- please export the rules for me. my fields machine name: sex: field_sex ; image field: field_profile_pic
Comment: there should be a button to change the value to 'direct input' where you can type in a value rather than using a field
Comment: yup, I can swear I saw that before, but somehow now its been disappeared. I'll look for this, & will come back :)


Difference between hide() and ['#access'] = FALSE

Question: I want to remove the delete button from a standard edit form in certain cases and I'm looking for the right way to do that.
So far I found that hide() marks an element as already rendered so it basically tricks the rendering process.
['#access'] = FALSE does something similar I guess, but still a little different.
In both cases, nothing is rendered concerning the delete button, but does either of them prevent the delete code from being executed on submit (e.g. if a user was manipulating the POST request)?
Or would I need a form_validate() method for that anyway?
Comment: @Djouuuuh: That one is discussed in http://drupal.stackexchange.com/questions/49984/what-is-the-difference-between-hide-function-and-unset. Unset is PHP, thus just throwing bits away.
Comment: I think that you could also ask for the unset($form['element']) function aswell! It is usually used for the same purpose! Don't you think?
Answer: Hiding the element is done during the rendering process.  If you look at the code, it just marks the element as already being rendered.
The #access key on the element is used during the form build process (can't find my chart, so I can't tell you exactly which part).  It says that this element is part of the form, but a particular user may or may not have access to be able to use it.
Unsetting the element, just throws the element away and says it is not part of the form anymore.
Of the three options, using #access is preferred: it's the API so you should use it.  When you just hide the element, a user can still submit that element git GET/POST as the Form API thinks it is still valid.  For non-submit elements, I believe the #default_value will also appear in $form_state['values'] when you validate/submit (however I don't recall the last time I tested this).
Comment: Hopefully chx will see this, as I think he wrote the original FAPI implementation.
Comment: This one seems to me a very satisfying answer.
Comment: chx is a hero, but not omnipotent
Answer: Using hide() will simply prevent that form element from being displayed. The same would be true of unset().
My understanding is that setting #access to false means that even if the POST request is manipulated, the input from that element will not be accepted.


After failing to remove fontyourface I'm left with PluginNotFoundException

Question: I ran into the error described in this issue when uninstalling the google_fonts_api used by @font-your-face: https://www.drupal.org/node/2916712
I tried going through some manual uninstall steps for google_fonts_api and fontyourface. But now I'm stuck when trying to enable/disable other modules or clearing the cache with this recurring error:
exception 'Drupal\Component\Plugin\Exception\PluginNotFoundException' with message 'The "entity:font" plugin does not exist.' in                           [error]
/srv/bridgemojo.com/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php:52
Stack trace:
#0 /srv/bridgemojo.com/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryCachedTrait.php(25):
Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition(Array, 'entity:font', true)
#1 /srv/bridgemojo.com/core/lib/Drupal/Core/Plugin/Factory/ContainerFactory.php(16): Drupal\Core\Plugin\DefaultPluginManager->getDefinition('entity:font')
#2 /srv/bridgemojo.com/core/lib/Drupal/Component/Plugin/PluginManagerBase.php(84):
[...]

I've tried truncating the cache tables. I'm stuck with trying to manually remove any references to this plugin.
If there's no successful cleanup possible, I'll have to rebuild the site from scratch, but I'm afraid I'll lose all of the content I have created.
Comment: It looks like you're already getting support in the linked issue; I would try what they suggest.  In general, the answer to a question like this is "always make a full site backup before a module install/uninstall."
Answer: For others who might land on this problem, I gave up on solving it, and rebuilt my site from scratch. Luckily it wasn't a major effort.
Answer: I stumbled upon the same issue and solved it with these commands:
reinstall via composer require drupal/fontyourface, but do not enable it
drush config-delete views.view.fontyourface_font_manager
drush config-delete taxonomy.vocabulary.font_classification
drush config-delete taxonomy.vocabulary.font_designer
drush config-delete taxonomy.vocabulary.font_foundry
drush config-delete taxonomy.vocabulary.font_tags

see if other settings by a drush config-edit
hope this helps


Dell Power Edge 2850 running slow on 1 drive?

Question: Would a dell poweredge 2850 running in a Raid 1 (mirroring) config run in a reduced performance state if one of the drives break? We're waiting on a replacement drive and getting numerous errors. Does it maybe go into some sort of automatic safe mode reduced performance state? Its a 15K drive.
Thanks,
john
Answer: I can't confirm this but I suspect that the RAID controller will disable any features that use the controller cache while there's a failed member of the array, which will probably reduce the performance slightly.
Comment: Thanks Joe, its a database intense system so it would be really good if someone could confirm this as it would dramatically reduce performance
Answer: Since you're only going to be reading from one drive, it's potentially only half the read performance it'd have in full RAID1, so I'd expect it to be slower on reads.


Paired t-test on a dataset containing multiple group variables

Question: I am analyzing data from a bacterial growth experiment.  In my experiment, I have different growth condition. For every growth condition, I have measured the bacterial number at day0, Day1, Day2, Day3, Day7 and Day14. So my main objective is to see the significant difference in bacterial count between Day0 and other days (Day0 ~ Day1, Day2, Day3, Day7, Day14) in different experimental condition.

In my data set (example image), all experimental condition are listed in column B (Temperature), C (Experiment), D (Swab), and E (Swab). The F column contains subsequent number of Day (0 to 7, I treat them as factor variable).  And the column G is the measure variable (count of bacteria).
For all experimental condition, I would like to compare the "logcfu" value of Day0 to to all subsequent day (each growth condition are independent, I am not going to compare the condition).
For example,
(i) compare (t-test) the "logcfu" between Day0 and Day1 of 'RT' temperature, 'A' experiment, 'T1' swab, 'low' inoculum.
(ii)    compare (t-test) the "logcfu" between Day0 and Day2 of 'RT' temperature, 'A' experiment, 'T1' swab, 'low' inoculum.
(iii)   compare (t-test) the "logcfu" between Day0 and Day3 of 'RT' temperature, 'A' experiment, 'T1' swab, 'low' inoculum.
…………..so on.
I can get summery measures by using following formula, which gives me a nice summary containing all results in single table.
<code>data <- read.csv("alllogcfu.csv",  sep = ";", dec = ",")
str(data)
data$day <- as.factor(data$day)
library(Rmisc)
summarydata <- summarySE(cfudata, measurevar="logCFU", groupvars=c("swab", "temperature", "inoculum", "experiment", "day"))
</code>
My question-
Is there any way to do t.test using a single command so that I will get all t statistics value for all experiment condition in a single table?
Thank you very much for your time.
Answer: From what you described the bacterial counts across days within experimental conditions are correlated, which may call for a more general longitudinal/repeated measures/serial data analysis that does not need to assume that differences in counts or difference in log counts have the correct statistical properties for subtraction to be valid (e.g., equal variance assumption, flat relationship between the difference and the baseline count).  I would think of this not as a "compare all with baseline" but rather as "characterize the time trends in counts and compute confidence bands for time-response profiles and differences in profiles across experimental conditions."  You might entertain a mixed effects Poisson regression.  Time trends can be modeled with a quadratic function of time.
Comment: Dear Frank Harrell, Thank you very much for your recommendation.


gcc 6.1 executable file link error

Question: I recently bootstrapped gcc 6.1 to my ubuntu based linux distribution.
Seemingly it installed properly because I can compile programs written in C and C++.
I can also run the compiled executables.
I can also compile a program that includes C++11 and C++14 features without any errors but when I try to run these executable I get the following error;
./exec: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./ardi)

when I run;
strings /usr/lib/x86_64-linux-gnu/libstdc++.so.6 | grep GLIB

the list does not include the needed file.
Does it mean gcc 6.1 has those files somewhere else.
How can I locate needed files and redirect gcc. I am new to linux system and not even sure I understand the error correctly.
Answer: I think this is because your host libstdc++ library is older than one from your new g++. So you can try to use static linking to avoid external dependency from newer std lib version using -static-libstdc++ g++ flag. The cost of this solution is increased size of resulting executables.
Comment: if i compile this way the executable runs but the size of the file increased from 200kb to 8mb. is this 8mb standard increase per file or connected to according to some ratio. And how does this affect compile time in general.
Comment: @fredric, Size increased exactly by size of standard library which attached to executable in this case. It is constant size addtion to every executable you will build. Compile time must not change, linking time slightly incresed per executable as well.

gcc 6.1 executable file link error


When creating new woocommerce free shipping method, it doesn´t save the changes

Question: I´ve created a new free shipping method in woocommerce using the following php code:
if ( ! defined( 'WPINC' ) ) {

    die;

}

/*
 * Check if WooCommerce is active
 */
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

function enviogratuitopeninsula_shipping_init() {
    if ( ! class_exists( 'Imp_WC_Shipping_Free_Local_Pickup' ) ) {

        class Imp_WC_Pickup_Free_Shipping_Method extends WC_Shipping_Method {
            /**
             * Constructor.
             *
             * @param int $instance_id
             */
            public function __construct( $instance_id = 0 ) {
                $this->id           = 'imp_enviopeninsulagratuito_method';
                $this->instance_id  = absint( $instance_id );
                $this->method_title = __( "Envio gratuito para la peninsula", 'imp' );
                $this->supports     = array(
                    'shipping-zones',
                    'instance-settings',
                    'instance-settings-modal',
                );
                $this->init();
            }

            /**
             * Initialize custom shiping method.
             */
            public function init() {

                // Load the settings.
                $this->init_form_fields();
                $this->init_settings();

                // Define user set variables
                $this->title = $this->get_option( 'title' );

                // Actions
                add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
            }

            function init_form_fields() {

                 $this->init_settings();
                $this->form_fields = array(

            'enabled'      => array(
                'title'   => __( 'Activar/Desactivar', 'woocommerce' ),
                'type'    => 'checkbox',
                'label'   => __( 'Una vez desactivado, este método heredado dejará de estar disponible.', 'woocommerce' ),
                'default' => 'no',
            ),
            'title'        => array(
                'title'       => __( 'Titulo', 'woocommerce' ),
                'type'        => 'text',
                'description' => __( 'Esto controla el título que el usuario ve durante el pago.', 'woocommerce' ),
                'default'     => __( 'Envío gratuito', 'woocommerce' ),
                'desc_tip'    => true,
            ),
            'availability' => array(
                'title'   => __( 'Disponibilidad de los métodos', 'woocommerce' ),
                'type'    => 'select',
                'default' => 'all',
                'class'   => 'availability wc-enhanced-select',
                'options' => array(
                    'all'      => __( 'All allowed countries', 'woocommerce' ),
                    'specific' => __( 'Specific Countries', 'woocommerce' ),
                ),
            ),
            'countries'    => array(
                'title'             => __( 'Países específicos', 'woocommerce' ),
                'type'              => 'multiselect',
                'class'             => 'wc-enhanced-select',
                'css'               => 'width: 400px;',
                'default'           => '',
                'options'           => WC()->countries->get_shipping_countries(),
                'custom_attributes' => array(
                    'data-placeholder' => __( 'Seleccione algunos países', 'woocommerce' ),
                ),
            ),
            'requires'     => array(
                'title'   => __( 'El envío gratuito requiere...', 'woocommerce' ),
                'type'    => 'select',
                'class'   => 'wc-enhanced-select',
                'default' => '',
                'options' => array(
                    ''           => __( 'N/D', 'woocommerce' ),
                    'coupon'     => __( 'Un cupón de envío gratuito válido', 'woocommerce' ),
                    'min_amount' => __( 'Un importe mínimo de pedido', 'woocommerce' ),
                    'either'     => __( 'Un importe mínimo de pedido O un cupón', 'woocommerce' ),
                    'both'       => __( 'Un importe mínimo de pedido Y un cupón', 'woocommerce' ),
                ),
            ),
            'min_amount'   => array(
                'title'       => __( 'Importe mínimo del pedido', 'woocommerce' ),
                'type'        => 'price',
                'placeholder' => wc_format_localized_price( 0 ),
                'description' => __( 'Los usuarios tendrán que gastar esta cantidad para obtener el envío gratuito (si está activado arriba).', 'woocommerce' ),
                'default'     => '0',
                'desc_tip'    => true,
            ),
         );

            }

            /**
             * calculate_shipping function.
             *
             * @access public
             *
             * @param mixed $package
             *
             * @return void
             */

            public function calculate_shipping( $packages = array() ) {
                $rate = array(
                    'id'       => $this->id,
                    'label'    => $this->title,
                    'cost'     => '',
                    'calc_tax' => ''
                );

                // Register the rate
                $this->add_rate( $rate );
            }
        }
    }
}
add_action( 'woocommerce_shipping_init', 'enviogratuitopeninsula_shipping_init' );

function envioapeninsulagratuito_shipping_method( $methods ) {
    $methods['imp_enviopeninsulagratuito_method'] = 'Imp_WC_Pickup_Free_Shipping_Method';

    return $methods;
}
add_filter( 'woocommerce_shipping_methods', 'envioapeninsulagratuito_shipping_method' );
}

In the following picture you can see the result:

The problem occurs when clicking "save changes", it doesn´t save them. Is there a way to create a different free shipping method appart from the default one of woocommerce?? I mean, same fields and same option but different ID.
Answer: Use $this->instance_form_fields instead of $this->form_fields in the init_form_fields() method.
function init_form_fields() {

    $this->init_settings();
    $this->instance_form_fields = array(

        'enabled'      => array(
            'title'   => __( 'Activar/Desactivar', 'woocommerce' ),
            'type'    => 'checkbox',
            'label'   => __( 'Una vez desactivado, este método heredado dejará de estar disponible.', 'woocommerce' ),
            'default' => 'no',
        ),
        'title'        => array(
            'title'       => __( 'Titulo', 'woocommerce' ),
            'type'        => 'text',
            'description' => __( 'Esto controla el título que el usuario ve durante el pago.', 'woocommerce' ),
            'default'     => __( 'Envío gratuito', 'woocommerce' ),
            'desc_tip'    => true,
        ),
        'availability' => array(
            'title'   => __( 'Disponibilidad de los métodos', 'woocommerce' ),
            'type'    => 'select',
            'default' => 'all',
            'class'   => 'availability wc-enhanced-select',
            'options' => array(
                'all'      => __( 'All allowed countries', 'woocommerce' ),
                'specific' => __( 'Specific Countries', 'woocommerce' ),
            ),
        ),
        'countries'    => array(
            'title'             => __( 'Países específicos', 'woocommerce' ),
            'type'              => 'multiselect',
            'class'             => 'wc-enhanced-select',
            'css'               => 'width: 400px;',
            'default'           => '',
            'options'           => WC()->countries->get_shipping_countries(),
            'custom_attributes' => array(
                'data-placeholder' => __( 'Seleccione algunos países', 'woocommerce' ),
            ),
        ),
        'requires'     => array(
            'title'   => __( 'El envío gratuito requiere...', 'woocommerce' ),
            'type'    => 'select',
            'class'   => 'wc-enhanced-select',
            'default' => '',
            'options' => array(
                ''           => __( 'N/D', 'woocommerce' ),
                'coupon'     => __( 'Un cupón de envío gratuito válido', 'woocommerce' ),
                'min_amount' => __( 'Un importe mínimo de pedido', 'woocommerce' ),
                'either'     => __( 'Un importe mínimo de pedido O un cupón', 'woocommerce' ),
                'both'       => __( 'Un importe mínimo de pedido Y un cupón', 'woocommerce' ),
            ),
        ),
        'min_amount'   => array(
            'title'       => __( 'Importe mínimo del pedido', 'woocommerce' ),
            'type'        => 'price',
            'placeholder' => wc_format_localized_price( 0 ),
            'description' => __( 'Los usuarios tendrán que gastar esta cantidad para obtener el envío gratuito (si está activado arriba).', 'woocommerce' ),
            'default'     => '0',
            'desc_tip'    => true,
        ),
    );

}

For obtaining these values use the $this->get_option() method like you did in the init() method:
    // Define user set variables
    $this->title = $this->get_option( 'title' );

In some cases you may need the get_instance_from_fields() method but I have a working solution without it:
    /**
     * Get setting form fields for instances of this shipping method within zones.
     *
     * @return array
     */
    public function get_instance_form_fields() {
        return parent::get_instance_form_fields();
    }

Answer: I´ve added the following code to the previous one:
´´´´
     /**
         * Process and redirect if disabled.
         */
        public function process_admin_options() {
            parent::process_admin_options();

            if ( 'no' === $this->settings['enabled'] ) {
                wp_redirect( admin_url( 'admin.php?page=wc-settings&tab=shipping&section=options' ) );
                exit;
            }
        }

´´´´
Now it seems to be trying to save the the configuration fields (minimum amount for activating the free shipping, countries...), but the saving doesn´t finish...


React styled-component

Question: I'm reading the styled-components documentation but there was a thing that was not explained in the documentation, below is the code example:
const Button = styled.button<{ $primary?: boolean; }>`
  background: ${props => props.$primary ? "#BF4F74" : "white"};
  color: ${props => props.$primary ? "white" : "#BF4F74"};

  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid #BF4F74;
  border-radius: 3px;
`;

What does this code mean: <{ $primary?: boolean; }>? Because this syntax isn't explained in styled component docs.
Answer: This is a type information for typescript.
This means that a prop called $primary, having boolean type and is optional.
Answer:
What does this code mean: <{ $primary?: boolean; }>? Because this syntax
isn't explained in styled component docs.

It is actually explained in a bit of detail in the Typescript section of the API page. See specifically Using Custom Props.

import styled from 'styled-components';
import Header from './Header';

const NewHeader = styled(Header)<{ customColor: string }>`
  color: ${(props) => props.customColor};
`;

Syntax/Code Breakdown
<{ $primary?: boolean; }>
   abbbbbbbc: ddddddd

This is declaring a custom prop with the following breakdown:

a. "$" prefix indicates a transient prop, e.g. a prop that isn't passed to the underlying React node or rendered to the DOM element
ab. Prop name, e.g. customColor or $primary
c. Prop is optional
d. Prop is a boolean type
Answer: I'm not super familiar with styled-components, but the code you're mentioning gives the button a prop called $primary. The : boolean indicates that the prop is a boolean, so it could be true or false. (If you're not familiar with props and components in frameworks like react, check out the documentation here.) To explain in simple terms, a prop is an input for a component, like a parameter for a function. The component's display or behavior/functionality may change in response to a prop.

React styled-component


Como navegar entre as abas de um painel bootstrap por link href?

Question: Então galera, estou com um problema... eu quero fazer um cadastro e quando eu processar ele em php eu quero que ele retorne em uma determinada aba do painel.. como faço isso?
Answer: Use:
$('a[href="#home"]').tab('show');

EDIT
Para usar ao carregar a Página use no evento de document.ready:
$(document).ready(function(){
    $('a[href="#home"]').tab('show');
});

ou sua abreviação:
$(function(){
    $('a[href="#home"]').tab('show');
});

Onde #home é o href da sua tab
Source:
Bootstrap

$('button').click(function(){
    $('a[href="#home"]').tab('show');
})
.btn{
    margin-top: 100px;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Dynamic Tabs

Home

Menu 1

Menu 2

Menu 3

HOME

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Menu 1

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Menu 2

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam.

Menu 3

Eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

<button class="btn btn-default">Ir para Tab Home</button>
Comment: Como executa a função javascript ao carregar a pagina?
Comment: @LucasFonseca Alterei minha resposta, espero ter Ajudado!


Python try except, try again after executing except statement

Question: I'm trying to execute a statement, but if it fails I want to execute the except statement and after I want to execute the try again. I know I can use loops, but I'm looking for a more elegant solution.
In my use case I try to save a file to a folder but if I get the FileNotFoundError I want to create the folder in the except and go to the try again.
from pathlib import Path
import os

folder = Path('folder')
df = [a,b,c]

try:
    df.to_feather(folder / 'abc.ftr')
except:
    os.makedirs(folder)
    df.to_feather(folder / 'abc.ftr')

But in this case I would repeat the df.to_feather(folder / 'abc.ftr') statement. This get's annoying if the statement gets larger and I want to refrain for building a function for this.
Another way could be:
if folder not in os.listdir():
    os.makedirs(folder)

df.to_feather(folder / 'abc.ftr')

Would this be the 'proper' way to tackle this?
Comment: Your statement is contradictory: "This get's annoying if the statement gets larger and I want to refrain for building a function for this." - breaking down a problem in to smaller parts (functions in this instance) is a way of reducing complexity and reusing code to avoid duplication. Why would you _not_ want to do that?
Comment: Does this answer your question? [Python pathlib make directories if they don't exist](https://stackoverflow.com/questions/50110800/python-pathlib-make-directories-if-they-don-t-exist)
Comment: @Nathan Not a duplicate!
Comment: Related: https://stackoverflow.com/questions/10594113/bad-idea-to-catch-all-exceptions-in-python
Comment: Does this answer your question? [How can I safely create a nested directory in Python?](https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory-in-python)
Answer: Since python3.2 os.makedirs has optional exist_ok argument, which by default is False. When set True and os.makedirs is instructed to create catalog(s) which is(are) already existing it is no-operation. Thus in place of
if folder not in os.listdir():
    os.makedirs(folder)

df.to_feather(folder / 'abc.ftr')

you can just do
os.makedirs(folder, exist_ok=True)
df.to_feather(folder / 'abc.ftr')

Comment: Although this answers the particular case of the user, it misses the general answer to the question about how to try something and if it fails try it again after doing something in the middle to remedy the first fail.
Comment: @SembeiNorimaki - Just because someone asks how to do something does not make it the best way of achieving the desired result. Although the question is asking about retrying in the event of an exception, it is generally better to avoid exceptions in the first place. The question does also go on to ask if checking for, and creating the missing folder, would "be the 'proper' way to tackle this?". So I think Daweo's answer is perfectly valid.
Comment: @Tony " it is generally better to avoid exceptions in the first place." why? in Python? what happened to EAFP?
Comment: @athing - true, and I admit I come from a C/C++ background where exceptions were more expensive computationally :) but that doesn't make them free in Python either. There are cases when checking first is more efficient if you expect the operation to fail more often than not. But in this particular instance, when interacting with the file system, it's a solved problem, as described in this answer.
Answer: To answer the question in the title, you can do this recursively:
def do_stuff(x):
    try:
        stuff(x)
    except SpecificException:
        other_stuff(x)
        do_stuff(x)

If you want to create a file, you can just use:
pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True)

Comment: It would be wise to check what caused the exception and only call `do_stuff` again if the fault can be rectified, otherwise you'll recurse until the stack overflows.
Comment: bare except is dangerous


Sum of a Geometrico-geometric series

Question: Is there a closed form solution for the sum of an infinite geometric series, where the growth from element n to element n+1 converges to zero for $n\rightarrow\infty$?
Specifically, I'm looking for a closed formula for $$\sum_{t=0}^\infty\left(1+a\phi^t\right)^t\omega^t$$ where $\omega<\phi<1$ as well as $a<1$.
Alternatively, a solution for $$\sum_{t=0}^\infty\left(1+\frac at\right)^t\omega^t$$ would also be great.
Thanks a lot for looking into this.
Answer: Well, I can rearrange the sum
but I don't think that
I've made it better.
Anyway,
here's what I've got.
$\begin{array}\\
S(a, b, c)
&=\sum_{t=0}^\infty\left(1+ab^t\right)^tc^t\\
&=\sum_{t=0}^\infty\sum_{k=0}^t\binom{t}{k}a^kb^{tk}c^t\\
&=\sum_{k=0}^{\infty}\sum_{t=k}^{\infty}\binom{t}{k}a^kb^{tk}c^t\\
&=\sum_{k=0}^{\infty}a^k\sum_{t=k}^{\infty}\binom{t}{k}(b^{k}c)^t\\
&=\sum_{k=0}^{\infty}\dfrac{a^k}{k!}\sum_{t=k}^{\infty}\dfrac{t!}{(t-k)!}(b^{k}c)^t\\
&=\sum_{k=0}^{\infty}\dfrac{a^k}{k!}\sum_{t=0}^{\infty}\dfrac{(t+k)!}{t!}(b^{k}c)^{t+k}\\
&=\sum_{k=0}^{\infty}\dfrac{a^k(b^kc)^k}{k!}\sum_{t=0}^{\infty}\dfrac{(t+k)!}{t!}(b^{k}c)^{t}\\
&=\sum_{k=0}^{\infty}\dfrac{a^k(b^kc)^k}{k!}k!(1-b^kc)^{-k-1}\\
&=\sum_{k=0}^{\infty}\dfrac{a^k(b^kc)^k}{(1-b^kc)^{k+1}}\\
\end{array}
$
And that's it.

Sum of a Geometrico-geometric series


Include_once e diretórios direferentes - php

Question: Estou tento problemas com o include em relação aos diretórios, pois quando chamo uma classe de outro diretório que contenha outro include os caminhos são diferentes. Preciso saber se tem alguma maneira de unificar estes includes e sempre chama-los da mesma forma, alguém tem alguma ideia?
Comment: Dê exemplos do que ocorre.
Comment: Ou você adiciona no `includepath` ou usa uma espécie de `define(_ROOT_, '/caminho/padrao')`, e inclui arquivos sempre usando `include _ROOT_ . "/caminho/arquivo.php";`.
Answer: Caso você não use namespaces, a melhor maneira disso é sempre levar em conta o caminho absoluto dos arquivos do sistema, e não os caminhos relativos – ou seja, o caminho de um arquivo em relação a outro.
Além disso, use sempre as seguintes constantes mágicas, a fim de facilitar a inclusão de arquivos:

__FILE__ (para referenciar o arquivo atual), e
__DIR__ (para referenciar o diretório do arquivo atual).

Por exemplo:
index.php:
<?php
require_once(__DIR__ . '/bootstrap.php');

bootstrap.php:
<?php
require_once(__DIR__ . '/autoload.php');
require_once(__DIR__ . '/config/config.php');
require_once(__DIR__ . '/app/url_router.php');

Agora, se você usa a versão 5.3 do PHP ou maior, de repente vale a pena começar a pensar em namespaces. Assim, ao invés de incluir os arquivos manualmente, a organização das classes leva em conta a estrutura de diretórios – o que fica muito mais intuitivo.
Se você optar por esse caminho, é uma boa usar o Composer, que pode gerar um arquivo de autoload e facilita alguns aspectos do desenvolvimento da sua aplicação.
Comment: Um detalhe à parte: a constante mágica (http://php.net/manual/pt_BR/language.constants.predefined.php) `__DIR__` só está disponível a partir do PHP 5.3. A melhor opção, para aumentar a portabilidade, é utilizar `dirname(__FILE__)` en vez de `__DIR__`.
Answer: Talvez isso lhe ajude.
No php set_include_path() verifica o primeiro caminho, e se não encontrá-lo, verifique o seguinte caminho, até que ele seja localize o arquivo incluído ou retorna com um aviso ou um erro. Você pode modificar ou definir o seu caminho de inclusão em tempo de execução usando set_include_path(). Veja:
set_include_path(get_include_path() . PATH_SEPARATOR . 'diretorio');

veja este exemplo
Mas, também você precisa conhercer o autoload() nativo do php.


What is a "gaussian" linear model?

Question: I saw the slides on https://ocw.mit.edu/courses/mathematics/18-655-mathematical-statistics-spring-2016/lecture-notes/MIT18_655S16_LecNote19.pdf
The title of the slide is "gaussian linear models." But it seems the content is just for general linear model. Are the two equivalent?
Comment: I see Kempthorne defines the general linear model on page 3 of the notes. It is the standard OLS model except that the error term is allowed to take any flavor -- not stated, but probably assuming IID and mean 0. The Gaussian linear model then would be the version with normally distributed (Gaussian) errors, where the OLS is the maximum likelihood estimator.
Comment: Why are you still stuck on this? The definition is given on slide 3. If you're going to follow the course notes, you have to follow the professor's definitions; read them closely.
Comment: The "Gaussian linear model" is a special case of the generalized linear model that just so happens to be ordinary least squares.
Comment: @AdamO I had a typo in my OP. I meant to type "general" instead of "generalized." Is the general linear model the same as the gaussian linear model? If so, then I don't think it's correct to say that a general linear model is OLS. OLS is just one (most popular) method to obtain a general model, but there are also other methods.
Comment: @AdamO Doesn't the general linear model, by definition, assume normality of errors? If the error term is allowed to be anything, isn't that a generalized linear model instead of a general model? The terminology confuses me.
Comment: Because there are so many resources on regression on the internet, it can be expected that definitions are often not perfectly aligned. Neither "General Linear Model" nor "Gaussian Linear Model" is a commonly used term. It's best to infer from context what exactly the author means.
Answer: Answered in comments by AdamO:

I see Kempthorne defines the general linear model on page 3 of the
notes. It is the standard OLS model except that the error term is
allowed to take any flavor -- not stated, but probably assuming IID
and mean 0. The Gaussian linear model then would be the version with
normally distributed (Gaussian) errors, where the OLS is the maximum
likelihood estimator.
Comment: Thank you for offering an answer.  I believe it misinterprets the slides, though, because later on there is a section *within this one* on models with Gaussian error terms that is referred to as *Normal* models.  "Gaussian linear model" most likely respects Gauss's contributions to OLS theory rather than referring to the error distribution.
Comment: @whuber Thanks - would you like to add that as a separate answer, or to edit this one to correct it?

What is a "gaussian" linear model?


Need for bonferroni correction

Question: I need help understanding if I need to / how to apply a bonferroni correction!
I have one continuous variable and three unrelated groups that have completed scores on this variable (Groups: A,B,C). I planned to conduct 4 pairwise comparisons with this outcome variable (A-B, A-C, AB-C and A-BC).
Unfortunately normality is violated so I plan to conduct non-parametric Mann Whitney U tests for these comparisons.
Do I need to apply a bonferroni correction here (.05*4?) or as I am only looking at one outcome variable does this not apply?
Are there alternative methods that may be more suitable?
Answer: Using bonferroni correction on multiple comparisons is correct, but there are some points to consider:

If your research is explorative or/and you don't have an adequate
sample size I would avoid bonferroni correction (you already
have a low power and it is really difficult you will achieve some
results);

If the comparisons are not the main endpoint of your research I would avoid bonferroni correction;

If you will perform a lot of multiple comparisons i would use it, otherwise if you will preform few tests the correction makes little difference;

How you will interpret the results: If the rejections of a single test will be considered a success the bonferroni correction could be a good idea otherwise if you consider a success the rejections of more than one test you could avoid it (considering the number of comparisons);

There are certainly a lot of things to consider before deciding to apply the bonferroni correction, take always in mind that it is a conservative method.
Comment: Great, the research is exploratory. Your answer helped a lot thank you
Answer: The need for Bonferroni correction does not follow hard and strict rules but calls for weighing up each time you consider it.
Each time you conduct a statistical test there is a risk for an alpha error and a beta error, type I and type II error. Sometimes making an beta error is bad, because if you fail to proove a drug is efficient, you might fail to hand it to a patient who should really take it. Sometimes making an alpha error is bad, because a patient suffers from the side effects of a drug, she should not have taken in the first place.
You need to consider both, the consequences of an alpha and those of an beta error and then you will have to weigh that, not in a statistical but in a human way. When you or a sensible reader of your work comes to the conclusion, that the alpha error is the big problem that needs to be controlled at the cost of a beta error, then Bonferroni correction of Bonferroni-Holm correction will have your back. However it comes at a price as it is correcting only against the overall alpha error and thus applying a Bonferroni correction may sometimes be not indicated or even unethical, even in situations where common rules may advise its use.
In a world, where p < .05 is generally considered a success of the researcher andthe researcher feels a need to defend against the accusation of obtaining that success surreptitiously it is easy to always recommend  alpha-correction but we should really not live in such a world.
Comment: @just_learning that sounds like two new questions, not like a comment to an answer given two years ago. It also appears as if you should first read up on Bonferroni correction before posting these as questions on this site. There probably is a good video on YouTube as well or two.
Comment: You are right, this is only two months old and I was wrong about that.
Comment: Thank you, a lot to consider

Need for bonferroni correction