Brass instrument lengths

Question: I assume (perhaps wrong), that the fundamental frequency of brass instruments can be calculated with the wave equation:
c = lambda * f,
WHERE:

c = the speed of sound.  I calculated this to be 349 m/s at 30 degrees C (temperature of a warm instrument).  I think this is right because two control conditions (0C and 20C) gave me correct answers (331 and 343 m/s).
f = Fundamental frequency of the instrument.
lambda = length of the instrument.

Given the fundamental frequency of 87.31 Hz (F2) the length of this F-tuba should be 4.0m.
However, Wikipedia's article on tubas says an Eb-tuba is 4.0m and an F-tuba is 3.7m. I took a tape measure and measured my F-tuba along the center of the bore to the edge of the bell, and I measured 3.72m.  It seems Wikipedia is right!
Did I use an incorrect equation to calculate the length of a brass tuba or was there another problem?
My guess is that there's a problem in the boundry condition at the bell.  c=Lf applies to a non-flared pipe like a Didgeridoo and the flare of the bell effectvely lengthens the instrument.  In the sketch below, I measured the long-dashed line to the X where I should have measured to the ?.  But is there a way to know the distance between those two marks?

I don't think the problem is related to the speed of sound.  If I use the known 331 m/s at 0 deg.C, the F tuba is 3.79m, still longer than my measured 3.72.
My mouth-piece is not 30cm long, so that also doesn't account for it.
Another thing it could be is the extra length added when reflecting from wall to wall as the sound travels around curves.  A straight tuba without curves could be closer to the theoretical length I calculated.  But I don't know if this is true.  Any ideas would be welcome.
Answer: Thanks to Elements in Space  for adding the "acoustics" tag to the question.  I browsed "acoustics" and find this nice answer about boomwhackers:
https://music.stackexchange.com/a/124754/72714
The answer is End Correction. It seems that the pressure waves are nicely aligned as they come out of the tube, and take some distance before mixing with the ambient air.  That means a correction can be should applied to the physical tube to match its "effective" length in generating sound.
The Tuba I measured has a 44cm (diameter) bell.  As brass instruments are open on both ends, the correction (delta-L) is dL = 0.6D, or 26.4cm.  Adding 26.4 cm to the measured 3.72m gets us quite 3.98m which is very close to the theoretical 4.00m.
I think that is within the tolerance of my tape measuring technique.
Still, it's possible that this answer is wrong. That formula applies to a cylindrical tube, while the tuba is conical. 44cm isn't the diameter of the entire instrument!  I was happy to get an answer that was close, but it might have been a coincidence. I'm not sure if it's a good, general solution. I'm happy to accept any better answers.
Comment: Another thing to be aware of is that the speed of sound is not a constant because the density of the air inside the instrument is not constant (density of a medium is directly related to the speed of sound in that medium). Both temperature and humidity affect the density, with very audible impact. Regarding pitch sense, exact frequencies and pitch do not always match exactly. Combining those facts with some other acoustic properties of real instruments means we shouldn't expect the ideal dimensions generated by math to match the real world dimensions.
Comment: If you think that's weird,  look up the acoustics of reed instruments.  For example, the saxophone has a conical bore, and the effective length goes way "backwards" to a convergence point well in advance of the mouthpiece.
Comment: @CarlWitthoft is that the case for all conical instruments? There's at least a few conical bore brass instruments too
Comment: @fyrepenguin I think so, but I bet you can track down some research papers for any given instrument.

Brass instrument lengths


How is Naive Bayes a Linear Classifier?

Question: I've seen the other thread here but I don't think the answer satisfied the actual question.  What I have continually read is that Naive Bayes is a linear classifier (ex: here) (such that it draws a linear decision boundary) using the log odds demonstration.
However, I simulated two Gaussian clouds and fitted a decision boundary and got the results as such (library e1071 in r, using naiveBayes())

As we can see, the decision boundary is non-linear.  Is it trying to say that the parameters (conditional probabilities) are a linear combination in the log space rather than saying the classifier itself separates data linearly?
Comment: how did you create the decision boundary? i suspect its to do with your fitting routine rather than the true decision boundary of the classifier. normally one would generate a decision boundary by calculating the decision at every single point in your quadrant.
Comment: That is what i did,  I took the two ranges of X = [Min(x), Max(x)] and Y = [Min(Y), Max(Y)] with a spacing of 0.1.  I then fitted all those data points with the trained classifier and found points such that the log odds were between -0.05 and 0.05
Answer: In general the naive Bayes classifier is not linear, but if the likelihood factors $p(x_i \mid c)$ are from exponential families, the naive Bayes classifier corresponds to a linear classifier in a particular feature space. Here is how to see this.
You can write any naive Bayes classifier as*
$$p(c = 1 \mid \mathbf{x}) = \sigma\left( \sum_i \log \frac{p(x_i \mid c = 1)}{p(x_i \mid c = 0)} + \log \frac{p(c = 1)}{p(c = 0)} \right),$$
where $\sigma$ is the logistic function. If $p(x_i \mid c)$ is from an exponential family, we can write it as
$$p(x_i \mid c) = h_i(x_i)\exp\left(\mathbf{u}_{ic}^\top \phi_i(x_i) - A_i(\mathbf{u}_{ic})\right),$$
and hence
$$p(c = 1 \mid \mathbf{x}) = \sigma\left( \sum_i \mathbf{w}_i^\top \phi_i(x_i) + b \right),$$
where
\begin{align}
\mathbf{w}_i &= \mathbf{u}_{i1} - \mathbf{u}_{i0}, \\
b &= \log \frac{p(c = 1)}{p(c = 0)} - \sum_i \left( A_i(\mathbf{u}_{i1}) - A_i(\mathbf{u}_{i0}) \right).
\end{align}
Note that this is similar to logistic regression – a linear classifier – in the feature space defined by the $\phi_i$. For more than two classes, we analogously get multinomial logistic (or softmax) regression.
If $p(x_i \mid c)$ is Gaussian, then $\phi_i(x_i) = (x_i, x_i^2)$ and we should have
\begin{align}
w_{i1} &= \sigma_1^{-2}\mu_1 - \sigma_0^{-2}\mu_0, \\
w_{i2} &= 2\sigma_0^{-2} - 2\sigma_1^{-2}, \\
b_i &= \log \sigma_0 - \log \sigma_1,
\end{align}
assuming $p(c = 1) = p(c = 0) = \frac{1}{2}$.

*Here is how to derive this result:
\begin{align}
p(c = 1 \mid \mathbf{x})
&= \frac{p(\mathbf{x} \mid c = 1) p(c = 1)}{p(\mathbf{x} \mid c = 1) p(c = 1) + p(\mathbf{x} \mid c = 0) p(c = 0)} \\
&= \frac{1}{1 + \frac{p(\mathbf{x} \mid c = 0) p(c = 0)}{p(\mathbf{x} \mid c = 1) p(c = 1)}} \\
&= \frac{1}{1 + \exp\left( -\log\frac{p(\mathbf{x} \mid c = 1) p(c = 1)}{p(\mathbf{x} \mid c = 0) p(c = 0)} \right)} \\
&= \sigma\left( \sum_i \log \frac{p(x_i \mid c = 1)}{p(x_i \mid c = 0)} + \log \frac{p(c = 1)}{p(c = 0)} \right)
\end{align}
Comment: Notice the important point that $\phi(x) = (x, x^2)$.  What this means is that linear classifiers are a linear combination of weights $\mathbf{w}$ and potentially non-linear functions of the features!  So, to the original poster's point, a plot of the datapoints may not show that they are separable by a line.
Comment: I find this answer misleading: as pointed out in the comment just about, and the answer just below, the Gaussian naive Bayes is not linear in the original feature space, but in a non-linear transform of these. Hence it is not a conventional linear classifier.
Comment: Thank you for the derivation, which I now understand, can you explain the notations in equation 2 and below? (u, h(x_i), phi(x_i), etc) Is P(x_i | c) under an exponential family just simply taking the value from the pdf?
Comment: There are different ways you can express one and the same distribution. The second equation is an exponential family distribution in canonical form. Many distributions are exponential families (Gaussian, Laplace, Dirichlet, Bernoulli, binomial, just to name a few), but their density/mass function is typically not given in canonical form. So you first have to reparametrize the distribution. This table tells you how to compute $\mathbf{u}$ (natural parameters) and $\phi$ (sufficient statistics) for various distributions: http://en.wikipedia.org/wiki/Exponential_family#Table_of_distributions
Comment: why $p(x_i|c)$ is Gaussian,then $\phi_i(x_i)=(x_i,x_i^2)$? I think the sufficient statistic $T(x)$ for Gaussian distribution should be $x/\sigma$.
Comment: See https://en.wikipedia.org/wiki/Exponential_family#Table_of_distributions
Answer: It is linear only if the class conditional variance matrices are the same for both classes. To see this write down the ration of the log posteriors and you'll only get a linear function out of it if the corresponding variances are the same.
Otherwise it is quadratic.
Answer: I'd like add one additional point:  the reason for some of the confusion rests on what it means to be performing "Naive Bayes classification".
Under the broad topic of "Gaussian Discriminant Analysis (GDA)" there are several techniques:  QDA, LDA, GNB, and DLDA (quadratic DA, linear DA, gaussian naive bayes, diagonal LDA).  [UPDATED] LDA and DLDA should be linear in the space of the given predictors.  (See, e.g., Murphy, 4.2, pg. 101 for DA and pg. 82 for NB.  Note:  GNB is not necessarily linear.
 Discrete NB (which uses a multinomial distribution under the hood) is linear.  You can also check out Duda, Hart & Stork section 2.6).  QDA is quadratic as other answers have pointed out (and which I think is what is happening in your graphic - see below).
These techniques form a lattice with a nice set of constraints on the "class-wise covariance matrices" $\Sigma_c$:

QDA: $\Sigma_c$ arbitrary: arbitrary ftr. cov. matrix per class
LDA: $\Sigma_c = \Sigma$: shared cov. matrix (over classes)
GNB: $\Sigma_c = {diag}_c$: class wise diagonal cov. matrices (the assumption of ind. in the model $\rightarrow$ diagonal cov. matrix)
DLDA: $\Sigma_c = diag$: shared & diagonal cov. matrix

While the docs for e1071 claim that it is assuming class-conditional independence (i.e., GNB), I'm suspicious that it is actually doing QDA.  Some people conflate "naive Bayes" (making independence assumptions) with "simple Bayesian classification rule".  All of the GDA methods are derived from the later; but only GNB and DLDA use the former.
A big warning, I haven't read the e1071 source code to confirm what it is doing.

How is Naive Bayes a Linear Classifier?


If 2 out of 3 maps between short exact sequences is zero, is the third also zero?

Question: In this commutative diagram, suppose that the rows are short exact sequences of modules over a commutative ring:
$$
0 \longrightarrow A \longrightarrow B \longrightarrow C \longrightarrow 0
$$
$$ f\downarrow \qquad\downarrow g \quad \downarrow h $$
$$0 \longrightarrow D \longrightarrow E \longrightarrow F \longrightarrow 0
$$
Suppose that $f=0$ and $h=0$. Does this imply that the middle map $g=0$ ?
Answer: Take $\require{AMScd}$ a non-zero module $M$ and consider
\begin{CD}
0 @>>> 0 @>>> M @>1>> M @>>> 0 \\
@VVV @V0VV @V1VV @V0VV @VVV \\
0 @>>> M @>1>> M @>>> 0 @>>> 0
\end{CD}


Maior palíndromo em uma string? C++

Question: Estou tentando fazer um código para conseguir descobrir, por exemplo se em frases como:
A arara azul é linda!
tem um palindromo e qual é o maior deles?
no caso a resposta seria:
arara
Cheguei no código abaixo mas não sei como desenvolver ele para conseguir a solução. Alguém pode me ajudar? Gostaria que me quem puder me ajudar explique como chegou nessa lógica para que eu possa entender. Obrigado.
#include <iostream>

using namespace std;

int main(){

    string frase; // Guarda uma string

    bool ok = true; // Ajuda a verificar se a variável é um palíndrormo

    getline(cin,frase); // Recebe a frase que será tratada.

    int tam = frase.size(); // Atribui na variável tam o tamanho da string: frase.

    for (int i = 0, j = tam - 1 ; i < tam - 1; i++, j--){

        if( frase[i] == frase[j] ){
            ok = true;
        }else{
            ok = false;
        }

    }

        if( ok == true ){
            cout << "E palindromo" <<  endl;
        }else{
            cout << "Nao e palindromo" << endl;
        }

    return 0;
}

Comment: Dica: tenta com o [algoritmo de Manacher](https://cp-algorithms.com/string/manacher.html).
Answer: O código a baixo faz a busca em uma frase pela sequencia de caracteres que formem um palíndromo, desde que a frase não use virgula ou acentuação, para este caso basta você inclui uma verificação a cada rodada do for na string sub_sentence.
#include <iostream>

using namespace std;

bool check_palindrome(string sentence) {

    string sentence_without_space;

    //Isto é necessário caso queira vê palidromes de várias palavras em uma frase
    for (int i = 0; i < sentence.size(); i++) {

        if (sentence[i] == ' ') {

            continue;
        }

        //Removendo os espaços em branco
        sentence_without_space.push_back(sentence[i]);
    }

    //Verificando se é palindrome
    for (int i = 0, j = sentence_without_space.size() - 1; i <= j; i++, j--) {

        if (sentence_without_space[i] != sentence_without_space[j]) {

            return false;
        }
    }

    return true;
}

string analyze_sentence(string sentence) {

    string greater_palindrome;
    string sub_sentence;
    string sub_sentence_palindrome;
    //---

    //Normaliza a entrada de dados
    for (int i = 0; i < sentence.size(); i++) {

        sentence[i] = tolower(sentence[i]);
    }

    //Percorre toda a sequencia de caracteres da frase, comparando se há um palindrome a partir do caracter atual
    for (int i = 0; i < sentence.size(); i++) {

        //Caso o caracter inicial seja fazio ignora e não verifica
        if (sentence[i] == ' ')
            continue;

        //Selecionando a senquancia de busca atual
        sub_sentence = sentence.substr(i);

        //Percorre do final para o inicio verificando se o conjunto de caracteres entre os indices i e j formam um palindrome
        for (int j = sub_sentence.size(); j > 0; j--) {

            //Caso o caracter final seja fazio ignora e não verifica
            if (sub_sentence[j] == ' ')
                continue;

            //Extrai o possível palindrome
            sub_sentence_palindrome = sub_sentence.substr(0, j);

            //Verifica se é um palindrome
            if (check_palindrome(sub_sentence_palindrome)) {

                //Sendo um palindrome verifica e salva o de maior tamanho
                if (sub_sentence_palindrome.size() > greater_palindrome.size()) {

                    greater_palindrome = sub_sentence_palindrome;
                }
                break; //Aqui você pode encerrar a busca pois este for só irá decrementar o J e procurar por coisa menores ao palindrome atual
            }
        }
    }

    return greater_palindrome;
}

int main() {

    string greater_palindrome = analyze_sentence("Enquanto ele estava seco de raiva coloco no colo caviar e doces!");

    printf("%s\n", greater_palindrome.c_str());

    system("pause");
    return 0;
}

O código está bastante comentado acredito que será fácil entender. De uma forma geral analiso todas as sequencias de caracteres a partir do primeiro índice da frase e sempre decrementando o tamanho da sequencia investigada. Por exemplo, na frase 'A arara azul é linda!' começo analisando tudo em seguida decremento o tamanho da string em 1 e ai a minha busca fica na string 'A arara azul é linda', em seguida 'A arara azul é lind', e assim sucessivamente. Após fazer isso, me baseado no início da string sendo a primeira posição, incremento o índice de início da sequencia de caracteres e faço a busca a partir de 'arara azul é linda!', e continuo decrementando o tamanho dessa analise em 'arara azul é linda'. Sempre que é formado uma nova sequencia para ser avaliada se é ou não um palíndromo eu verifico o tamanho do palíndromo para salvar apenas a de maior tamanho.
Obs.: O comentário de Mário sobre o algoritmo de Manacher deve ser interessante, pois deve ser algo mais otimizado, não cheguei a ler.
Comment: Obrigado Lucas Arruda! Você me ajudou muito. Vou estudar o código e estudar a lógica. Acredite em min, você me ajudou muito. Obrigado e sucesso nos seus objetivos :)

Maior palíndromo em uma string? C++


Fatal error: Declaration of .. must be compatible with .. PHP (parameter required: extended class of specification)

Question: I'm working on the next version of my language-constraint reconciliation system. I started with this (the abstract function declaration seems to be the problem):
namespace AAABIT;
abstract class LangPrefSet{
    private $LangPrefs;
    public function __construct(){$this->LangPrefs=array();}
    public function add(LangPref $langpref){$this->LangPrefs[]=$langpref;}
    public function langPrefs(){return $this->LangPrefs;}
    abstract public function reconcile(LangPrefSet $other);//←Seems to be throwing an error… We don't strictly need this line, but this is a little concerning…
    protected static function reconcile_LangPrefSets(LangPrefSet_ForUser $UserLangPrefSet,LangPrefSet_Resource $RsrcLangPrefSet,$maxOptions){//…
    }
}
//Following classes are necessary because language similarity is a one-way mapping. Just because resources in Lang A (e.g. Russian) are likely to be readily understandable for speakers/readers of Lang B (e.g. Ukrainian), does not mean that the resources in Lang B (e.g. Ukrainian) are equally intelligible for speakers/readers of Lang A (e.g. Russian)!
class LangPrefSet_For_User extends LangPrefSet{public function reconcile(LangPrefSet_Resource $RsrcLangPrefSet){return self::reconcile_LangPrefSets(self,$RsrcLangPrefSet);}}
class LangPrefSet_Resource extends LangPrefSet{public function reconcile(LangPrefSet_For_User $UserLangPrefSet){return self::reconcile_LangPrefSets($UserLangPrefSet,self);}}

I thought this would work because LangPrefSet_Resource conforms to LangPrefSet; but PHP found this objectionable, throwing the aforementioned error. I thought I might have better luck with an Interface… So I did this:
interface LangPrefSet_Reconcilable{
    public function reconcile(LangPrefSet_Reconcilable $other);
}

Then I made the two classes extending LangPrefSet, implements LangPrefSet_Reconcilable, and commented out the abstract function declaration (after first trying to make that require an LangPrefSet_Reconcilable interface-typed parameter, also which didn't work) — the results are:
Fatal error: Declaration of AAABIT\LangPrefSet_For_User::reconcile() must be compatible with AAABIT\LangPrefSet_Reconcilable::reconcile(AAABIT\LangPrefSet_Reconcilable $other)

— This is not a blocker issue for me, since I can just strip out the abstract function and interface and the system will work fine. However I'm concerned that I might not have understood interfaces/ abstract classes properly!
What is wrong with specifying that a class method overriding abstract function a(ObjB $b) or a similar interface specification, takes as a parameter ObjC $c, where ObjC extends ObjB?
Answer: Your parameter type must be the same in the interface(or abstract class) and where you are implementing the same. right now the interface is LangPrefSet_Reconcilable
and the implementation says LangPrefSet_Resource and LangPrefSet_For_User.
You can either use a 2nd interface like below, or use the same class.
interface LangPrefSetReconcilableDataInteface {
    ...
}

interface LangPrefSet_Reconcilable{
    public function reconcile(LangPrefSetReconcilableDataInteface $other);
}

class LangPrefSet_Resource implements LangPrefSetReconcilableDataInteface {
...
}

class LangPrefSet_For_User implements LangPrefSetReconcilableDataInteface {
...
}

class LangPrefSet_For_User extends LangPrefSet
{
    public function reconcile(LangPrefSetReconcilableDataInteface $RsrcLangPrefSet)
    {
        return self::reconcile_LangPrefSets(self,$RsrcLangPrefSet);
    }
}

class LangPrefSet_Resource extends LangPrefSet
{
    public function reconcile(LangPrefSetReconcilableDataInteface $UserLangPrefSet)
    {
        return self::reconcile_LangPrefSets($UserLangPrefSet,self);
    }
}

Comment: I'm a bit confused by his because you appear to be redeclaring classes.
Regarding your solution with two interfaces, does it have to be this convoluted? As mentioned in my question, this is not a blocker issue for me: I tend to favour beautiful code that is easily maintained, modified and upgraded. With the interfaces/ abstract method declarations, I'm trying to make sure that appropriate errors are thrown if anyone tries to change something in an inadvisable way: if the implementation for this "icing on the cake" is inscrutable at first glance, I might just leave it out!
Answer: The issue may to be that in the abstract class declaration, I am specifying that any LangPrefSet must be acceptable to the reconcile() object method:
abstract public function reconcile(LangPrefSet $other);

— Whereas in the actual method declaration, I am specifying in one case that only a LangPrefSet_Resource would be acceptable, and in the other case, that only a LangPrefSet_For_User would be acceptable.
The object method declarations are therefore incompatible with the abstract method declaration. It seems that the proper application of these interface/abstract method declaration techniques is not to broaden the range of permissible parameter type constraints in classes that implement the interface, since we may achieve this simply by declaring the input restrictions as they ought to be for those specific classes/methods; but rather, interface/abstract method declarations are meant to broaden the range of parameters that may actually be passed to a method that specifies these abstract parameter types.


Laplace transform of integrated geometric Brownian motion

Question: Is there any closed form of the Laplace transform of an integrated geometric Brownian motion ?
A geometric Brownian motion $X=(X_t)_{t \geq 0}$ satisifies $dX_t = \sigma X_t \, dW_t$ where $W=(W_t)_{t \geq 0}$ denotes a Brownian motion and the associated integrated Brownian motion is $\int_0^t X_s \, ds$. The Laplace transform of an integrated gometric Brownian motion is thus
$$ \mathcal{L}(\lambda) = \mathbb{E}\left[e^{-\lambda \int_0^t X_s ds } \right]$$
Answer: What is known is explained in C. Albanese, S. Lawi, Laplace transform of an integrated gometric Brownian motion, MPRF 11 (2005), 677-724, in particular in the paragraph of the Introduction beginning by A separate class of models...
Comment: Try [this](http://www.albanese.co.uk/stochint.pdf).
Comment: Google only points to this very question on MSE when typing the article/book you mentionned.
Comment: Very nice, thanks.
Answer: I would be very surprised (in a good way) if there was a closed form solution of this. Even though it is straight-forward to calculate
$$E\left[\int_0^t X(s) ds\right]$$
the distribution of $$\int_0^t X(s) ds$$ is unknown. And without knowing the distribution, I believe it will be difficult to calculate the expectation. The only thing I can figure out is a lower bound $$E\left[e^{- \lambda \int_0^t X(s) ds} \right] \geq e^{-\frac{2\lambda}{\sigma^2}( e^{\frac{\sigma^2 t}{2}}-1)}$$ which is of little use.
Comment: $\forall s \geq 0, \ \mathbb{E}(X(s)) = x_0$ since it is a martingale. Thus by Jensen $$ \mathbb{E}(e^{-\lambda \int_0^t X(s) ds}) \geq e^{-\lambda \mathbb{E}(\int_0^t X(s)ds)} \geq  e^{-\lambda x_0 t} $$


Compositum of normal extensions is a normal extension

Question: I'm trying to prove that if $ F \subset K, F \subset M $ are normal extensions, $ K,M \subset E $, then $ KM$ is also a normal extension of $ F $.
I tried using the fact that $ F \subset KM $ is a normal extension iff for any $ f \in K[x] $ such that $ f(km) = 0 $ for some $ km \in KM $, $ f $ splits into linear factors in $ KM[x] $. So I would write
$$ f(km) = a_0 + a_1km + \dots + a_n (km)^n = 0$$
$$ g(m) = a_0/k^n + a_1/k^{n-1} m + \dots +a_nm^n = 0 $$
And I thought it would lead me to using the fact that $ F\subset M $ is normal. But $ b_i = a_i/k^{n-i} $ are in $ K $, not necessarily in $ F $.
I'm not sure if that's the right way. I'd appreciate some suggestions
Answer: Let $\sigma$ be a homomorphism $KM \to \overline F$, that fixes $F$. We have $\sigma(KM)=\sigma(K)\sigma(M)$. By assumption we have $\sigma(K) \subset K$ and the same holds for $M$. So we have $\sigma(KM) \subset KM$, which is one characterisation of a normal extension.


Group with an even number of elements.

Question: If $G$ is a group such that $|G|=2n$. Prove that there's an odd number of elements of order 2, and then there's an element which is its own inverse, besides of the identity.
If we consider all the elements of $G$ that have order different than 2, we have two cases: 1) the elements with order greater than 2, and 2) elements with order 1.
For 1). Let $A=\{g\in G: g^k=e, k>2\}$, then if $g\in G$ then $g^{-1}\in G$ (should I prove that the inverse has the same order?), and also $e\not\in G$. Then there's an even number of elements in A, because $g\not = g^{-1}$. So $|A|=2m$ for some $m$.
For 2). The only element of order 1 is the identity, so $B=\{g\in G: g^k=e, k=1\}=\{e\}$ then $|B|=1$.
So $|A|+|B|=2m+1$ like we wanted, but if that happens, the second part of the problem doesn't make sense.
So doing this in a different way, instead of directly counting the elements of B, we consider the complement of A, so $|A^c|=2k$, that way $|G|=|A|+|A^c|=2n$ checks out right. But $A^c=\{g\in G: g^k=e, k\not>2\}=\{g\in G: g^k=e, k=1 or 2\}$, so because the identity is the only element of order 1, then there must be at least one element in $A^c$ of order 2, that means $g_o^2=g_o*g_o=e$ hence $g_o=g_o^{-1}$.
Is this right? What am I doing wrong in the first try?
I know this problem has been solved before in this site, but I really wanted to make it on my own, sorry if this is redundant.
Comment: Your proof is correct for part one.  Just to clarify some of the reasoning, if g does not have order two, then g^{-1} != g (since then g^2 = 1), so these are in fact two _distinct_ elements.  You should mention this when counting elements, otherwise you might be counting some elements more than once.
Comment: possible duplicate of [Group of even order contains an element of order 2](http://math.stackexchange.com/questions/42034/group-of-even-order-contains-an-element-of-order-2)
Comment: @vadim123 I know, please don't close my question, I wish people could help me with what I wrote, plus the link you shared uses a different approach, and I just want to know what I did wrong and why, thanks.
Comment: @breeden there might be a way to know if I'm counting more?
Comment: @Abodi, I guess we could be a little more careful with counting.  You have $A = \{ g \in G | ord(g) > 2 \}$.  This is a finite set.  Take $g \in A$, and note that $g^{-1}$ is in $A$ (easy).  Note that $g \neq g^{-1}$ so we have two elements in $A$.  Remove these two elements from $A$.  If $A$ is now empty, you are done and have removed an even number of elements.  Otherwise, take another element from $g \in A$.  Note that $g^{-1}$ has _not_ already been removed (by uniquness of inverses) and so $g^{-1}$ is now in  $A$.  Take these two elements out.. and so on
Comment: @breeden This is very helpful, thanks!
Comment: Voted to close as a duplicate over the earlier objection because the OP is satisfied and the question is (ultimately) a duplicate. Thus the question (while initially valuable) no longer serves a purpose.
Answer: Your first try is correct. By your proof, you know the number of elements of order 2 is odd, hence can not be zero. This means there exists at least one, say $g$, which is just the element you wanted in the second part.

Group with an even number of elements.


Divergence of laplacian

Question: It seems to me that, in some derivations on fluid dynamic books I am reading, the identity $$\nabla \cdot (\nabla^2 u) = 0 $$ where $u$ is a vector field, is used.
Does this identity exist? Is it true?
Answer: Note: $\nabla^2 u= \nabla(\nabla \cdot u) - \nabla \times (\nabla \times u)$. Taking the divergence gives: $\nabla \cdot(\nabla^2 u)= \nabla^2 (\nabla \cdot u)$. The reason the statement holds in your case is likely that $u$ is assumed to be an incompressible flow field, i.e. $\nabla \cdot u=0$, which is the incompressible continuity equation. Else, it may not hold.
Comment: Why is the divergence of the RHS of the equation equals to that? Is it because "curl is always solenoidal"?
Answer: The definition of vector Laplacian is
$$ \nabla^2 \mathbf{u} = \nabla(\nabla \cdot \mathbf{u}) - \nabla \times (\nabla \times \mathbf{u})
$$
Since curl is always solenoidal, the divergence of the second term is $\mathbf{0}$, so we are left with
$$ \nabla \cdot (\nabla^2 \mathbf{u}) = \nabla^2(\nabla \cdot \mathbf{u})
$$
and it may not be $\mathbf{0}$.
Comment: Thanks, Henry W. The other answer was very similar and I can mark just one... :(
Comment: By "second term", you mean "div curl curl u", and not "curl curl u", right?

Divergence of laplacian


Como fazer o this se referir a um item HTML que chama uma função quando clicado?

Question: Estive lendo vários materiais a respeito do uso do this e seu funcionamento no JavaScript. Vi boas explicações sobre o contexto global, bind, apply e call, mas, ainda assim, não consigo entender como fazer com que ele (o this) passe a se referir a um item da página que, quando clicado, chama uma função (no exemplo abaixo, uma âncora HTML).
A propósito, também já fiz testes usando o event.target, mas sem sucesso.
Qualquer elucidação será muito bem-vinda.
Texto 1

Texto 2

function chamaFuncao(a,b) {
  (...)
  var texto = this.innerText // Aqui, o this sempre retorna a janela.
}

Answer: Acabei percebendo que a solução é, ao invés de chamar a função por meio do href, chamá-la no onclick. Assim, o this aponta para a própria âncora, e não mais para a janela.
Comment: Se tiver uma situação em que precise usar no href, em vez do this você passa um ID na chamada (que inclusive não precisa ser do próprio elemento, pode referenciar qualquer outro). Exemplo: `` e recupera o ID no corpo da função. - De qualquer forma, trabalhar com eventos como `onclick` é o normal numa situação dessas (e nada impede de passar um parâmetro em vez de usar o this neste caso também, se for um elemento diferente do que faz a chamada), comentei só como complemento mesmo.
Comment: Concordo completamente, @Bacco. Inclusive foi isso mesmo que fiz antes de perceber que o problema estava no uso do href. Coloquei IDs como parâmetros e as chamei no corpo da função, exatamente desse jeito que você mencionou e funcionou também. No final das contas, foi mais um aprendizado. E muito obrigado por se dispor a compartilhar conhecimento e pela dica no geral.


AngularJS - Unit test for http get to JSON file

Question: I am trying to write a unit test to test a simple factory that performs a http.get to retrieve a JSON file.
The factory is called within my controller.
Here's a plunker showing my http.get: http://plnkr.co/edit/xg9T5H1Kreo4lwxzRQem?p=preview
Ctrl:
app.controller('MainCtrl', function($scope, $http, factoryGetJSONFile) {

  factoryGetJSONFile.getMyData(function(data) {
    $scope.Addresses = data.Addresses.AddressList;
    $scope.People = data.Names.People;
  });

});

Factory:
app.factory('factoryGetJSONFile', function($http) {
  return {
    getMyData: function(done) {
      $http.get('data.json')
      .success(function(data) {
        done(data);
      })
      .error(function(error) {
        alert('An error occured whilst trying to retrieve your data');
      });
    }
  }
});

Test:
// ---SPECS-------------------------

describe('with httpBackend', function () {
    var app;
    beforeEach(function () {
        app = angular.mock.module('plunker')
    });

    describe('MyCtrl', function () {
        var scope, ctrl, theService, httpMock;

        beforeEach(inject(function ($controller, $rootScope, factoryGetJSONFile, $httpBackend) {
            scope = $rootScope.$new(),
            ctrl = $controller('MyCtrl', {
                $scope: scope,
                factoryGetJSONFile: theService,
                $httpBackend: httpMock
            });
        }));

        it("should make a GET call to data.json", function () {
                console.log("********** SERVICE ***********");
                  httpMock.expectGET("data.json").respond("Response found!");
                //expect(factoryGetJSONFile.getMyData()).toBeDefined();
                httpMock.flush();
            });

    })
});

Error:
TypeError: 'undefined' is not an object (evaluating 'httpMock.expectGET')

Comment: where are you defining the theService object ?
Comment: as your code is now it would only compile if you write factoryGetJSONFile: factoryGetJSONFile  but it would simply call the original service. You have to define a mock service and put it in theService
Answer: You should assign $httpBackend to httpMock in beforeEach like this:
   beforeEach(inject(function ($controller, $rootScope, factoryGetJSONFile, $httpBackend) {
        httpMock = $httpBackend;
        scope = $rootScope.$new();
        ctrl = $controller('MyCtrl', {
            $scope: scope,
            factoryGetJSONFile: factoryGetJSONFile,
            $httpBackend: httpMock
        });
    }));

Comment: why define it in the beforeEach and inside the ctrl parameters?
Comment: tried your code, get an error: Error: Unexpected request: GET /data.json?  Expected GET /data.json   Where is the ? coming from??


No power through daisy chain

Question: I have a Boss BCB 30 pedal board with daisy chain. I have three pedals: TU2, CS3 and DD3. I bought an universal power supply to use with it. I have set the power supply to correct polarity and voltage. I've checked with a voltmeter and it shows 9.13 volt. It also work with each of the pedals, but not if all pedals are connect with daisy chain.
I have tested the daisy chain with my voltmeter to see if there is a connection, and there are. But if I test it with voltmeter when connect, it doesn't show any voltage.
TLDR: daisy chain doesn't deliver power, but wires are sound.
Comment: Is the "daisy chain" a separate cable that plugs into the power supply and then into all the pedals? If so that piece might be broken.
Comment: @ToddWilcox Yes, it's a separate cable that came with the [BCB 30 pedal board](http://www.soundaffectspremier.com/blog/wp-content/uploads/2014/10/Boss-BCB-30-Pedal-Board.jpg). I have tested the cable with a voltmeter, and it seems to have connection if I just tests each ends of cable (female plug to each of the male plug).
Comment: But if you plug it in, you don't see 9V at the outputs with the tester?
Comment: @ToddWilcox That's correct. Shows connection if I just test cable. Shows 0 if I test volt when plugged into power socket.
Answer: Something's wrong with your daisy-chain cable. Likely the end the plugs into the power supply has the wrong plug and/or is not making contact with the power supply output.
Comment: May it be that I might need an original Boss adapter? This universal adapter I have fits perfectly into the daisy chain and I can change polarity to make it right, so I guess it should work?
Comment: The fact that it doesn't work is more significant than the supposition that it should work.
Comment: You answer made me double check the daisy chain. It seems like the pin inside the daisy chain is a bit smaller than the inside of the adapter plug. Making me guess that Boss has made their adapter plug a little bit different than the universal ones. Can I just put some alumnium foil inside the plug, or would it be a bad idea?
Comment: I can't imagine the correct cable costing that much. Using aluminum foil as a conductor is almost certainly a fire hazard.
Comment: Kinda needed a quick fix, but I'll wait for the original one. Thanks for helping out!

No power through daisy chain


Understanding Piano Sheet Music w/ Guitar Instructions?

Question: Some piano pieces I want to play also include guitar instructions, with tab images and chord letters above the grand staff. I am trying to tell if the chord instructions only apply to guitar, or if I have to follow them for piano, also?
I am including an image of how this applies to the Scarborough Fair sheet music. In it, you can see that there are chord instructions for G and Em chords, but I don't know if they have to be followed for piano in addition to guitar.

Thanks for any help! :)
Answer: It's not that you have to follow them. As a pianist you could just ignore them. But if you play the notes written on the staff you'll be playing those chords anyway.
So in the first measure there's a G chord diagram for a guitar. And the notes in the staff all outline a G chord as well.
Though yes, those diagrams are meant for guitarists usually because for pop songs like this it may be more stylistically and ergonomically appropriate for a guitarist to strum a chord rather than play the separate bass and chord parts as written for piano.
If you wanted to, you could use the name above the diagram as hint for what chord you're playing. Or you could use it the way a guitarist would and make up your own comping rhythm using that chord.
Or ignore it, your choice.
Answer: They don't have to be followed, because they're there specifically for any guitarist. Having said that, the staves you play written out just for the piano (and vox) will reflect the chords shown in the boxes.
Some piano players will use the chord names (not the windows, obviously) in order to use their clues to produce their own, usually left hand, accompaniment.
Incidentally, the boxes/windows showing the chord shapes for guitar generally show the basic chord shape, which beginner guitarists will be more familiar with. They are not sacrosanct, and most guitarists will read the chord names and play their own voicings of those chords. As in - don't bother to try playing the exact chord notes shown in the window on the piano, it's just not necessary - although it can work.
Answer: If you only have the upper line (like a fake book would have), you play the melody in the right hand (usually) and the chords in the left hand. The style of chord (oom-pah or block chords or Alberti Bass or come combination) is up to you. It should follow the style of the song. You may have to use some inversions in the chords (mostly first inversions) to create a good bass line. The bass line should make adequate (hard to be good or great) with the melody.
It's also possible to add a harmony to the melody if it sounds good.
It's tricky to do this while sight reading but not to hard if you practice a piece a couple of times.
Answer: Based on the incomplete view of the sheet music, I think you should follow the 2 bottom staffs for piano/keyboard instead. It includes melody on the right hand and accompanying chord on the left hand (in arpeggio style).
I assume the sheet music is for multiple instruments. From top to bottom:

Guitar chord for accompaniment
Vocal line with lyrics
Piano/keyboard for accompaniment

But to answer the asked question directly: well, you can try to improvise with shown chord, not strictly following it. But the chord gives a hint what to play according to how the music supposed to be played.


"No such session" / "chrome not reachable" error when running Chrome in parallel in Jenkins

Question:
I am getting the issue with running automation tests on Chrome in Jenkins using parallel_test gem (also use with Capybara, selenium - Ruby language). I'm running it in headless mode with Xvfb. However, most of all test scenarios failed due to 'no such session' or 'chrome not reachable' errors.
This is my run command on test job in Jenkins:
xvfb-run -a --server-args='-screen 0 1680x1050x24' bundle exec parallel_cucumber features/ -n 4 -o '-t ~@ignore -p jenkins_chrome'

This is my register_driver in env.rb:
Capybara.register_driver :chrome do |app|
    Capybara::Selenium::Driver.new(app,
         browser: :chrome,
         desired_capabilities: {
             "chromeOptions" => {
                 "args" => %w{ --start-maximized --disable-impl-side-painting --no-sandbox }
             }
         })
  end

And this is error message:
(Driver info: chromedriver=2.20.353124 (035346203162d32c80f1dce587c8154a1efa0c3b),platform=Linux 4.0.5 x86_64) (Selenium::WebDriver::Error::NoSuchDriverError)
./features/step_definitions/view_a_profile.rb:204:in `/^user has signed in as "([^"]*)"$/'

Someone said the errors are due to xvfb, some said due to Chrome can't run in parallel.
Have anyone experienced this issue? How can I solve this problem?
Answer: Chrome with chromedriver and xvfb won't run on any
   suse. (probably not related here)
Usually on build servers everything gets executed as root, which
   causes this exact error for me with chrome. (for this I am searching for a workaround myself)


Using GP_fit() of GPfit package in R

Question: I am trying to work with Gaussian process through GPfit package of R but every time I use GP_fit() of this package, either it gets hanged or throws error which is like this:
Error in chol.default(Sig) :
  the leading minor of order 2 is not positive definite.

My input matrix looks like this:
     visitLength       hour
   [1,] 0.0241057543 0.73913043
   [2,] 0.0413780103 0.91304348
   [3,] 0.0432866771 0.30434783
   [4,] 0.0000000000 0.17391304
   [5,] 0.0639756822 0.60869565
   [6,] 0.1239219567 0.86956522
   [7,] 0.0000000000 0.34782609
   [8,] 0.0389038126 0.17391304
   [9,] 0.0886469674 0.04347826
     .      .             .
     .      .             .

and so on. There are about 200 rows in this input matrix. My output matrix looks like this:
     [,1]
   [1,]    0
   [2,]    0
   [3,]    1
   [4,]    0
   [5,]    1
   [6,]    0
   [7,]    0
   [8,]    1
   [9,]    0

and this too has same number of rows as the input matrix. Now when I use:
model = GP_fit(input_mat,outpt_mat)

either it gets hanged or the above mentioned error is thrown. I have no idea why it gets hanged when there are only 2000 rows and also I have scaled values in range [0,1] or it throws as error which does not clarify the meaning or reason. Can anyone provide some information about what and why is it happening?
UPDATE: The signature of GP_fit() is:
GP_fit(X,Y)

where
X is the (n x d) design matrix
Y is the (n x 1) vector of simulator outputs.

One of the example code given in the package documentation is like this:
 library(GPfit)
n = 5; d = 1;
    computer_simulator <- function(x){
    x = 2*x+0.5;
    y = sin(10*pi*x)/(2*x) + (x-1)^4;
    return(y)
    }
    set.seed(3);
    library(lhs);
    x = maximinLHS(n,d);
    y = computer_simulator(x);
    GPmodel = GP_fit(x,y);
    print(GPmodel)

Comment: Since `y` isn't even remotely Gaussian, trying to model it as a Gaussian process is inherently hopeless.  What are you really trying to accomplish?
Comment: I don't know the package you're talking about, but `chol.default` is the Cholesky decomposition function. It seems something about your input array is creating a singular matrix within the code. I would look for `NA` values and/or make sure you are not sending collinear arrays.
Comment: @gmacfarlane I have checked all the values and none of them is `NA`. Also I have added some extra information regarding the function in my post above.
Comment: could the values of only 1 or 0 in Y for me create issues?
Answer: Do you have identical rows in you input matrix?
If yes, try to remove them, e.g. by adding a small noise.
Comment: This looks like a genuine effort to help the OP to me, @Andre.  However, it's not likely to be correct: `GP_fit` generally has no problems with repeated rows (nor should it, in theory).

Using GP_fit() of GPfit package in R


Is there a powershell command for azure functions

Question: Is there a powershell for azure functions? In azure cli there are commands to manage azure function. but are there for powershell like get-azfunction...
Answer: The PowerShell module for Functions is here, currently in preview: https://www.powershellgallery.com/packages/Az.Functions


Intepretation of the fact that $\operatorname{stab}_G(g \cdot x) = g\operatorname{stab}_G(x)g^{-1}$

Question: I know how to prove the fact that $\operatorname{stab}_G(g \cdot x) = g\operatorname{stab}_G(x)g^{-1}$ but I'm having trouble finding meaning behind it. Does someone know why this is useful or has an intuitive view of this matter?
Comment: You can think of it as a change of base point. For example, if $X$ is your Cayley graph then left-multiplication by $g$ moves everything by $g$, so to find the elements which stabilise $g\cdot x$ you head along the path $g^{-1}$, find everything which fixes the point $x$, and then retract your steps back to $g\cdot x$. Indeed, when thinking about fundamental groups, conjugation $\pi_1(S, x)^g$ corresponds *precisely* to change of base point, $\pi_1(S, g\cdot x)$.
Comment: One importance is that if we know the stabilizer of a point $x$, then we suddenly know it for every point in the orbit of $x$, and in particular they are equinumerous.
Answer: Here's an intuition.
Suppose you are standing on the point $g \cdot x$.
Now three things happen quickly in succession:

$g^{-1}$ moves you from $g \cdot x$ to $x$;
Someone spins the space around $x$ but leaves you fixed in position at $x$ (although perhaps leaving you somewhat dizzy)
And then $g$ moves you back from $x$ to $g\cdot x$.

The result: You started standing at $g \cdot x$, and you're still standing at $g \cdot x$.
Comment: Thanks for the fix @Berci


Base64 encoding of CryptoDigest / SHA1 - string doesn't match the result from Java / Python

Question: I'm trying to get message digest of a string on IOS. I have tried nv-ios-digest 3rd party Hash lib but still no use.
Below is the function i'm using to get the base64encoded string of a message digest.
-(NSString*) sha1:(NSString*)input //sha1- Digest
{
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1(data.bytes, data.length, digest);
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++){
        [output appendFormat:@"%02x", digest[i]];//digest
    }
    return [NSString stringWithFormat:@"%@",[[[output description] dataUsingEncoding:NSUTF8StringEncoding]base64EncodedStringWithOptions:0]]; //base64 encoded

}

Here is my sample input string - '530279591878676249714013992002683ec3a85216db22238a12fcf11a07606ecbfb57b5'
When I use this string either in java or python I get same result - '5VNqZRB1JiRUieUj0DufgeUbuHQ='
But in IOS I get 'ZTU1MzZhNjUxMDc1MjYyNDU0ODllNTIzZDAzYjlmODFlNTFiYjg3NA=='
Here is the code I'm using in python:
import hashlib
import base64

def checkForDigestKey(somestring):
     msgDigest = hashlib.sha1()
     msgDigest.update(somestring)
     print base64.b64encode(msgDigest.digest())

Let me know if there is anyway to get the same result for IOS.
Answer: You are producing a binary digest in Python, a hexadecimal digest in iOS.
The digests are otherwise equal:
>>> # iOS-produced base64 value
...
>>> 'ZTU1MzZhNjUxMDc1MjYyNDU0ODllNTIzZDAzYjlmODFlNTFiYjg3NA=='.decode('base64')
'e5536a65107526245489e523d03b9f81e51bb874'
>>> # Python-produced base64 value
...
>>> '5VNqZRB1JiRUieUj0DufgeUbuHQ='.decode('base64')
'\xe5Sje\x10u&$T\x89\xe5#\xd0;\x9f\x81\xe5\x1b\xb8t'
>>> from binascii import hexlify
>>> # Python-produced value converted to a hex representation
...
>>> hexlify('5VNqZRB1JiRUieUj0DufgeUbuHQ='.decode('base64'))
'e5536a65107526245489e523d03b9f81e51bb874'

Use base64.b64encode(msgDigest.hexdigest()) in Python to produce the same value, or Base-64 encode the digest bytes instead of hexadecimal characters in iOS.
Comment: @vivianaranha: convert the `uint8_t digest` array to base 64 instead. [how to convert array of bytes to base64 String in iphone?](http://stackoverflow.com/q/6466083) looks relevant.
Comment: @vivianaranha: you already *have* binary, you are converting that to hex.


Which AIC value to use from R's sarima() function for model comparison

Question: I'm using R's 'astsa' package and I get the following output from sarima.
Which AIC value would I use to compare this model (let's call it A) against others? When trying another model (B), model A's fit$AIC (858.19) is greater than model B's, but model A's AIC (12.38841) is less than model B's, so I'm not sure which model to choose.
What's the difference between the two AIC's, AICc's, and BIC's? I've checked the sites below, among others, but haven't been able to figure it out. Any help is much appreciated.
http://stat.ethz.ch/R-manual/R-patched/library/stats/html/arima.html
http://www.inside-r.org/packages/cran/astsa/docs/sarima
<code>$fit
Series: xdata
ARIMA(0,1,1)(1,1,1)[12]

Coefficients:
         ma1    sar1     sma1
     -0.3282  0.5529  -0.8835
s.e.   0.3290  0.4751   0.8635

sigma^2 estimated as 82513:  log likelihood=-425.1
AIC=858.19   AICc=858.93   BIC=866.5

$AIC
[1] 12.38841

$AICc
[1] 12.42448

$BIC
[1] 11.48327
</code>
Answer: Akaike's Information Criterion (AIC): Formally, AIC is defined as $2 \log L_k+ 2k$ where $L_k$ is the maximized log likelihood and $k$ is the number of parameters in the model. For the normal regression problem, AIC is an estimate
of the Kullback-Leibler discrepancy between a true model and a candidate model.
AIC, Bias Corrected (AICc): A corrected form, suggested by Sugiura (1978), and expanded by Hurvich and Tsai (1989), can be based on small-sample distributional results for the linear regression model
Bayesian Information Criterion (BIC): is also called the Schwarz Information Criterion (SIC), for an approach yielding the same statistic based on a minimum
description length argument. Various simulation studies have tended to verify that BIC does well at getting the correct order in large samples, whereas
AICc tends to be superior in smaller samples where the relative number of
parameters is large.
Example:
<code>sarima(gnpgr, 1, 0, 0) # AR(1)
$AIC: -8.294403 $AICc: -8.284898 $BIC: -9.263748

sarima(gnpgr, 0, 0, 2) # MA(2)
$AIC: -8.297693 $AICc: -8.287854 $BIC: -9.251711
</code>
The AIC and AICc both prefer the MA(2) fit, whereas the BIC prefers the
simpler AR(1) model. It is often the case that the BIC will select a model
of smaller order than the AIC or AICc. It would not be unreasonable in this
case to retain the AR(1) because pure autoregressive models are easier to
work with.
Comment: Would you have a view on why is AIC an estimate of the KL information quantity rather than an estimate of the mean expected log-likelihood of a model?
Comment: Have a look at [this book](http://books.google.ca/books?id=fT1Iu-h6E-oC&printsec=frontcover&dq=Model+Selection+and+Multi-Model+Inference&hl=en&sa=X&ei=yGPRUoSSNMKY2QXps4Bw&ved=0CDAQ6AEwAA#v=onepage&q=Model%20Selection%20and%20Multi-Model%20Inference&f=false).
Answer: The first AIC from the sarima command comes from the formal definition of AIC, the second version comes from a reduced form, which is only applicable in the context of normal regression, see:
https://en.wikipedia.org/wiki/Akaike_information_criterion#Comparison_with_least_squares


Recuperando valores MultiSelectList MVC

Question: Não estou sabendo como tratar os dados recebidos via MultiSelectList. Além disso, só consigo selecionar mais de uma opção na View se pressiono o CTRL. Existe uma forma do usuário conseguir clicar em mais de um valor sem necessariamente segurar essa tecla?
View Create

  Combos @Html.ListBox("Combos", new MultiSelectList(ViewData["Combos"] as System.Collections.IEnumerable, "id", "nome", Model.Combos.Select(x => x.id).AsEnumerable()))

Populando MultiSelectList no Controller
CombosAplicacao bdCombos;
bdCombos = CombosAplicacaoConstrutor.CombosAplicacaoEF();
ViewData["Combos"] = bdCombos.ListarTodos();

Em todo o resto da minha aplicação, trabalho com SelectList, pois tenho uma relação normalmente de 1 - n. Apenas no caso dos Combos que tenho uma relação de muitos para muitos.

No caso das SelectList trabalho da seguinte forma:
View Create
@Html.DropDownList("Sala", ViewData["Sala"] as SelectList)

Populando pelo Controller
SalaAplicacao bdSala;
bdSala = SalaAplicacaoConstrutor.SalaAplicacaoEF();
var listSala = new SelectList(bdSala.ListarTodos(), "ID", "Nome");
ViewData["Sala"] = listSala;

Recuperando e salvando no banco pelo Controller
 [AcceptVerbs(HttpVerbs.Post)]
 public PartialViewResult Create(CONGRESSO_Cursos cursos, FormCollection dados)
 {
     SalaAplicacao bdSala;
     bdSala = SalaAplicacaoConstrutor.SalaAplicacaoEF();
     cursos.CONGRESSO_Sala = bdSala.ListarPorId(dados["Sala"]);
     bdcursos.Salvar(cursos);
 }

Answer: Se você recuperar o dados["Combos"], vai recuperar todos que foram selecionados, então basta dar um split.
var combos = dados["Combos"].ToString().Split(',');
foreach(var combo in combos){
   //vai percorrer todos os combos selecionados.
}

Recuperando valores MultiSelectList MVC


how to get input from scanner to my private viarable string in another class?

Question: this is my first assignment, how to get input from scanner to  my private viarable string in another class?

Create Author class as the description mentioned below.(i already done it)
Create a test class called TestAuthor to test all the public methods in class Author. Below
is the example of the output.

the questions
this is my author code
package assignment1;

public class Author {

    //attribute of the class
    private String name;
    private String email;
    private char gender;

    //constructor
    public Author(String name, String email, char gender) {

        this.name = name;
        this.email = email;
        this.gender = gender;
    }

    //methods
    public String getName() {

        return name;
    }

    public String getEmail() {

        return email;
    }

    public void setEmail(String newEmail) {

        this.email = newEmail;

    }

    public char getGender() {

        return gender;

    }
    //method to get data from author object
    public String toString() {

        return "Author[name="+name+", email="+email+", gender="+gender+"]";

    }

}

this is my testauthor
and i get this error
'The method getName() in the type Author is not applicable for the arguments (String)'

package assignment1;

import java.util.Scanner;  // Import the Scanner class

public class TestAuthor {

    public static void main (String[] args) {

        //test constructor
        Author newAuthor = new Author();

         Scanner input = new Scanner(System.in);
         System.out.println("Please enter name : ");
         String name = input.nextLine();
            newAuthor.getName(name);
            System.out.println("Name : "+newAuthor.getName());

    }

}

TIA
Comment: Just remove the `name`  argument in the function call. `getName` method does not require any parameter.
Answer: You need to add setter method for name property in Author class like this:
package assignment1;
public class Author {
//attribute of the class
private String name;
private String email;
private char gender;

//constructor
public Author(String name, String email, char gender) {

    this.name = name;
    this.email = email;
    this.gender = gender;
}

//methods
public String getName() {

    return name;
}

public void setName(String name){
  this.name = name;
 }

public String getEmail() {

    return email;
}

public void setEmail(String newEmail) {

    this.email = newEmail;

}

public char getGender() {

    return gender;

}
//method to get data from author object
public String toString() {

    return "Author[name="+name+", email="+email+", gender="+gender+"]";

}

}
In TestAuthor class you need to call setter to set value then call like this :
package assignment1;
import java.util.Scanner;  // Import the Scanner class
public class TestAuthor {
public static void main (String[] args) {

    //test constructor
    Author newAuthor = new Author();

     Scanner input = new Scanner(System.in);
     System.out.println("Please enter name : ");
     String name = input.nextLine();
        newAuthor.setName(name);
        System.out.println("Name : "+newAuthor.getName());

}

}
Answer: thank you for the help, i got the answer
this is my testAuthor file
package assignment1;

import java.util.Scanner;  // Import the Scanner class

public class TestAuthor {

    public static void main (String[] args) {

        //set variables()
        String name;
        String email;
        char gender;

        //Scanner input object
        Scanner input = new Scanner(System.in);

        //get user input
        System.out.println("Please enter Name : ");
        name= input.nextLine();

        System.out.println("Please enter Email : ");
        email= input.nextLine();

        System.out.println("Please enter Gender : ");
        gender= input.nextLine().charAt(0);

        //
        Author newAuthor = new Author(name,email,gender);
        name = newAuthor.getName();
        email = newAuthor.getEmail();
        gender = newAuthor.getGender();

        //output toString
        System.out.println(newAuthor.toString());

        //set new email
        System.out.println("Please change Email : ");
        String newEmail= input.nextLine();
        newAuthor.setEmail(newEmail);

        //output
        System.out.println("Name : "+newAuthor.getName());
        System.out.println("Email : "+newAuthor.getEmail());
        System.out.println("Gender : "+newAuthor.getGender());

    }

}

Comment: Cool, but you mention in question having trouble getting input value for private property value in a different class, anyway it works for you well.
Comment: Yeah sorry, i don't know how to say the problem, anyways thank you for the help


Save a $_GET value because I use another one in PHP

Question: Look at the code below and you will onderstand ;)
Multiplecompetitions.php

competition 1!

competition 2!

competition 3!

Subscribe.php
<?php
if ($_SESSION['login']== "OK" ) {
  $Competition = $_GET[' Competition '];
  echo $Competition;

  if (isset($_GET[' Competition '])) {}
?>

Subscribe

And more code…
As you can see, I will use another $_GET but I want to save the first one somewhere. How do I do this?
At the moment the first $_GET value gets overwritten by the new one.
Comment: Take a minute and explain your issue thoroughly and clearly. Not everyone will see your question and "onderstand".
Comment: I hope all those extra spaces are not on your code.
Comment: isn't it already saved in `$Competition`?
Comment: The spaces are just a mistake because I placed it in Word first :p
The issue is that I want to save the $_GET somewhere. People who understand $_GET will understand me I think.
Comment: We "understand `$_GET`". We *don't* understand what exactly you mean by "saving it somewhere" without more context. Sessions? Database? Files? URL?
Comment: Dagon understood me so no morep problems :p
Answer: My 'guess' as to what you want:
use & and add as many  variables as you like to the url:
 ... Subscribe...

Comment: Thank you a lot! You understood what I was trying to say :D I'll rep you as soon as I can :)
Answer: First, don't put spaces in the parameter name, it's not permitted. Also you should remove the space between $ and Competition (line 2).
You can have only 1 variable with the name Competition. When you get it, you store it in the $Competition variable, so you can later change $Competition without affecting $_GET['Competition']
Generally your question isn't very clear, please give more details


I don't know to find subgroups.

Question: $G=\mathbb Z_3\times\mathbb Z_5$
I don't know to find a subgroup.
Give me an example a subgroup of $G$ how to find that ?
Comment: $\mathbb Z_3$ is a subgroup; $\mathbb Z_5$ is a subgroup. These are the only non-trivial subgroups of $G$.
Comment: Sure. $\{(0,0)\}$, for instance, is a subgroup.
Comment: Is $G$ cyclic ?
Comment: any a subgroup not identity ?
Comment: Use cyclic to find a subgroup ?
Comment: cyclic groups have certain subgroups
Comment: if i find a generator$(a)$ of $G$ then $$ is a subgroup of $G$.
Comment: No $=G$ in your case.You have to find a generator $a$ of $G$ and then $$ is a subgroup of $G$ for every positive $n| |G|$
Answer: There are exactly 4 subgroups

$G$ itself is a subgroup of $G$
$\{(0,0)\}$ is a subgroup of $G$.
$\mathbb{Z}_3\times\{0\}$ is a subgroup of $G$
$\{0\}\times\mathbb{Z}_5$ is a subgroup of $G$.

There are no more subgroups of $G$.
How we find those? The group $G$ is a cyclic group because it is generated by $(1,1)$, hence every subgroup is a cyclic group as well. So you just take an element in $a\in G$ and you have that $\left<a\right>$ is a subgroup of $G$ (and every subgroup is of that form).
$G$ has 15 elements, but some of the elements define the same group (for example $\left<(1,0)\right> = \left<(2,0)\right> = \mathbb{Z}_3\times\{0\}$.
You can go over all elements and confirm that those 4 subgroups I mentioned before are the only subgroups of $G$.
Answer: Because $(3,5)=1$, $G$ is cuclic and $([1]_3,[1]_5)$ is a generator of $G$.
Now as I commented for every positive $n| |G|=15$ there exists a subgroup of $G$ the one that is generated by $([1]_3,[1]_5)^n$.So we have:
$1)$ for $n=1$:$<([1]_3,[1]_5)>=G$
$2)$ for $n=3$ :$<([0]_3,[3]_5)>=\{0\}\times\mathbb{Z_5}$
$3)$for $n=5$:$<([2]_3,[0]_5)>=\mathbb{Z_3}\times\{0\}$
$4)$for $n=15$:$<([0]_3,[0]_5)>=\{0,0\}$
Comment: that's a great answer why downvote?

I don't know to find subgroups.


jQuery each function not working

Question: I've got some p tags with the class PointsToggle

POINTS STATEMENT - AVAILABLE 7AM TOMORROW

SOME OTHER TEXT

And some jQuery like this
$('.PointsToggle').each(function() {
if ($(this).text = 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
    $(this).css('width', '510px');
}
else {
    $(this).css('width', '20px');
}
})

But I can't seem to get it to work
Any ideas?
Thanks
Jamie
Answer: $('.PointsToggle').each(function() {
  var $this = $(this);
  if ($this.text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
    $this.width(510);
  } else {
    $this.width(20);
  }
})

Comment: well, I meant catch...catch into a variable to cache the value.
Comment: Catch `$(this)` into a local variable at the start of function.
Answer: You are using = which means assign.  Try == instead.
Answer: .text() is a function, so you're missing some parenthesis when calling it, like this:
if ($(this).text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {

Or a bit simpler overall in jQuery 1.4+:
$('.PointsToggle').width(function() {
 return $(this).text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW' ? 510 : 20;
});

Answer: $(document).ready() {
    $('.PointsToggle').each(function() {
        if($(this).html() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
            $(this).width(510);
        } else {
            $(this).width(20);
        }
    })
});

EDIT:
If it's possible I would have the code generating the html add another class. Then this can all be done with css. For example:

POINTS STATEMENT - AVAILABLE 7AM TOMORROW

Answer: This will work:
$('.PointsToggle').each(function() {
if ($(this).text() == 'POINTS STATEMENT - AVAILABLE 7AM TOMORROW') {
    $(this).css('width', '510px');
}
else {
    $(this).css('width', '20px');
}
})

jQuery each function not working


Save and Load image SQLite C#

Question: I'm trying to save and load images with SQLite with an app on WinForm with CF. I found a way to save an image into the db but I don't know if it's right because I couldn't find a way to load the image stored in the db.
I have a code to convert my image into a Base64:
public void ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format){
        using (MemoryStream ms = new MemoryStream()){
            // Convert Image to byte[]
            image.Save(ms, format);
            byte[] imageBytes = ms.ToArray();

            // Convert byte[] to Base64 String
            string base64String = Convert.ToBase64String(imageBytes);
            SaveImage(base64String);
        }
    }

This is my code to save the image into the db:
void SaveImage(string pic){
        string query = "insert into Table (Photo) values (@pic);";
        string conString = @" Data Source = \Program Files\Users.s3db ";
        SQLiteConnection con = new SQLiteConnection(conString);
        SQLiteCommand cmd = new SQLiteCommand(query, con);
        cmd.Parameters.Add("@pic",DbType.String);
        con.Open();
        try{
            cmd.ExecuteNonQuery();
        }
        catch (Exception exc1){
            MessageBox.Show(exc1.Message);
        }
        con.Close();
    }

I have a code to make the opposite of ImageToBase64 but first I need to load the image from the db. Any idea to do that?
EDIT I am trying to use the blob to save the image now as Charlie suggested. I tried this code:
Image photo = new Bitmap(@"\Photos\Image20120601_1.jpeg");
SaveImage(photo);

void SaveImage(Image pic){
string conString = @" Data Source = \Program Files\Users.s3db ";
SQLiteConnection con = new SQLiteConnection(conString);
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandText = String.Format("INSERT INTO Table (Photo) VALUES (@0);");
SQLiteParameter param = new SQLiteParameter("@0", System.Data.DbType.Binary);
param.Value = pic;
cmd.Parameters.Add(param);
con.Open();
try{
    cmd.ExecuteNonQuery();
}
catch (Exception exc1){
    MessageBox.Show(exc1.Message);
}
con.Close();}

But when I ExcecuteNonQuery() it catch an error of InvalidCastException.
Any suggest?
SOLUTION This code save an image into the database and then it load the image to show it in a pictureBox:
namespace ImagenSQLite
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Image photo = new Bitmap(@"\Photos\Image20120601_1.jpeg");
            byte[] pic = ImageToByte(photo, System.Drawing.Imaging.ImageFormat.Jpeg);
            SaveImage(pic);
            LoadImage();
        }

        public byte[] ImageToByte(Image image, System.Drawing.Imaging.ImageFormat format){
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();
                return imageBytes;
            }
        }
        //public Image Base64ToImage(string base64String)
         public Image ByteToImage(byte[] imageBytes)
        {
            // Convert byte[] to Image
            MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image image = new Bitmap(ms);
            return image;
        }
        /***************** SQLite **************************/
        void SaveImage(byte[] imagen){
            string conStringDatosUsuarios = @" Data Source = \Program Files\GPS___CAM\Data\DatosUsuarios.s3db ";
            SQLiteConnection con = new SQLiteConnection(conStringDatosUsuarios);
            SQLiteCommand cmd = con.CreateCommand();
            cmd.CommandText = String.Format("INSERT INTO Empleados (Foto) VALUES (@0);");
            SQLiteParameter param = new SQLiteParameter("@0", System.Data.DbType.Binary);
            param.Value = imagen;
            cmd.Parameters.Add(param);
            con.Open();

            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (Exception exc1)
            {
                MessageBox.Show(exc1.Message);
            }
            con.Close();
        }
        void LoadImage(){
            string query = "SELECT Photo FROM Table WHERE ID='5';";
            string conString = @" Data Source = \Program Files\Users.s3db ";
            SQLiteConnection con = new SQLiteConnection(conString);
            SQLiteCommand cmd = new SQLiteCommand(query, con);
            con.Open();
            try
            {
                IDataReader rdr = cmd.ExecuteReader();
                try
                {
                    while (rdr.Read())
                    {
                        byte[] a = (System.Byte[])rdr[0];
                        pictureBox1.Image = ByteToImage(a);
                    }
                }
                catch (Exception exc) { MessageBox.Show(exc.Message); }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            con.Close();
        }
    }
}

Thanks for your help!
Comment: Does this answer your question? [How do i store and retrieve a blob from sqlite](https://stackoverflow.com/questions/625029/how-do-i-store-and-retrieve-a-blob-from-sqlite)
Answer: To load the image from the database, you use a SQL select statement to get the data back, just like you would for any other kind of data. The base64-encoded image is stored as a string in the SQLite database. So you will retrieve it as a string, just like if you were storing any other string (like, for example, your name) in the database.
string LoadImage() {
    string query = "select Photo from Table;";
    string conString = @" Data Source = \Program Files\Users.s3db ";
    SQLiteConnection con = new SQLiteConnection(conString);
    SQLiteCommand cmd = new SQLiteCommand(query, con);
    string base64EncodedImage = null;
    con.Open();
    try {
        IDataReader reader = cmd.ExecuteReader();
        reader.Read(); // advance the data reader to the first row
        base64EncodedImage = (string) reader["Photo"];
        reader.Close();
    }
    catch (Exception ex) {
        MessageBox.Show(ex.Message);
    }
    con.Close();
    return base64EncodedImage;
}

Like your saving code, my example code to load the image uses only one image saved to the table. To load and save more than one image, you would need to insert an ID field into the table, and then use a where clause on your SQL select statement.

I'm not sure that I, personally, would store the image as a base64-encoded string. The string representation of the image will be much larger than the binary representation. SQLite supports the BLOB data type, so I would look into using that.
Comment: Charlie, thanks for your answer. I tried your code but in the line where you cast the reader into string it catch an error of CastInvalidException. This is my line `base64EncodedImage = (string)reader["Photo"];`. Maybe I'm not saving successfully the image, could it be?
Comment: Maybe the problem is that the Photo field is blob, could that be?
Comment: If I don't store the picture as base64 I should pass the image directly to the database? I should put ´SaveImage(Image Pic)´ and ´cmd.Parameters.Add("@pic",DbType.Binary);´?
Comment: I wasn't asking if my field is blob, I know that. I was asking if the problem could it be because I have the field declared as blob. I am trying to not use the Base64. I'm going to edit my post now
Answer: Here is sample Code in VB.net:
Imports System.IO
Imports System.Data.SQLite

Public Class Form1

    'Image BLOB Functions:'
    Private Function BlobToImage(ByVal blob)
        Dim mStream As New System.IO.MemoryStream
        Dim pData() As Byte = DirectCast(blob, Byte())
        mStream.Write(pData, 0, Convert.ToInt32(pData.Length))
        Dim bm As Bitmap = New Bitmap(mStream, False)
        mStream.Dispose()
        Return bm
    End Function

    'USE THIS FUNCTION TO CREATE A BLOB FROM AN IMAGE FILE'
   Public Overloads Function ImageToBlob(ByVal id As String, ByVal filePath As String)
        Dim fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
        Dim br As BinaryReader = New BinaryReader(fs)
        Dim bm() As Byte = br.ReadBytes(fs.Length)
        br.Close()
        fs.Close()
        'Create Parm'
        Dim photo() As Byte = bm
        Dim SQLparm As New SQLiteParameter("@image", photo)
        SQLparm.DbType = DbType.Binary
        SQLparm.Value = photo
        Return SQLparm
    End Function

    'USE THIS FUNCTION TO CREATE A BLOB FROM AN IMAGE VARIABLE IN MEMORY'
    Public Overloads Function ImageToBlob(ByVal id As String, ByVal image As Image)
        Dim ms As New MemoryStream
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
        'Create Parm'
        Dim photo() As Byte = ms.ToArray()
        Dim SQLparm As New SQLiteParameter("@image", photo)
        SQLparm.DbType = DbType.Binary
        SQLparm.Value = photo
        Return SQLparm
    End Function

    'USE THIS SUB TO CREATE A DB AND TABLE'
    Private Sub btnCreateDB_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim SQLconnect As New SQLiteConnection()
        Dim SQLcommand As New SQLiteCommand
        SQLconnect.ConnectionString = "Data Source = " & Application.StartupPath & "\imgdb.sqlite3;"
        SQLconnect.Open()
        SQLcommand = SQLconnect.CreateCommand
        'SQL Query to Create Table'
        SQLcommand.CommandText = "CREATE TABLE foo(id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, description TEXT, image BLOB);"
        SQLcommand.ExecuteNonQuery()
        SQLcommand.Dispose()
        SQLconnect.Close()
    End Sub

    'USE THIS SUB TO INSERT IMAGE INTO SQLITE DB.  IT GETS AN id INTEGER FROM
    Textbox1'
    Private Sub btnInsertImage_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim d As New OpenFileDialog
        d.Filter = "image (*.png)|*.png|(*.jpg)|*.jpg|All files|*.*"

        If d.ShowDialog() = DialogResult.OK Then
            Dim myimage As Bitmap = Clipboard.GetImage()

            Dim SQLconnect As New SQLite.SQLiteConnection()
            Dim SQLcommand As New SQLiteCommand
            SQLconnect.ConnectionString = "Data Source = " & Application.StartupPath & "\imgdb.sqlite3;"
            SQLconnect.Open()
            SQLcommand = SQLconnect.CreateCommand
            'Insert Image, DO NOT single-quote @image'
            SQLcommand.CommandText = "INSERT INTO foo (id,image) VALUES('" + TextBox1.Text + "', @image)"
            'Define @image'
            SQLcommand.Parameters.Add(ImageToBlob("@image", myimage))
            SQLcommand.ExecuteNonQuery()
            SQLcommand.Dispose()
            SQLconnect.Close()
            MessageBox.Show("Pic Inserted")
        End If
    End Sub

    'USE THIS SUB TO GET THE BLOB FROM THE DB AND CONVERT IT BACK TO AN IMAGE'
    Private Sub btnGetImageFromDB_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim SQLconnect As New SQLite.SQLiteConnection()
        Dim SQLcommand As New SQLiteCommand
        SQLconnect.ConnectionString = "Data Source = " & Application.StartupPath & "\imgdb.sqlite3;"
        SQLconnect.Open()
        SQLcommand = SQLconnect.CreateCommand
        SQLcommand.CommandText = "SELECT image FROM foo WHERE id = '" + TextBox1.Text + "'"
        Dim SQLreader As SQLiteDataReader = SQLcommand.ExecuteReader()
        Dim myimage As Bitmap
        While SQLreader.Read
            myimage = BlobToImage(SQLreader("image"))
            PictureBox1.Image = Nothing
            PictureBox1.Image = myimage
        End While
        SQLcommand.Dispose()
        SQLconnect.Close()

    End Sub

Comment: Not sure how to thank this amazing and rare example that I'm aren't find on internet.

Save and Load image SQLite C#


Evaluation of MCMC samples

Question: My model contains five parameters. I want to make Bayesian estimation, but the Bayes estimates can not be obtained in closed form. So, I used Metropolis-Hastings to generate MCMC samples from conditional posterior density of each parameter. The trace and Auto-correlation plots were used to evaluate the generated sample. The trace plots for four parameters are random and the Auto-correlation plots are decreasing whereas for the fifth parameter(I will referred as alpha1), the trace plot is not random and the lags in Auto-correlation plot is not decreasing.
Discussion about alpha1
The acceptance rate is  0.99905 (It is too high) and the density plot is multimodal like the following graph

Trace plot

Auto-correlation plot

when I change the variance of the proposal density (absolute normal density) from 0.0005 to 0.5 the Acceptance rate becomes 0.1515 and the trace plot is horizontal line and the density function becomes uni-modal

I read MCMC for multimodal posterior
and this chapter from this book Evaluating Markov Chain Monte Carlo (MCMC) Algorithms. I am beginner in MCMC, I would be appreciated if one can help me to detect the problem. Is it multi modal or the correlation between parameters are high.
Many thanks in advance.
Edit
mixture 5 Normal density and trace plots

mixture 3 Normal trace plots

mixture 3 Normal density plot
Answer: Multimodality is often a cause of poor convergence or lack thereof for MCMC algorithms. Without any detail available about the posterior you aim at approximating, it is hard to tell whether or not you are facing such a case, because the multimodality on the first (density) figure is most likely an artefact reflecting the very slow move of the (sub) Markov chain in the $\alpha$ space.
What is more worrying is the trace plot you produce for $\alpha$ when the scale of the proposal density moves to $0.5$ as it seems the sequence does not change at all. The density you obtain is again an artefact I believe, namely a single Normal density produced by the kernel density estimator of R.
I would suggest using a sequence of scales in the Metropolis proposal, from the lowest 5e-5 to the largest 5e-1 (or higher), chosen at random at each iteration, meaning the use of a mixture proposal in the Metropolis acceptance ration. This means using the sum of the five Normal proposals in this ratio, rather than the Normal with the scale that has been chosen for that iteration.
Comment: Do you know how can I make thinning in Metropolis-Hastings algorithm in R. I wrote the code not a function in R.
Comment: Thinning means taking one simulation out of 10, 100, 1000.
Comment: I want to apply this in R , I tried to make thinning after getting the mcmc samples by using     'a<-seq(1,10000,by=100)
alpha1.adj<-alpha1[a]'
Comment: but this does not give me the acceptance rate. I want to enter the thinning code in MH algorithm code
Comment: Many thanks, I tried to use mixture of Gaussian proposal  using the sum of the five Normal proposals which is better than my suggestion.  when I use mixture Gaussian  using the sum of the three Normal proposals it better than based on five Normal proposals. The trace plot better than before and partly solving multi-modal.  I edit the question to present the results
Comment: Your traceplot does not exhibit convergence or stationarity. You should attempt ten times or 100 times more iterations.

Evaluation of MCMC samples


Configuration settings of Authcache for roles

Question: I'm not sure about configuration of roles in Autchcache module, specifically with authenticated user role. I want to enable caching for both anonymous and authenticated users, but I want to exclude from caching some roles (administrator and webmanager). My web has a lot of roles but an authenticated user may has one, two or more of them.
For example, my web has the next roles: anonymous, authenticated, administrator, webmanager, rol1, rol2, rol3, etc. Some users may have some roles: rol3 and rol4, but other users may have only rol1 and rol2, etc. I want cahing for all of them except the ones who has webmanager or administrator.
How should I config this behavior in Authcache module?
Answer: Authcache will only attempt to cache a page and deliver a cached page respectively if every single role of the logged in user is authcache enabled.
Consider the following example:

Five roles are defined on the website (including the built-in ones): anonymous, authenticated, customer role 1, customer role 2, administrator.
Three roles are enabled for authcache: anonymous, authenticated, customer role 1
User Customer A has the following role: customer role 1
User Customer B has the following role: customer role 2
User Customer C has the following roles: customer role 1 and customer role 2
User Customer D has no additional roles
User Administrator has the following role: administrator

This will lead to the following behavior:

Authcache will kick in for every anonymous user (anonymous role is authcache enabled).
Authcache will kick in for Customer A (customer role 1 is authcache enabled).
Authcache will not kick in for Customer B (customer role 2 is not authcache enabled).
Authcache will not kick in for Customer C (customer role 2 is not authcache enabled).
Authcache will kick in for Customer D (authenticated is enabled)
Authcache will not kick in for Administrator (administrator role is not authcache enabled).
Comment: Thanks for your explanation. Now, I understand it. It's a pity, because the way it works isn't good for my requirements and then I can't enable authcache for authenticated users because the most of my users are in your case C. In any case, thank for your help.


Showing a modulus equals 1

Question: Prove that if $z \ne 1$ then $\mid\dfrac{1-z}{\bar{z}-1}\mid = 1$
I have first re-written this as:
$$\frac{\mid 1 - x -iy \mid}{\mid x - iy - 1 \mid}$$
Now I am stuck. Any ideas?
Comment: Group together the real and imaginary parts of top and bottom, and use the formula $|a + ib|^2  = a^2 + b^2$.
Comment: "Then...." **what**??
Comment: You should insert $=1$ immediately after the absolute value after "then" in your post. This will turn it into a statement to be shown.
Comment: Yes, im sorry about that!!
Answer: Hint: for any complex $w$ we have $|\overline w|=|w|$.
This will make it much easier than expanding in terms of $x+iy$.
Comment: Ok but is $\mid{1-z}\mid = \mid \bar{z} - 1 \mid$ ??
Comment: Choose a suitable expression for $w$ in my hint.
Answer: Well, if $\space\exists\space\text{z}\in\mathbb{C}$ and $\text{z}\ne1$:
$$\mathcal{Z}=\left|\frac{1-\text{z}}{\overline{\text{z}}-1}\right|=\frac{\left|1-\text{z}\right|}{\left|\overline{\text{z}}-1\right|}=\frac{\left|1-\Re\left(\text{z}\right)-\Im\left(\text{z}\right)i\right|}{\left|\Re\left(\text{z}\right)-\Im\left(\text{z}\right)i-1\right|}=\frac{\sqrt{\left(1-\Re\left(\text{z}\right)\right)^2+\Im^2\left(\text{z}\right)}}{\sqrt{\left(\Re\left(\text{z}\right)-1\right)^2+\Im^2\left(\text{z}\right)}}\tag1$$
Now, we can write:
$$\mathcal{Z}=\sqrt{\frac{\left(1-\Re\left(\text{z}\right)\right)^2+\Im^2\left(\text{z}\right)}{\left(\Re\left(\text{z}\right)-1\right)^2+\Im^2\left(\text{z}\right)}}=\sqrt{\frac{\left(1-\Re\left(\text{z}\right)\right)^2+\Im^2\left(\text{z}\right)}{\left(1-\Re\left(\text{z}\right)\right)^2+\Im^2\left(\text{z}\right)}}=\sqrt{1}=1\tag2$$
Because:
$$\left(1-\Re\left(\text{z}\right)\right)^2=\left(\Re\left(\text{z}\right)-1\right)^2\tag3$$

Showing a modulus equals 1


Submitting webform without refreshing the page

Question: I have a webform displayed as a block:

Is it possible to submit the form without refreshing the page, followed by a message saying the webform has successfully been submitted? If so, could someone guide me in the right direction?
Thanks!
Answer: Check out Webform AJAX module.

This module adds AJAX support to Webform (3.0 and above).
As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.

I think that may do what you are asking. Should then show up as options in form settings.

Also, be sure you are set to "no redirect"
Comment: The ajax response uses the horendous drupal_set_message. Seriously, it's ugly.
Answer: There is an option on the block configuration page to "Show all webform pages in block", that will do what you what you need.
See, attachment:
Comment: Thanks! However I want the webform to be replaced by the confirmation message, now the page just reloads and I get an empty webform again.


writing COUNTIFS in python based on multiple conditions

Question: I have an issue which I have been able to solve on excel but need to also be able to solve this in python.
I have a table of customers with members who have terminated their membership and their purchase history. I want to be able to count number of purchases each customer has before and after their membership termination.
for the first row I used the countifs formulae =COUNTIFS(C:C,">"&B2,A:A,A2) to calculate the number of purchases the customer has done since termination.
is there a way to do this in python? I have tried using groupby but it doesnt really output the same data
here is the dataframe
Comment: Please copy/paste as plain text few lines of your worksheet to get help.
Answer: Group by is the technique you need, may be you're doing it wrong.
Try the following for counting purchases made after termination.
select id, count(*) from table where term < purchase group by id;

Replace term and purchase with the column names, and < with > if you want to count the purchases done before the termination.
The pandas query for the corresponding SQL statement is
df[df['Membership Termination date'] < df['Purchase date']].groupby('ID').size()

Comment: this looks more like SQL than pandas
Comment: @sammywemmy I've added the pandas query for the given SQL statement.


How many ways can you select 10 pieces of fruit with 4 different types and 5 each?

Question: Given 5 apples, 5 oranges, 5 bananas, and 5 pears, how many ways can you select 10 total fruits, having a minimum of 2 oranges and 1 apple?
So far I have narrowed it down to having 4 apples left, 2 oranges, and 5 of the remaining ones
Comment: What do you mean by "have narrowed it down to... "? Could you show us what you have done?
Comment: If you were allowed to write a computer program to solve it, how would you do it?
Answer: We have to count the integer solutions of $a+o+b+p=7$, given the constraints
$$a\in[0..4],\quad o\in[0..3],\quad  b,p\in[0..5]\ .$$ Let $x:=a+o$. Then $(0,1,2,3,4,5,6,7)$ is the list of possible values of $x$, and the list $(1,2,3,4,4,3,2,1)$ gives the numbers of corresponding admissible pairs $(a,o)$. Let $y:=b+p=7-x$ with value list $(7,6,5,4,3,2,1,0)$. It is easily checked that the  numbers of corresponding admissible pairs $(b,p)$ are given by the list $(4,5,6,5,4,3,2,1)$.
The total nmber of admissible selections therefore is
$$1\cdot4+2\cdot5+3\cdot6+4\cdot5+4\cdot4+3\cdot3+2\cdot2+1\cdot1=82\ .$$
Answer: Let's say total number of oranges is $(a+2)$, total number of apples is $(b+1)$, total number of bananas is $c$ and total number of pears is $d$.
We know that
$$a+b+c+d=7$$
So for $(a+2)$ oranges and $(b+1)$ apples, the number of ways to arrange the bananas and pears is
$$\sum_{c=0}^{7-a-b} \left( \frac{{5 \choose c}}{c!} \cdot \frac{{5 \choose {7-a-b-c}}}{(7-a-b-c)!} \right)$$
Hence, for $(a+2)$ oranges, the total number of ways to arrange the rest of the fruits is
$$ \sum_{b=0}^{7-a} \left( \frac{{5 \choose {b+1}}}{(b+1)!} \cdot \sum_{c=0}^{7-a-b} \left( \frac{{5 \choose c}}{c!} \cdot \frac{{5 \choose {7-a-b-c}}}{(7-a-b-c)!} \right) \right)$$
Thus, the grand total number of ways is
$$ \sum_{a=0}^{7} \left(  \frac{{5 \choose {a+2}}}{(a+2)!} \cdot \sum_{b=0}^{7-a} \left( \frac{{5 \choose {b+1}}}{(b+1)!} \cdot \sum_{c=0}^{7-a-b} \left( \frac{{5 \choose c}}{c!} \cdot \frac{{5 \choose {7-a-b-c}}}{(7-a-b-c)!} \right) \right) \right)$$


Froala WYSIWYG Editor Not Appearing in Browser

Question: I am running into an issue where I am loading the JS and CSS files correctly for the Froala editor,
but for some reason I believe that somewhere is the jQuery script, it is not taking my form and replacing it with the correct CSS styles.
Here is my view (#blog-editor is where I want to use the editor):

    <% include ../partials/head %>

        <% include ../partials/header %>

Blog Create

            <form action="/admin/posts/create" method="POST">
                Title: <input type="text" name="title">

                Author:
                    <select name="author">
                        <option value="Author">Connor Phillips</option>
                    </select>

                Category:
                    <select name="category">
                        <option value="Analytics/SEO/SEM">Analytics/SEO/SEM</option>
                        <option value="Advice">Advice</option>
                        <option value="Programming">Programming</option>
                        <option value="Thoughts">Thoughts</option>
                    </select>

                Tagline: <input type="text" maxlength="160" name="tagline">

                Content:

                <textarea name="content" id="blog-editor" rows="10" cols="80">

                </textarea>

                Tags: <input type="text" name="tags">

                <input type="submit" value="Submit">
            </form>

        <% include ../partials/footer %>

Comment: You should check what error you get in JS console and start from there.
Comment: Hey @st3fan there is no error in the JS console.
Answer: You are initialising the inline editor instead of the basic one and that's why you don't see nothing. You should use $('#blog-editor').editable({inlineMode: false}).
Comment: hey @st3fan, even with the inlinemode set to false, I am still seeing incorrect styles and no errors within my console.


Intersection between a tetrahedron in 4D space and a 3D hyperplane

Question: I am trying to compute all possible intersections between a tetrahedron lying in 4D space and a non-centered 3D hyperplane. Because of my lack of visualization (obviously), and for computer rendering purposes, I am using a computational approach.
My algorithm fills an array with vertices, and builds the resulting intersection as being the convex polygon or polyhedron uniquely defined by said vertices, on the basis that the intersection of a convex set with a hyperplane is also convex.
Here is the workflow of the algorithm :

Determine which of the tetrahedron's points lie in opposite half-spaces
If all points are in the same half-space, terminate with an empty intersection
If at least one point is inside the hyperplane, then add to the array all the vertices that are inside the hyperplane. This could be 1, 2, 3 or 4 vertices
Then, for each edge that intersects the hyperplane (ie edges for which the two vertices lie in opposite half-spaces), add to the array the intersection between that edge and the hyperplane

Although I have not written a rigorous proof for this, I find empirically that you only get points, lines, triangles, quadrilaterals or tetrahedras out of this algorithm (or at least, I have never encountered a counter-example).
The problem resides in this visualisation of a unit hypercube rotating around its center on the XZ and ZW canonical planes by equal angles, in that order (WebM video) :
http://www.mirari.fr/ITg9
The principle of the visualisation is a simple application of the aforementioned algorithm. The hypercube is decomposed in 4D tetrahedras, which are subsequently intersected with a 3D hyperplane, which is defined by the position of the camera and the direction of its (3D) viewing frustum. The resulting intersections, being 3D objects, are directly displayed on the screen with no further transformation. The pixels colored with different shades of blue are forward-facing faces, and the black pixels are backward-facing faces.
As you can see, the 3D model becomes non-convex from time to time, as it looks like a face or two are "forgotten" and we can see the "inside", back-facing faces behind. This leads to my question : am I forgetting any scenario in my intersection algorithm that may lead to the omission of some of the 3D objects making up the hypercube ? Although I have not yet totally outruled a flaw in my rendering process, I believe I have done enough checking and trying to think the error is in this algorithm.
Comment: In general, you can solve this problem for a $k$-simplex in $n$-space sliced by an $n-k + 1$ plane. Aside from the kind of edge-cases (like slicing a tetrahedron in a way that gives you a single edge), you can look at $s+1$ vertices on one side of the slice plane, $k - s$ on the other side, and then figure out the number of vertices of the slice object, and their connectivity, and there's really no need for anything numerical -- it's pure combinatorics. (The "special cases" are really just the cases where there are some verts on one side, some on the other, and some ON the slice plane, BTW.)
Comment: Surely, but the point of the whole thing is the actual representation of it, so I do have to get numerical at one point, haha.
Answer: The slice of a tetrahedron $T$ in 4-space by a 3-plane $P$ can be simplified:
let $U$ be the 3-plane that contains the tetrahedron (there always is one!).
Then
$$slice(T, P) = slice (T \cap U, P \cap U)
$$
so any such slice is the slice of a tetrahdron by some plane in 3-space. So you're done, and no visualization is needed.
Comment: Just to be sure, what you wrote as $slice(A, B)$ is really just $A \cap B$ right ?
Comment: Yes, but I wanted to emphasize that it was the slicing operation; I should have mentioned that.
Comment: Okay, I guess it helps a little, although I won't be using that approach. The point of the algorithm is to not have to calculate $P \cap U$, which would require calculating a base for $U$ and the intersection between both hyperplanes, in addition to actually intersecting the tetrahedron with the result. Instead, it directly computes the intersection with very few and fast (from an algorithmic point of view) conditionals. One thing that bugs me is that there are infinitely many 3-planes that contain the tetrahedron, so can't I always choose one that is parallel to P ?
Comment: Answer to self : no you can't, because 4 non-coplanar points define a single 3-plane. Nevermind !
Answer: You mentioned your second step as:  If all points are in the same half-space, terminate with an empty intersection.  Just checking (as I will be needing to do this myself soon) if you wouldn't also need to do a test if three or four points lie completely in the intersection instead of in opposite halves?  If that tests as true then wouldn't that single face (3 points) or the whole tetrahedron (4 points) need to be drawn instead of an intersection through the tesseract?  Could that possibly be why yours had missing faces?
Comment: Welcome to MSE. This should be a comment, not a answer.
Comment: Thanks José I'll try to move it to the right place.  Just realised I can't so I better remove it...
Comment: By "in the same half-space", I meant that all the points returned the same *non-zero* value when fed to the hyperplane's cartesian equation.