Effect size calculation

Question: I am conducting a meta-analysis on the diet of predators. This diet is expressed as the proportion of aquatic vs terrestrial prey. I have a value (% of aquatic prey) for each species for each site of each study. I can't find any satisfying way to calculate an effect size.
Any advice ?
Thanks
Denis
Comment: What would be wrong with using the proportions you have, possibly transformed?
Answer: Several options exist. For example, Cohen h or Odds Ratio. Cohen h is usually associated with sample size determination and power analysis, but the Odds Ratio can be used for meta-analysis (see last two links).
https://ncss-wpengine.netdna-ssl.com/wp-content/themes/ncss/pdf/Procedures/PASS/Tests_for_Two_Proportions_using_Effect_Size.pdf
https://www.campbellcollaboration.org/escalc/html/EffectSizeCalculator-OR2.php
https://www.ncbi.nlm.nih.gov/pubmed/28169977
Comment: I think the OP has a single proportion from each study so could not compute an OR.
Comment: Thank you for the clarification. The proportion as noted by mdewey seems logical, or present as an odds of the event, p/(1-p), or Cohen (1988, Statistical Power Analysis for the Behavioral Sciences, p. 147) discusses effect size g as the departure of the probability from .50 (i.e., g = p-.5), but that is probably most suitable for power and sample size determination.
Comment: Hi. Yes, this is not the result of a test and I have no control. So I can't calculate the usual Odds ratio. The g value ou odds of the event sounds promising. I will follow these leads. Thanks

Effect size calculation


How to solve a system of nonlinear equations with inequality constraints and ensure convergence?

Question: Now I have the nonlinear equations with inequality constraints as below:
\begin{equation}
\label{equ:kkt}
\begin{aligned}
\left\{
\begin{aligned}
&\sum_{i=1}^M a_i \exp \left( -\frac{u_i}{\tau} \right) = \sum_{j=1}^N b_j \exp \left( -\frac{v_j}{\tau} \right)\\
& u_i + v_j + s_{ij} = C_{ij}\\
& s_{ij} \ge 0
\end{aligned}
\right.
\end{aligned}
\end{equation}
I need to solve $u \in \mathbb{R}^{M \times 1}$, $v \in \mathbb{R}^{N \times 1}$ and $s \in \mathbb{R}^{M \times N}$.
Currently my solution:
(1) First set $s_{ij} = 0$ and fix $s_{ij}$ then optimize $u_i$, $v_j$. For optimize $v$ we set $u_i^{(l)} = C_{iw} - s^{(l)}_{iw}-v^{(l)}_w = \widehat{C}^{(l)}_{iw}-v^{(l)}_w$:
\begin{equation} \nonumber
\begin{aligned}
\sum\limits_{j=1}^N  b_j  \exp \left( -\frac{v^{(l)}_j}{\tau} \right)   = \exp \left( \frac{ v^{(l)}_w }{\tau} \right) \sum\limits_{i=1}^M  a_i \exp \left( -\frac{   \widehat{C}^{(l)}_{iw} }{\tau} \right) \quad {\rm for} \quad \forall w \in \{ 1, 2, \cdots, N\}
\end{aligned}
\end{equation}
Then we can solve the results for $v^{(l)}$.
Meanwhile we optimize $u$ and we set $v_j^{(l)} = C_{rj} - s^{(l)}_{rj}-u^{(l)}_r = \widehat{C}^{(l)}_{rj}-u^{(l)}_r$:
\begin{equation} \nonumber
{
\begin{aligned}
\sum\limits_{i=1}^M  a_i \exp \left( -\frac{u^{(l)}_i}{\tau} \right)  = \exp \left( \frac{ u^{(l)}_r }{\tau} \right) \sum\limits_{j=1}^N  b_j \exp \left( -\frac{   \widehat{C}^{(l)}_{rj} }{\tau} \right) \quad {\rm for} \quad \forall r \in \{ 1, 2, \cdots, M\}
\end{aligned}
}
\end{equation}
Finally we update $s$ via $s^{(l+1)}_{ij} = \max(0, C_{ij} - u^{(l)}_i - v^{(l)}_j)$ for the next iteration.
I have tried this in my Python program, it works well. However, I still have questions below:
<1> Is my solving process mathematically reasonable?
<2> Continuing on, if the answer is yes, how can we prove the convergence of this algorithm?
<3> Continuing on, if the answer is no, how to correctly solve the above questions with convergence guarantee?
Many Thanks to all of you.
Answer: Sir, it's a slight overkill actually.

Select such $i_0$ and $j_0$ that $a_{i_0}$ and $b_{j_0}$ are of the same sign; if one can't select - до побачення, the problem is infeasible.

Denote $C = \min \limits_{i, j} C_{ij}$. Now set $v_i = \frac{C}{2} - x$ for all $i$ and $v_j = \frac{C}{2} - x$ for all $j$. Reset $v_{i_0} = \frac{C}{2} - y$, $v_{j_0} = \frac{C}{2} - z$. Now for all nonnegative $x, y, z$ all linear constraints are satisfied.

Now the first constraint is

$$ \sum \limits_{i \neq i_0} a_i e^{-\frac{C - 2x}{2\tau}} + a_{i_0} e^{-\frac{C - 2y}{2\tau}} = \sum \limits_{j \neq j_0} b_j e^{-\frac{C - 2x}{2\tau}} + b_{j_0} e^{-\frac{C - 2z}{2\tau}}$$
or
$$ \sum \limits_{i \neq i_0} a_i e^{\frac{x}{\tau}} + a_{i_0} e^{\frac{ y}{\tau}} = \sum \limits_{j \neq j_0} b_j e^{\frac{x}{\tau}} + b_{j_0} e^{\frac{z}{\tau}}.$$
Finding a feasible solution of the latter satisfying $x, y, z \geq 0$ is more-less obvious, and the solution always exists since $a_{i_0}$ and $b_{j_0}$ have the same sign.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Many Thanks for your apply! It really works!


The UPDATE statement conflicted with the foreign key - SQL Server and Entity Framework

Question: I have tables called tbScore, tbScoreDetail and tbReview. I have a foreign key column reviewId (nullable) in tbScoreDetail. It will allow me to insert the row, but while updating the table, it is throwing an exception

The UPDATE statement conflicted with foreign key constraint "FK_Review_ScoreDetail"

This is my code:
public class ScoreDetail
{
    public int ScoreDetailId { get; set; }
    public int ScoreId { get; set; }
    public int? ReviewId { get; set; }
}

public class ReviewId
{
    public int ReviewId { get; set; }
    public string Review { get; set; }
}

Comment: Show us the code doing the `UPDATE`, and show us some sample data you're working with!
Comment: Are you updating column `reviewId`?  if so, then that is the problem
Answer: Your problem is related to your mapping settings in the EntityFramework, why do I say this is where the foreign keys are configured and whether or not they are nullable is commanded or by:
public int? IndexNullable { get; set ;}

Or in the configs where you can configure this way
https://www.entityframeworktutorial.net/code-first/configure-entity-mappings-using-fluent-api.aspx
What it takes to check how your keys are configured in your default entity correctly and the index by your own nomenclature see the keys too and the index on your own when migrations perceive a database of your indexes and very likely that a cases, where an index was created without its explicit intention.


2-adic valuation of odd harmonic sums

Question: I'm playing with p-adic valuations, and find that the odd harmonic sums, $\tilde{H}_k=\sum_{i=1}^{k}\frac{1}{2i-1}$, has 2-adic valuation $||k^2||_2=2||k||_2$.
E.g.) $\tilde{H}_4=\frac{176}{85}$ has $||\tilde{H}_4||_2=||176||_2=4=2||4||_2$.
$\tilde{H}_6=\frac{6508}{3465}$ has $||\tilde{H}_6||_2=2$. $||\tilde{H}_8||_2=||\frac{91072}{45045}||_2=6$. $\cdots$
How can I prove this?
(Some simple observation I have tried: As $||H_k||_2 =-r$ for $2^r\leq k <2^{r+1}$, $||H_k||_2=||H_{2k}||_2+1=||\frac{1}{2}H_k||_2$. Thus ultrametric ineq for $\tilde{H}_k=H_{2k}-\frac{1}{2}H_k$ doesn't help at all, yielding trivial result $\tilde{H}_k\in \mathbb{Z}_2$.)
(That $||\tilde{H}_k||_2=2||k||_2$ for odd $k$ is almost trivial, so the problem can be reduced to show $||\tilde{H}_{2k}||_2=||\tilde{H}_k||_2+2$, still have no idea)
(I've checked this holds up to $\sim 1000$ using Mathematica, and Mathematica spits the result almost immediately for $n\sim 1000$ and takes about a minute for $n\sim 10000$. )
For anyone interested : I've used the following Mathematica code, try it yourself
a = Table[
   IntegerExponent[
     Numerator[HarmonicNumber[2 n] - HarmonicNumber[n]/2], 2]/2, {n,
    10000}];
b = Table [IntegerExponent[n, 2], {n, 10000}];
NonNegative[Min[a - b]]
Comment: If we can show that a partial sum
$$\tilde{H}_{2^k,m}=\sum_{i=m\cdot2^k+1}^{(m+1)\cdot2^k}\frac1{2i-1}$$ of length a power of two always has 2-adic value $=2k$, then your conjecture would follow, right? My testing (with Mathematica) supports this as well, but it is anything but comprehensive.
Comment: @JyrkiLahtonen Yes, maybe this form is a little bit easier but I have no idea how to show this too :(
Comment: It looks like you use $\|\cdot\|_2$ for the additive $2$-adic valuation. This symbol usual means multiplicative $2$-adic absolute value.
Answer: Only  a partial result. I note  $v_2$ the $2$-adic valuation.
Let $\displaystyle Q_k(x)=\prod_{i=1}^{k}(x-j)=x^{k}+b_{k-1}x^{k-1}+\cdots+b_0$. We have $b_l\in \mathbb{Z}$. Note that $b_{k-1}=-\frac{k(k+1)}{2}$. Put $P_k(x)=2^kQ_k(\frac{x}{2})$. Then $P_k(x)=x^{k}+2b_{k-1}x^{k-1}+\cdots+2^{k-1}b_1 x+2^k b_0=\prod_{j=1}^{k}(x-2j)$.
Now
$$\frac{P_k^{\prime}(x)}{P_k(x)}=\sum_{j=1}^k \frac{1}{x-2j}$$ Putting $x=1$, we get that $v_2(\tilde{H_k})=v_2(P_k^{\prime}(1))$.
Now suppose that $k$ is odd. Then $P_k^{\prime}(1)=k+2q$ with $q\in \mathbb{Z}$. Hence your result is true in this case (as you have noted).
Suppose that $k=2m$ with $m$ odd.Then the first two terms in $P_k^{\prime}(1)$ give $ (2m-(2m(2m+1)(2m-1))=4m(1-2m^2)$, and it is easy to see that $8$ divide the other terms. Hence your result is true in this case.

2-adic valuation of odd harmonic sums


Spring Boot Rest call - ERR_CONNECTION_REFUSED

Question: I have a war file with spring boot as server side and angular 8 as front end.
and the war is getting deployed in remote machine where ip changes on restart.
If I deploy the war where rest request call from  angular are made with ip address of the host it was working fine
http://220.127.116.11:8080/test/getMessage

since the IP is changing on each time machine restart i need to change the code each time
Is there a way where i can make the rest call with out referring ip address, as both angular and spring boot are packaged in same war
i tried using local host in the rest url , but getting error
ERR_CONNECTION_REFUSED

it was working only when war is deployed in my desktop not on remote machine, which makes sense.
Adding Client Code:
    public SERVER_IP:string="188.8.131.52";
    public SERVER_PORT:string="8080";
    public SERVER_PROTOCOL:string="http";
    public APP_CONTEXT:string="test";
    public  URL_BASE:string= this.SERVER_PROTOCOL+"://"+this.SERVER_IP+":"+this.SERVER_PORT+"/"+  this.APP_CONTEXT+"/";
    public  URL_GET_MESSAGE:string= this.URL_BASE +"getMessage";

    this.http.get(this.constant.URL_GET_MESSAGE,{params: data})

Comment: can you post your client code? How you're making call? You can possibly do relative URL.
Comment: It's related to network configuration either you can bind your instance to 127.0.0.1 or use static IP so that your ip won't change every time you restart you machine. Configure your tomcat to bind to 127.0.0.1.
Answer: Yes there is a pretty simple way to implement this. When you build your application, set your SERVER_IP parameter to "/". This simple forward slash means that if your angular application loads on xyz.com then your API url will be xyz.com.
Also you can then form the URL using the code:
public  URL_BASE:string= "/"+  this.APP_CONTEXT+"/";

Of course, you'll need to get rid of Port by using a reverse proxy like NGINX.
Thus, it will always be relative to your current host URL. This is an approach we use in multiple of our applications and it works smooth.
Answer: Either u fixed the remote machine ip permanently neither you will do the testing in your local machine it will work.


file mask to exclude *.m.swp files in git

Question: When I run git status, *.m.swp files are showing up in the "untracked list" because I currently have these files open in MacVim (The originals are MATLAB files with *.m file extensions).
I have tried adding *.m.swp, and various permutations of this, to my .gitignore file so that the files are ignored, but nothing seems to work for me.
See an example of git status output below:
git status
# On branch mybranch1
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   ../dir1/file1.m
#   new file:   file2.m
#   new file:   file3.m
#   modified:   file4.m
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   ../../dir2/.file5.m.swp
#   ../dir1/.file6.m.swp
#   ../dir1/.file1.m.swp
#   ../dir1/.file7.m.swp
#   ../dir1/.file8.swp
#   .file9.m.swp
#   .file4.m.swp

How can I get git to ignore these?  Thanks in advance for any help!
Answer: .*.m.swp

should work: I have tested it in my msysgit1.7.4 environment.
So: not "*..." but ".*...".
Don't forget to add your modified .gitignore to the index before doing a new git status.
Comment: Thanks @VonC! I don't think I was adding `.gitignore` before running `git status`.  I have it in my global ignores now.
Comment: @Abbie: excellent :) I take it the `.gitignore` is now working?
Answer: .*\\.m\\.swp

do this instead, since unescaped .'s match anything
Comment: You don't need to escape dots in .gitignore


Paradigma Imperativo e Declarativo

Question: Quais as diferenças dos paradigmas de programação imperativa e declarativa? Vantagens e desvantagens?
Answer: Resumidamente o imperativo diz como fazer e o declarativo diz o que fazer.
Imperativo
Este paradigma se preocupa com os detalhes do funcionamento do algoritmo e o declarativo apenas com a semântica correta do que se quer alcançar. Fica claro que é muito difícil programar de forma apenas declarativa. O declarativo deverá ter algum suporte de outros paradigmas, como o imperativo, mesmo que de forma bastante transparente.
Grande parte das linguagens de programação mainstream são mais imperativas. Mesmo algumas que tentam se vender como sendo de outros paradigmas, elas apenas possuem certas características destes paradigmas. Praticamente não existe linguagem orientada a objeto de fato, puramente falando, mesmo que o marketing delas digam que sim. Hoje algumas linguagens procuram ter formas mais declarativas em adição à forma imperativa.
Com ele você comunica melhor com o computador, diz extamenet como fazer.
Exemplo de código C#:
var lista = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
var pares = new List<int>();
foreach (var num in lista) if (num % 2 == 0) pares.Add(num);

Declarativo
Esta forma pode usar uma sintaxe mais fluente. Mas nem sempre. É possível usar uma sintaxe imperativa e programar de forma declarativa. Muitas vezes a programação funcional é considerada uma forma declarativa já que ela se preocupa mais com a execução geral do que os detalhes específicos.
A forma declarativa pode ser mais expressiva em alguns cenários mas é muito difícil expressar detalhes. A não ser que exista uma limitação do que se deve fazer é comum ter formas de escapar da forma declarativa, talvez até estendendo de alguma forma o estilo declarativo de codificar.
Neste paradigma temos melhores abstrações e a linguagem é considerada de mais alto nível.
Eficiência não é algo que se espera neste paradigma. Não que ele não possa executar algo rápido, em alguns casos pode até obter melhores resultados mas em códigos comparáveis, onde se obteve o máximo de otimização possível em cada paradigma, o declarativo será mais lento, mesmo que a diferença não seja importante.
É claro que pode-se obter até mais eficiência nos casos não otimizados. A forma declarativa permite que um bom backend otimize o código de uma forma que o programador tem dificuldade, justamente por não dar muitos detalhes, ele pode escolher o melhor caminho. É muito difícil melhorar código imperativo. Existem algumas coisas que podem ser feitas mas não se pode mudar completamente o jeito de fazer sob pena de mudar o resultado. Há detalhes demais.
Para funcionar, estas linguagens normalmente precisam de um backend que interpretará ou compilará o código. Provavelmente escrito de forma imperativa.
Muitas vezes as linguagens declarativas não são linguagens de programação. Elas costumam ter limitações para armazenar estados, principalmente intermediários, e em estruturas de controle de fluxo, já que este não é o objetivo deste tipo de linguagem. Sem essas características fica difícil ou impossível reproduzir a máquina de Turing. É possível ter neste paradigma as características necessárias para classificar a linguagem como de programação.
O SQL é uma linguagem bastante declarativa. Você especifica como quer o resultado, mas exatamente como o banco de dados irá achar o resultado desejado é problema dele. SQL padrão não é uma linguagem de programação. Com algumas extensões pode ser.
O C# adotou o LINQ que é uma forma mais declarativa de programar, tendo inclusive uma sintaxe mais imperativa e outra mais puramente declarativa.
Outros exemplos são as linguagens de declaração de GUI onde você diz como quer que monte os elementos de telas, com alguma forma de XML ou formato semelhante, mas não informa como isto deve ser executado. Outros exemplos são o HTML, CSS, RegEx.
Linguagens de programação podem ser mais declarativas, mas não totalmente.
Com o declarativo você comunica melhor com humanos.
Exemplo de código C#:
var lista = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
var pares = from num in lista
                where num % 2 == 0
                select num;
pares = pares.ToList();

Forma declarativa com sintaxe imperativa:
var lista = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
var pares = lista.Where(num => num % 2 == 0).ToList();

Coloquei no GitHub para referência futura.
O ToList() pode ser omitido em certas circunstâncias, mas para ser igual ao exemplo de cima ele tem que ser colocado.
Comment: mesmo a linguagem de máquina é "compilada" de maneiras diferentes dentro de um chip... isso torna essa classificação de imperativo vs declarativo um tanto variada conforme a perspectiva de quem vê ou do contexto que se aplica. Dizer "a linguagem C é declarativa/imperativa" significa: "a linguagem C é declarativa/imperativa" em relação a que?
Answer: Programação Imperativa

A Programação Imperativa é um conceito baseado em estados, definidos
por variáveis, e ações que são manipuladoras de estado, procedimentos.
Pelo fato de permitir o uso de procedimentos como estruturação, também
é conhecido como, Programação Procedural.

Exemplos de linguagens: Pascal,C,Cobol,Python
Vantagens

Eficiência
Modelagem natural dos problemas do mundo real
Dominância de mercado
Bem estabelecido

Desvantagens

Focaliza o "COMO" e não o "QUE" precisa ser feito
Difícil legilibilidade

Explicação: Em uma linguagem imperativa, o programador diz com detalhes as operações que o programa realiza, incluindo manipulação de memória e interface direta com a entrada/saída do programa.

Programação Declarativa

A Programação Declarativa, ao contrário da Programação Imperativa que
informa ao computador "COMO" as instruções devem ser executadas,
preocupa-se em apenas dizer ao computador "O QUE" precisa ser feito,
cabendo ao computador decidir qual a melhor solução para essa
solicitação.As linguagens definidas por este paradigma não podem ser
consideradas como linguagens de programação, e sim, como
sub-linguagens.

Exemplos de linguagens: SQL, XML
Vantagens

Facilidade de acesso a banco de dados(SQL)
Conversão de objetos complexos(Pessoa, Empregado) por Binding para trafegar pela rede(XML)

Desvantagens

Ilegilidade do código(Quando usada de forma funcional)

Explicação: Quando diz aqui usada de forma funcional, está se referindo a linguagens de marcação, como XML e HTML por exemplo, na qual pode ser difícil entender o seu conteúdo devido às marcações.

Fonte: Programação Imperativa vs Programação Declarativa
Comment: Oi @Pedro, porquê o "Focaliza o "COMO" e não o "QUE" precisa ser feito" é tido como uma desvantagem para o PI(paradigma imperativo)?

E o que significa usar de forma funcional o P.D?
Comment: desculpe a demora, veja as explicações na resposta se esclarescem sua dúvida

Paradigma Imperativo e Declarativo


How to project data onto a model (specifically, GMM)?

Question: I'm using data to train a Gaussian mixture model (GMM). I then take a sample and would like to see its projection on the GMM 'space'. I can think of an optimization problem such as this: consider $y$ to be my sample and $p(x)$ my trained GMM. $ll(x)=log(p(x))$ is the log-likelihood function. Therefore, $\hat{y}$ shall be the projection, defined as:
$$
\hat{y}=\arg\min_u ||u-y||_2^2-ll(u),
$$
which makes sense as it seeks the closest $u$ to $y$ but keeping the log-likelihood of $u$ high enough.
Does this make sense? are there any standard ways to do that specifically in the case of GMM (I wouldn't want to reinvent the wheel)?
Comment: What exactly do you mean by "projecting data onto a model"? If you are also not sure, then maybe the following question will help. What do you plan to do after you get this "projection"?
Comment: I have a model for how the data should behave (alternatively, describes the manifold on which it resides), and I have a sample that's out of the manifold and I would like to find the best approximation of the sample constrained to be on the manifold. This manifold is described as all possible samples spanned by the GMM model.
Comment: The way I'm looking at it is that if my manifold was all points of the form $(x,0)$ and my points was $(x_0,y_0)$, then the result would be $(x_0,0)$. Here the manifold structure is much more complicated...
Comment: I can imagine what you said if you had a surface, a point outside it, and you want to project it down to the surface. But how do you see a Gaussian mixture model as a surface? Do you, say, take a quantile to form the surface boundary..?
Answer: If I understand your question correctly, then what you are looking for is a way to make `predictions' with a mixture model, that is, to find out what is the mean of an observation according to the model.
Let's start with the obvious case of a one component mixture. That is:
$$
y_1,...,y_n \sim N(\mu, \Sigma).
$$
We can estimate $\mu$ with the sample mean $\hat\mu = \bar{y}$ and then the prediction for any unobserved value is simply $\hat\mu$.
Things are a bit more complicated for mixture models. Assume the following model:
$$
y_1,...,y_n \sim \sum_{k=1}^{K}\pi_k N(\mu_k, \Sigma), \qquad \sum_{k=1}^{K}\pi_k = 1.
$$
Given estimates for the parameters, the expected value for any new observation is :
$$
E(y) = \sum_{k=1}^{K}\hat\pi_k \hat\mu_k.
$$
Now this solution is obviously unsatisfactory as what we are looking for is a way to estimate the expected value of an observation $y_i$ based on the model and the observed information. For this purpose, let us pose this problem as a Bayesian one. Suppose that $E(y_i) = \nu_i$ where:
$$
\nu_i \sim \sum_{k}\pi_k \delta_0(\mu_k),
$$
that is, the prior for $\nu_i$ is discrete with probabilities at the estimated mean values. Now,
$$
E(\nu_i | y_i) = \sum_{k=1}^{K} \hat\mu_{k} P(\nu_i = \hat\mu_k | y_i)
$$
where,
$$
P(\nu_i = \hat\mu_k|y_i) = \frac{\varphi(y_i ; \hat\mu_k, \Sigma)\hat\pi_k}{\sum_{l=1}^{K}\varphi(y_i;\hat\mu_l,\Sigma)\hat\pi_l}.
$$
That is, the best estimate for the expected value of $y_i$ given $y_i$ is the posterior mean of $\nu_i$.


Obtaining consistent classifications when regenerating an rpart() model with predict() in R

Question: This is been a recurrent problem for me in the past few days.
I've the following dataset that I'm using to test the accuracy of a rpart() model:
> head(resp41366_observed)
   ACTIVITY_X ACTIVITY_Y       observed
1:         29         19 Feeding/Moving
2:         34         30 Moving/Feeding
3:         51         47 Moving/Feeding
4:         78         38 Moving/Feeding
5:         18         17 Feeding/Moving
6:          4          0 Feeding/Moving

The model is:
xtree <- rpart(classification ~ ACTIVITY_X + ACTIVITY_Y , data = train, method = "class", parms = list(split = "information"))

To test model's accuracy, I'm using resp41366 to predict the classes seen in resp41366$observed and then comparing the classes predicted by the model with the resp41366$observed classes.
The predictor dataset I'm using is pred41361 which has the exact same format as resp41366. This is the code:
#Running the model
> resp41366_pred413561 = predict(xtree,resp41366,type="class")
> resp41366_pred413561<-data.table(resp41366_pred413561)
> names(resp41366_pred413561)="predicted"
#Merging the observed classes with the predicted classes by the model
> test_accuracy<-cbind(resp41366_observed,resp41366_pred413561)
> head(test_accuracy)
         observed      predicted
1: Feeding/Moving Moving/Feeding
2: Moving/Feeding Moving/Feeding
3: Moving/Feeding Moving/Feeding
4: Moving/Feeding Moving/Feeding
5: Feeding/Moving Feeding/Moving
6: Feeding/Moving Feeding/Moving
#Calculating accuracy
> obs<-as.factor(test_accuracy$observed)
> pred<-as.factor(test_accuracy$predicted)
> mean(obs == pred)
[1] 0.8208556

This is the perfect scenario were the predicted classes match the observed classes fairly well. However, if I regenerate test_accuracy, it might happen that I get (as an example):
#Calculating accuracy
> obs<-as.factor(test_accuracy$observed)
> pred<-as.factor(test_accuracy$predicted)
> mean(obs == pred)
[1] 0.02345

When this happens, I can bring the accuracy back to 0.8208556 by shuffling the predicted classes as follows, to make them compatible with the observed classes again:
1) replace Feeding/Moving for Standing
2) replace Moving/Feeding for Feeding/Moving
3) replace Standing for Moving/Feeding
My question: Is there a way to predefine the classes so that I'm always getting a consistent classification without the need of re-arranging the classes post-hoc? Am I missing something when implementing predict() maybe?
I hope somebody can help me solve this issue, as I'll need to use this model for datasets which observed classes are unknown and I need to have consistent classifications every time the data is regenerated.
Any input is appreciated!

Code:
#80:20 data split for cross-validation
trainIndex  <- sample(1:nrow(tableresults), 0.8 * nrow(tableresults))
train <- tableresults[trainIndex,]
test <- tableresults[-trainIndex,]
#Model implementation
xtree <- rpart(classification ~ ACTIVITY_X + ACTIVITY_Y , data = train, method = "class", parms = list(split = "information"))

Data details:
> dput(tableresults)
structure(list(ACTIVITY_X = c(40L, 60L, 62L, 60L, 66L, 60L, 57L,
54L, 52L, 93L, 80L, 14L, 61L, 51L, 40L, 20L, 21L, 5L, 53L, 48L,
73L, 73L, 21L, 29L, 63L, 59L, 57L, 51L, 53L, 67L, 72L, 74L, 70L,
60L, 74L, 85L, 77L, 68L, 58L, 80L, 34L, 45L, 34L, 60L, 75L, 62L,
66L, 51L, 53L, 48L, 62L, 62L, 57L, 5L, 1L, 12L, 23L, 5L, 4L,
0L, 13L, 45L, 44L, 31L, 68L, 88L, 43L, 70L, 18L, 83L, 71L, 67L,
75L, 74L, 49L, 90L, 44L, 64L, 57L, 22L, 29L, 52L, 37L, 32L, 120L,
45L, 22L, 54L, 30L, 9L, 27L, 14L, 3L, 29L, 12L, 61L, 60L, 29L,
15L, 7L, 6L, 0L, 2L, 0L, 4L, 1L, 7L, 0L, 0L, 0L, 0L, 0L, 1L,
23L, 49L, 46L, 8L, 31L, 45L, 60L, 37L, 61L, 52L, 51L, 38L, 86L,
60L, 41L, 43L, 40L, 42L, 42L, 48L, 64L, 71L, 59L, 0L, 27L, 12L,
3L, 0L, 0L, 8L, 21L, 6L, 2L, 7L, 4L, 3L, 3L, 46L, 46L, 59L, 53L,
37L, 44L, 39L, 49L, 37L, 47L, 17L, 36L, 32L, 33L, 26L, 12L, 8L,
31L, 35L, 27L, 27L, 24L, 17L, 35L, 39L, 28L, 54L, 5L, 0L, 0L,
0L, 0L, 17L, 22L, 25L, 12L, 0L, 5L, 41L, 51L, 66L, 39L, 32L,
53L, 43L, 40L, 44L, 45L, 48L, 51L, 41L, 45L, 39L, 46L, 59L, 31L,
5L, 24L, 18L, 5L, 15L, 13L, 0L, 26L, 0L), ACTIVITY_Y = c(47L,
74L, 63L, 56L, 61L, 53L, 40L, 41L, 49L, 32L, 54L, 13L, 99L, 130L,
38L, 14L, 6L, 5L, 94L, 96L, 38L, 43L, 29L, 47L, 66L, 47L, 38L,
31L, 36L, 35L, 38L, 72L, 54L, 44L, 45L, 51L, 80L, 48L, 39L, 85L,
42L, 39L, 37L, 75L, 36L, 45L, 32L, 35L, 41L, 26L, 99L, 163L,
124L, 0L, 0L, 24L, 37L, 0L, 6L, 0L, 29L, 29L, 26L, 27L, 54L,
147L, 82L, 98L, 12L, 83L, 97L, 104L, 128L, 81L, 42L, 102L, 60L,
79L, 58L, 15L, 14L, 75L, 75L, 40L, 130L, 40L, 13L, 54L, 42L,
7L, 10L, 3L, 0L, 15L, 8L, 75L, 55L, 26L, 18L, 1L, 13L, 0L, 0L,
0L, 1L, 0L, 4L, 0L, 0L, 0L, 0L, 0L, 0L, 17L, 45L, 38L, 10L, 31L,
52L, 36L, 65L, 97L, 45L, 59L, 49L, 92L, 51L, 34L, 21L, 20L, 29L,
28L, 22L, 32L, 30L, 86L, 0L, 15L, 7L, 4L, 0L, 0L, 0L, 11L, 3L,
0L, 1L, 3L, 1L, 0L, 72L, 62L, 98L, 55L, 26L, 39L, 28L, 81L, 20L,
52L, 12L, 48L, 24L, 40L, 30L, 5L, 6L, 40L, 37L, 33L, 26L, 17L,
14L, 39L, 27L, 28L, 67L, 0L, 0L, 0L, 0L, 0L, 10L, 12L, 14L, 7L,
0L, 2L, 39L, 67L, 74L, 28L, 23L, 57L, 34L, 36L, 36L, 37L, 46L,
43L, 73L, 65L, 31L, 64L, 128L, 17L, 3L, 12L, 17L, 0L, 9L, 7L,
0L, 17L, 0L), classification = c("Moving/Feeding", "Standing",
"Standing", "Standing", "Standing", "Standing", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Standing", "Standing", "Feeding/Moving",
"Standing", "Standing", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Standing", "Standing", "Standing", "Standing",
"Moving/Feeding", "Moving/Feeding", "Standing", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Standing", "Standing", "Standing", "Moving/Feeding", "Standing",
"Standing", "Standing", "Standing", "Moving/Feeding", "Standing",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Standing",
"Standing", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Standing", "Standing", "Standing",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Moving/Feeding",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Standing",
"Standing", "Standing", "Standing", "Feeding/Moving", "Standing",
"Standing", "Standing", "Standing", "Standing", "Moving/Feeding",
"Standing", "Moving/Feeding", "Standing", "Standing", "Feeding/Moving",
"Feeding/Moving", "Standing", "Moving/Feeding", "Moving/Feeding",
"Standing", "Moving/Feeding", "Feeding/Moving", "Moving/Feeding",
"Moving/Feeding", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Standing",
"Standing", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Moving/Feeding", "Moving/Feeding",
"Feeding/Moving", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Standing", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Standing", "Standing", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Standing", "Standing", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Standing", "Moving/Feeding", "Standing", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Standing", "Moving/Feeding",
"Moving/Feeding", "Feeding/Moving", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Feeding/Moving", "Feeding/Moving", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Standing", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Moving/Feeding", "Standing", "Standing", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Standing", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving")), class = "data.frame", row.names = c(NA,
-215L))

Here's resp41366_observed. The resp41366 dataset used above is simply resp41366_observed without resp41366$observed:
> dput(resp41366_observed)
structure(list(ACTIVITY_X = c(29L, 34L, 51L, 78L, 18L, 4L, 27L,
19L, 23L, 21L, 19L, 52L, 71L, 141L, 103L, 59L, 85L, 129L, 86L,
129L, 82L, 67L, 79L, 49L, 51L, 32L, 27L, 48L, 10L, 2L, 18L, 29L,
39L, 70L, 64L, 88L, 90L, 94L, 69L, 91L, 80L, 81L, 92L, 109L,
96L, 84L, 67L, 89L, 85L, 67L, 79L, 68L, 88L, 72L, 67L, 65L, 71L,
79L, 63L, 64L, 36L, 56L, 61L, 80L, 49L, 45L, 65L, 59L, 58L, 62L,
49L, 58L, 68L, 52L, 78L, 51L, 73L, 75L, 80L, 75L, 89L, 63L, 33L,
41L, 44L, 34L, 43L, 9L, 11L, 21L, 30L, 34L, 41L, 30L, 24L, 31L,
65L, 52L, 21L, 35L, 39L, 35L, 27L, 32L, 38L, 38L, 56L, 65L, 81L,
28L, 38L, 10L, 32L, 45L, 26L, 8L, 0L, 19L, 56L, 7L, 0L, 23L,
13L, 1L, 2L, 29L, 15L, 15L, 1L, 33L, 3L, 45L, 143L, 46L, 78L,
76L, 81L, 44L, 89L, 15L, 45L, 52L, 49L, 64L, 55L, 52L, 72L, 68L,
95L, 66L, 74L, 103L, 49L, 26L, 7L, 29L, 25L, 31L, 7L, 13L, 12L,
3L, 22L, 40L, 40L, 47L, 9L, 29L, 9L, 11L, 14L, 4L, 58L, 53L,
60L, 30L, 40L, 42L, 41L, 48L, 40L, 31L, 51L, 29L, 33L, 76L, 38L,
35L, 27L, 46L, 60L, 54L, 47L, 55L, 35L, 51L, 64L, 63L, 32L, 43L,
52L, 47L, 41L, 64L, 54L, 56L, 66L, 64L, 33L, 26L, 28L, 33L, 45L,
53L, 46L, 37L, 39L, 52L, 31L, 1L, 0L, 56L, 19L, 17L, 21L, 33L,
68L, 61L, 78L, 31L, 0L, 11L, 63L, 62L, 43L, 42L, 154L, 4L, 187L,
43L, 56L, 49L, 62L, 46L, 71L, 56L, 46L, 66L, 14L, 0L, 0L, 7L,
0L, 0L, 0L, 17L, 39L, 23L, 0L, 0L, 0L, 4L, 3L, 9L, 8L, 14L, 7L,
17L, 2L, 6L, 0L, 67L, 49L, 0L, 7L, 2L, 0L, 3L, 0L, 0L, 11L, 0L,
2L, 4L, 10L, 4L, 3L, 55L, 41L, 34L, 43L, 21L, 0L, 6L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 4L, 81L, 63L, 44L, 30L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 27L, 41L, 38L, 26L, 30L, 44L, 57L, 69L, 31L, 54L,
32L, 60L, 37L, 15L, 55L, 49L, 52L, 59L, 49L, 9L, 8L, 12L, 11L,
14L, 20L, 54L, 43L, 64L, 53L, 61L, 108L, 39L, 63L, 54L, 56L,
60L, 46L, 64L, 15L, 3L, 8L, 43L, 90L, 43L, 64L, 38L, 13L, 12L,
46L, 24L, 1L, 30L, 9L, 58L, 105L, 2L, 4L, 2L, 4L, 8L), ACTIVITY_Y = c(19L,
30L, 47L, 38L, 17L, 0L, 20L, 11L, 11L, 8L, 13L, 46L, 105L, 133L,
131L, 64L, 76L, 94L, 58L, 69L, 47L, 57L, 155L, 49L, 72L, 43L,
38L, 53L, 4L, 1L, 12L, 22L, 43L, 91L, 72L, 80L, 74L, 89L, 93L,
115L, 79L, 89L, 85L, 103L, 87L, 84L, 71L, 98L, 83L, 81L, 83L,
74L, 85L, 83L, 58L, 86L, 63L, 55L, 64L, 54L, 34L, 46L, 88L, 71L,
69L, 51L, 58L, 53L, 53L, 67L, 57L, 70L, 71L, 77L, 59L, 74L, 58L,
61L, 93L, 77L, 72L, 73L, 13L, 14L, 24L, 25L, 29L, 4L, 5L, 3L,
13L, 14L, 16L, 10L, 7L, 13L, 54L, 38L, 17L, 19L, 20L, 15L, 10L,
8L, 19L, 15L, 26L, 75L, 62L, 31L, 34L, 9L, 31L, 59L, 27L, 0L,
0L, 3L, 59L, 5L, 0L, 14L, 6L, 0L, 0L, 28L, 7L, 14L, 0L, 24L,
6L, 34L, 168L, 68L, 115L, 103L, 67L, 35L, 122L, 39L, 42L, 42L,
43L, 47L, 44L, 39L, 77L, 43L, 112L, 68L, 59L, 188L, 127L, 25L,
3L, 15L, 15L, 25L, 0L, 6L, 3L, 0L, 30L, 30L, 21L, 38L, 6L, 20L,
17L, 7L, 8L, 5L, 61L, 87L, 44L, 57L, 43L, 73L, 87L, 46L, 97L,
42L, 60L, 29L, 34L, 75L, 43L, 83L, 42L, 86L, 105L, 78L, 72L,
103L, 51L, 88L, 74L, 66L, 42L, 36L, 45L, 77L, 60L, 69L, 49L,
61L, 53L, 44L, 71L, 23L, 28L, 21L, 24L, 61L, 39L, 28L, 29L, 53L,
39L, 0L, 2L, 29L, 25L, 23L, 16L, 43L, 70L, 107L, 149L, 62L, 1L,
5L, 63L, 61L, 32L, 159L, 209L, 1L, 255L, 68L, 68L, 90L, 94L,
64L, 92L, 97L, 75L, 77L, 15L, 0L, 0L, 12L, 0L, 0L, 0L, 33L, 56L,
37L, 0L, 0L, 0L, 1L, 0L, 3L, 6L, 4L, 0L, 11L, 0L, 1L, 0L, 41L,
61L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 3L, 0L, 5L,
54L, 51L, 26L, 30L, 31L, 0L, 0L, 0L, 5L, 0L, 0L, 0L, 0L, 0L,
16L, 88L, 55L, 42L, 24L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 15L,
30L, 29L, 21L, 26L, 43L, 56L, 40L, 22L, 6L, 19L, 16L, 15L, 13L,
46L, 59L, 88L, 41L, 35L, 9L, 1L, 2L, 5L, 6L, 4L, 40L, 24L, 55L,
41L, 56L, 210L, 26L, 127L, 67L, 65L, 73L, 41L, 47L, 8L, 1L, 10L,
23L, 76L, 36L, 79L, 15L, 0L, 2L, 46L, 39L, 4L, 23L, 2L, 48L,
141L, 1L, 0L, 1L, 1L, 4L), observed = c("Feeding/Moving", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Moving/Feeding", "Standing", "Standing", "Standing",
"Moving/Feeding", "Standing", "Standing", "Standing", "Standing",
"Standing", "Moving/Feeding", "Standing", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Moving/Feeding",
"Standing", "Standing", "Standing", "Standing", "Standing", "Standing",
"Standing", "Standing", "Standing", "Standing", "Standing", "Standing",
"Standing", "Standing", "Standing", "Standing", "Standing", "Standing",
"Standing", "Standing", "Standing", "Moving/Feeding", "Standing",
"Standing", "Standing", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Standing", "Standing", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Standing", "Moving/Feeding",
"Standing", "Moving/Feeding", "Standing", "Standing", "Standing",
"Standing", "Standing", "Standing", "Feeding/Moving", "Feeding/Moving",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Moving/Feeding", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Moving/Feeding", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Moving/Feeding", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Moving/Feeding", "Feeding/Moving", "Moving/Feeding", "Standing",
"Standing", "Moving/Feeding", "Moving/Feeding", "Feeding/Moving",
"Moving/Feeding", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Moving/Feeding", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Moving/Feeding", "Feeding/Moving", "Moving/Feeding",
"Standing", "Moving/Feeding", "Standing", "Standing", "Standing",
"Moving/Feeding", "Standing", "Feeding/Moving", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Standing", "Moving/Feeding", "Standing", "Standing",
"Standing", "Standing", "Standing", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Moving/Feeding", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Moving/Feeding", "Standing", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Standing", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Standing", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Standing",
"Moving/Feeding", "Moving/Feeding", "Standing", "Moving/Feeding",
"Standing", "Standing", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Feeding/Moving", "Moving/Feeding", "Feeding/Moving",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Feeding/Moving",
"Feeding/Moving", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Moving/Feeding", "Standing", "Standing", "Standing",
"Moving/Feeding", "Feeding/Moving", "Feeding/Moving", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Standing", "Standing", "Feeding/Moving",
"Standing", "Moving/Feeding", "Moving/Feeding", "Standing", "Standing",
"Moving/Feeding", "Standing", "Standing", "Moving/Feeding", "Standing",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Moving/Feeding", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Moving/Feeding",
"Moving/Feeding", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Standing", "Moving/Feeding",
"Moving/Feeding", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Moving/Feeding",
"Moving/Feeding", "Feeding/Moving", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Feeding/Moving", "Moving/Feeding",
"Feeding/Moving", "Moving/Feeding", "Feeding/Moving", "Feeding/Moving",
"Moving/Feeding", "Moving/Feeding", "Standing", "Moving/Feeding",
"Moving/Feeding", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Moving/Feeding",
"Standing", "Moving/Feeding", "Standing", "Moving/Feeding", "Moving/Feeding",
"Moving/Feeding", "Moving/Feeding", "Moving/Feeding", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Moving/Feeding", "Standing",
"Moving/Feeding", "Standing", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving", "Moving/Feeding", "Moving/Feeding", "Feeding/Moving",
"Feeding/Moving", "Feeding/Moving", "Moving/Feeding", "Standing",
"Feeding/Moving", "Feeding/Moving", "Feeding/Moving", "Feeding/Moving",
"Feeding/Moving")), row.names = c(NA, -374L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x0000000002541ef0>)

Answer:
I would suggest you to use frameworks for your classification or ML tasks, e.g. MLR or CARET.
Maybe you prepare your data such that train and test are consistent before pushing them into the pipeline and let the framework let do the split (resmapling).
Comment: Thank you for your answer. Yes, I thought about your point 2. Would you have a code suggestion that at least could send me on the right track?
Comment: Without having example data, it is difficult to provide a final answer. It looks like that sometimes the labels are shuffled. You may try to map your class column in train/test to factor with the same levels, e.g. `factor(df$var, levels = c(...))` and try it again.
Comment: I uploaded some `dput()` date and some extra code in my original post that should help a lot with the replicability of my question.


How to make pagination in Laravel when the URL length exceeds its limit

Question: I am working on a project with Laravel 5.2
I have hidden ID values and I want to search the ID from the database and later I will sort it in descending order.
I wrote this code.
Controller
$jsonObject =json_decode(request('membersdata'));
$member = (new Membermasternewdata)->newQuery();
$members=$member->whereIn('id', $jsonObject)->latest();
$members=$members->paginate(50);

View
The HTML page
{{$members->appends(request()->except('page'))->links()}}

My URL example http://localhost:8000/ascendingregistrationdate?_token=ktlNHgx9PLNCOQL0CE1YZT2AzmWpJeXexqOduy8F&membersdata=%5B199%2C284%2C344%2C355%2C381%2C461%2C488%2C576%2C601%2C652%2C747%2C825%2C849%2C878%2C883%2C912%2C913%2C915%2C972%2C1004%2C1071%2C1310%2C1501%2C1534%2C1585%2C1610%2C1677%2C1854%2C1923%2C1935%2C2163%2C2301%2C2302%2C2326%2C2339%2C2717%2C2773%2C3052%2C3361%2C3446%2C3683%2C3848%2C3853%2C3914%2C4114%2C4244%2C4311%2C4357%2C4389%2C4881%2C5312%2C5322%5D&page=2
I got a problem with pagination. For around 400 records, the pagination works.  But If I have many records, pagination doesn't work as the URL length exceed its limit. Is there any workaround for this problem?
Thank you!
Comment: Just a sidenote, Laravel 5.2 has been EOL for almost a year now, please consider updating to at least 5.5: https://endoflife.software/programming-languages/frameworks/laravel
Comment: @Loek , that is right. Unfortunately, the client-server PHP version is a bit old. That is why I use Laravel 5.2 for this project.
Answer: Rather than using a GET request for the search, why don't you switch to using POST instead. That way, the memberdata array can be passed as POST data, which can have larger limits for the data (depending on your PHP config, this would be 2+ MB.
The memberdata in the URL is what's causing the URL to exceed the max limit, so you need to remove that from the URL.


How does the choice of strings impact sound and playability?

Question: I recently bought a classic series '50s Fender Telecaster. Beautiful guitar with 2 peculiar vintage-style pickups and vintage-style machine heads. It's best when I play classic rock songs, with clean channel tube amp.
I'm wondering if the choice of the strings on this guitar could have a very significant impact on its sound and playability. Which factors have to be considered in the choice of the strings?
Comment: I've discussed the question of how different string affect playability in my answer below. The question about which strings would be best for your guitar seems like both a gear search question and largely a matter of opinion (or at least personal taste, which is another word for opinion I would think). I suggest you edit out your last question and leave the overall question about how strings affect playability.
Comment: In the interest of keeping this question open, I've tweaked it as Todd suggests.  I would recommend that you try out a bunch of different strings and see what works best for you.
Answer:
I'm wondering if the choice of the strings on this guitar could have a very significant impact on its sound and playability.

Yes, definitely. Well, I suppose it might depend on what you consider "significant". In terms of the sound, the change between string gauges can be subtle, but I notice it right away on my guitars - perhaps because I'm so familiar with how they sound. I might not notice as easily if someone else changed guages on their guitar.
But there's no question that string guage affects playability. That and the setup of the guitar (neck relief, neck angle, saddle height, nut slot depth, etc.) are pretty much the only things that can be changed that affect the playability. Neck geometry and bridge and body design are the only other factors I can think of, but they can't be changed without changing major parts of the guitar.
Lighter guage strings require less finger pressure to fret or bend, and tend to have a thinner, brighter sound. The ease of bending lighter strings has a downside in that it's easier to accidentally bend them which can worsen intonation.
Heavier strings require more force to fret and bend and can be harder to play, and they usually have a fatter sound that might be slightly less bright. They can actually be a bit easier to play in some ways in that you have better tactile feedback and better intonation.
Personally I find that I like heavier guages, even for playability, because it seems like heavier guages tend to have a smaller maximum displacement when vibrating, possibly because they have to be under higher tension. That means that I can have a lower setup with less neck relief without fret buzz. By having a flatter setup and using the minimal pressure necessary and optimum finger placement, I can play more cleanly with better intonation and I find the guitar feels better.
The point of the last paragraph is to say that one shouldn't assume that it's a simple equation of "thinner is easier to play and thicker sounds better". There are lots of different interactions with string guage, sound, and playability, and the setup of the guitar is affected by the guage and affects playability, so there are many variables at work.
Comment: +1. Back in the early 1950s a Telecaster would be strung with very heavy 0.013 - gauge strings. These days a Telecaster will come from the factory with the popular, easy-to-play 0.009 - gauge strings. If you want to go with heavier strings, pay a guitar technician for a full setup for your instrument. This should calibrate the guitar to make it much easier to play and with better intonation.
Comment: I used to have 13s on an archtop, but if I didn't practice on it every day, my hand and fingers didn't maintain enough strength and callus and I had to fight the instrument. Since I'm a casual guitarist I switched to a hard-tail Stratocaster with 10s and it's no struggle. But I certainly liked the tone and the tuning stability and intonation of the 13s. It was just too much effort for me.
Comment: @WheatWilliams Even acoustics are shipping with 12s these days. I've had 12s with a solid G string on my Les Paul before and it was great. Sadly my fingers are not in shape for that right now, nor is the Les Paul.
Comment: I've always like the 'best of both worlds', light top, heavy bottom [I actually use Ernie Ball 'skinny top, heavy bottom, which go 10 - 52 but no doubt lots of makers do them] I came to 6-string from bass & found that with standard 10s I would just squeeze them out of tune all the time. I tried heavier standard gauges but my fingers didn't like the plain strings, so I ended up with that compromise.


Algebraic and Geometric Multiplicity

Question: I am having a hard time understand these two concepts
Algebraic multiplicity and Geometric multiplicity of a matrix regarding its eigenvalues
for example
if I have the matrix:
<code>| 5 0 0 |
| 1 5 0 |
| 0 1 5 |
</code>
The eigenvalues are 5,5,5, so what does this mean about its multiplicity?
Is geometric multiplicity the number of similar eigenvalue? In this case, 3
and algebraic multiplicity the number of unique eigenvalue? In this case, 1
thanks
Answer: The geometric multiplicity of an eigenvalue is defined to be the number of linearly independent eigenvectors associated with that eigenvalue.
The algebraic multiplicity of an eigenvalue is defined as the eigenvalue's multiplicity as a root of the characteristic polynomial.
Comment: the characteristic equation is det(A-$\lambda$I)=0. And yes if it has n roots then it has algebraic multiplicity of n.
Comment: what do you mean by " as a root of the characteristic equation" ? If the characteristic equation has n roots, does it mean it has algebraic multiplicity of n?
Comment: For example, consider the characteristic equation $\lambda^2-4\lambda+4$. Then it does have two roots, but note that it has only have 1 distinct root: $\lambda = 2$.   Hence, $\lambda$ would have algebraic multiplicity of 2.
Answer: You have the types of multiplicity reversed. Geometric multiplicity here basically means how many different eigenvectors can you create given these eigenvalues. the eigenvalues are the same, therefore the number of distinct eigenvectors is the same. You have geometric multiplicity of 1. Algebraic multiplicity is how many solutions does the solving for eignenvalues give you. It doesn't matter if the solutions are the same. So you have algebraic multiplicity of 3.

Algebraic and Geometric Multiplicity


Why have a clef change right after a previous clef?

Question: I came across this section in Mozart's piano sonata no.
It shows a clef change at the start of the measure, but the bass clef is shown right before it. Why would this be needed if the measure uses the treble clef and does not use the bass clef?
I'm sorry if the doubt seems amateurish, but it's the first time I'm coming across such a thing.
Comment: Is this the very beginning of the piece? If so, we have an excellent question on our hands. If not, we might still have a dupe.
Comment: It  isn't the very beginning of the piece of as far as I'm concerned. I'm starting to think that it could be a mistake with the uploader as the other versions didn't have this. **For those concerned about the origins of the image, look up piano sonata no. 7 on Wikipedia and this is the image which pops up. I know it would be stupid to trust the genuinety of Wikipedia when it comes to sheet music and that I must look at more authentic sites**, but I thought I'd ask it  nonetheless as I could have been wrong in this assumption as well. Could someone please clarify for me?
Comment: Does this answer your question? [Two different clefs at the start of a piece on the same hand](https://music.stackexchange.com/questions/111572/two-different-clefs-at-the-start-of-a-piece-on-the-same-hand)
Comment: @LiamGallagher This example is not the start of the piece.  Rather, it is measure 148 or so.  And actually it starts on beat 2 of that measure; beat 1 is presumably at the end of the previous system.
Answer: So, here we have a clef change. The line before the line in question has the bottom staff in the bass clef, and in our first line here, the music begins with the treble clef. This change of clefs happens of on the first bar of the new line. So, why do we write a bass clef, only, only to have it immediately change to a treble clef? Why not just start the next line with a treble clef?
Well, the reason for this is simple: cautionary clef. We want to make the clef change obvious to someone who is sight reading. When a pianist is sight reading, he or she often do not pays attention to details, such as the clef at the beginning of the line, or the key signature. The pianist often assumes it's the same clef, and the same key signature. So if we were to suddenly put a treble clef, it might confuse the pianist who is sight reading. By continuing the line with a bass clef, and putting the treble clef immediately after it, what we are signalling is this: "here is a clef change!" in the most obvious way possible, that is, by ignoring the fact it is on the first bar of the line and treating it like any other clef change.
Of course, this is not necessary to pianists who practised the piece well in advance, they are neither benefited, nor hurt by this notation. But we want to be courteous to people who are sight reading. They need things to be really obvious.
Comment: If I recall correctly standard practice is to indicate the clef change at the end of the previous system and then print two treble clefs (in this example) in the second system.  In other words, the example in question is notated incorrectly.
Comment: It's not incorrect – there are no hard rules concerning this – and if there are, these rules are a modern invention, certainly not concerning the old editions or modern editions trying to be faithful to old editions and manuscripts.

While slightly unusual, it's actually quite comfortable to read.

Also, note that the measure in question is incomplete, having only three beats – the first beat being on the previous line (the line break was inside the measure).
Comment: It is certainly not an attempt to be faithful to any manuscript or old engraving. The first edition of this sonata has the left hand part in the upper staff, so there is no clef change at all. The other editions have the first beat of the measure between the bass clef and the treble clef, where it belongs. It's possible that this edition was created by some authority on innovative modern approaches to notation, but the more likely explanation is that it was created by someone who didn't know what they were doing. Breaking a measure like that after the first beat isn't unusual; it's unheard of.
Answer: It would be more usual to have a (small) cautionary treble clef at the end of the previous stave, start the new one with a normal, full-size clef.
You sometimes see it done the way shown in hand-written scores using pre-printed 'piano layout' manuscript paper.
But the example looks like it's been prepared in Sibelius.  It is actually quite hard to make Sibelius notate a clef change this way!  And where's the first beat of the bar?  This notation would make perfect sense if there was one beat of music in bass clef starting the bar.
Perhaps noorav@ could give better details of where this was found?
Comment: The measure in question only has three beats anyway, it's obviously an amateurish typesetting job. Splitting a measure across systems is sometimes necessary but in a Mozart sonata? Nope.
Comment: Be nice to see the previous bar, wouldn't it?
Comment: The deficient bar is the last bar but 7 of the first movement of Mozart's piano sonata 7 K309. In the lower stave, the first beat, and the whole of the previous bar, are in the bass clef. I wondered if the source of the image in the OP might have been a score someone created by using a program to lay the score out, and then uploaded to IMSLP. IMSLP has several such scores of various public-domain works, and in those scores produced using a program that isn't Lilypond, the layout is appalling. But IMSLP has no such scores for K309.


new Date('yyyy-MM-ddTHH:mm:ss') without locale

Question: I am based in the UK so when I attempt to parse a new date in JavaScript as follows:
new Date('2016-06-03T09:05:15');

Results in the following date:
Fri Jun 03 2016 10:05:15 GMT+0100 (BST)

I want the date to be parsed as is, and for no locale adjustments (in this instance, BST) to occur. Is this achievable without writing my own date/time parser?
Comment: There's no such thing as an "as is" date -- there is always a locale implied.  Closest you can get is do everything in UTC/GMT.
Comment: When dealing with dates, you might want to consider using something like [Moment.js](http://momentjs.com/) or [Date.js](http://www.datejs.com/), which are the de-facto standards for handling this type of operation and might make your life easier.
Comment: Hey @RionWilliams ironically I am using Date.js :) however, `Date.parse` is not parsing all dates. Am I missing a trick?
Comment: those two things are different textual representations of the exact same data.
Comment: Possible duplicate of [Where can I find documentation on formatting a date in JavaScript?](http://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript)
Answer:
I want the date to be parsed as is, and for no locale adjustments (in this instance, BST) to occur

That is exactly what should occur, however it doesn't in all browsers. You should not parse strings using the Date constructor or Date.parse (they are equivalent for parsing). Always manually parse strings, a library can help but usually isn't necessary.
According to EMCAScript 2015, '2016-06-03T09:05:15' should be parsed as a "local" date (i.e. based on the host system settings for date, time and time zone on the date and time supplied). A Date object's time value is UTC, so when creating the time value, the host settings are taken into consideration. The same settings are also used for output, so if the OP string is correctly parsed and then written to output, you should get back exactly the same date and time (though probably in a different format).
If you're seeing a different time from the input string, then the string isn't being correctly parsed (hence advice to manually parse strings).

Is this achievable without writing my own date/time parser?

Yes, use a library that someone else wrote. However, if you also want host settings to be ignored for output, you'll also need to write your own formatter, or use a library.
The good news is that there are many to choose from.


Find the conditional CDF of the sum of exponential r.v given X = x

Question:
Let $X$ and $Y$ be i.i.d. $\text{Expo}(λ)$, and $T = X + Y$ .
(a) Find the conditional CDF of $T$ given $X = x$.
(b) Find the conditional PDF $f_{X\mid T}(x\mid t)$, and verify that it is a valid PDF.

Can you help me to verify that the PDF is valid?
I found the following PDF
$P(T \le t\mid  X=x)=P(Y \le t-x)=1-e^{-λ(t-x)}\implies$
$f(T \le t \mid X=x)=λe^{-λ(t-x)}$, to verify that it is valid:
$\int_{0}^{\infty} λe^{-λ(t-x)}$ and I compute that the integral is divergent!
Comment: Consider: What is the support for $Y+x$ ?
Answer: The integral is not divergent. \begin{align*}\int\limits_{0}^{\infty}f_{T|X}(t|x)\text{d}t=\int_{x}^{\infty}\lambda e^{-\lambda(t-x)}\text{d}t=\left.-e^{-\lambda(t-x)}\right\vert_{x}^{\infty}=1\end{align*}
The reason is that $t\ge x$.


How to find efficiently and systematically audiovisual analysis of pieces?

Question: An elderly relative's debility inhibits  reading music analysis only in writing: so it is off-topic.
I mean 'audiovisual analysis' as analysis of pieces with music history and theory in video with audio, like Japanese pianist Kotaro Fukuma's helpful videos on Bartok's Piano Concerto no. 2 and Ligeti's only Piano Concerto. Particularly helpful are his on-screen:

transcriptions of important music theory terms.
reproductions of parts of scores that he explains or samples by playing on the piano.

How can such analysis be found efficiently, without Googling each piece?
Answer: Some possibilities that you may find interesting:

The Society for Music Theory, the international community for our field, recently began a videocast journal called SMT-V. It's still new, so there aren't many videos, but you can currently find analyses of Mozart, video game music, and Schumann. And even though it isn't analysis, I'll particularly recommend the Repetition and Musicality video.
On the other side of the pond, the Society for Music Analysis also has some video podcasts. Their videos are:

Why do we analyse music?
Aspects of popular music
Analysing musical time
Analysis in context

Lastly, occasionally Music Theory Online, the online journal for the Society for Music Theory, includes audiovisual analyses. This one looks at a Bartók Scherzo, Op. 14, No. 2, and I bet it's a type of analysis that's new to most on this site!

These videos are a bit different than what you're looking for, but I still thought I'd offer them, considering no one else has answered in quite some time.


Remove items from SWT tables

Question: This is more of an answer I'd like to share for the problem I was chasing for some time in RCP application using large SWT tables.
The problem is the performance of SWT Table.remove(int start, int end) method. It gives really bad performance - about 50msec per 100 items on my Windows XP. But the real show stopper was on Vista and Windows 7, where deleting 100 items would take up to 5 seconds! Looking into the source code of the Table shows that there are huge amount of windowing events flying around in this call.. That brings the windowing system to its knees.
The solution was to hide the damn thing during this call:
<code>table.setVisible(false);
table.remove(from, to);
table.setVisible(true);
</code>
That does wonders - deleting 500 items on both XP & Windows7 takes ~15msec, which is just an overhead for printing out time stamps I used.
nice :)
Answer: Instead of table.setVisible(), you should rather use table.setRedraw(). This method on Control has exactly the purpose of suppressing drawing operations during expensive updates.

Remove items from SWT tables


Sessão não faz logoff em php

Question: Estou criando um pequeno site, porem quando aperto para sair, o site desloga, mas se eu coloco o link de uma das páginas, consigo entrar no sistema e não verifica se foi efetuado o login, mesmo com campos de segurança
Login.php:

    <form method="POST" action="validalogin.php">

Área de Login

          E-mail
          <input type="text" class="form-control" id="login" name="login" placeholder="Digite seu e-mail..." />

          Senha
          <input type="password" class="form-control" id="senha" name="senha" placeholder="Digite sua senha..."/>

           <input type="checkbox" value="remember-me"> Relembre-me

        <button type="submit" class="btn btn-entrar">ENTRAR</button>

© 2018

    </form>

      <?php
        if(isset($_SESSION['security'])){
          echo $_SESSION['security'];
          unset($_SESSION['security']);
        }
      ?>

Security.php
<?php
ob_start();
if($_SESSION['login'] == null || $_SESSION['id'] == null){
  $_SESSION['security'] = "Efetue o Login!";
  header("Location: login.php");
}
?>

Fechar.php
<?php
unset($_SESSION['login'], $_SESSION['id'], $_SESSION['usuario']);
session_destroy();
header("Location: login.php");
?>

Comment: Testa mudando o `== null` por `== ""` (string vazia)
Comment: Já tentei, mas não funcionou :/
Comment: Testa então `isset($_SESSION ["nome"])`, se não der faz um `echo` da variável de sessão e coloca na pergunta
Comment: Infelizmente não funcionou nem o echo
Comment: Verifica se a sessão foi iniciada em todas as páginas  (`session_start ()`), tente trocar `ob_start` por `session_start`, se nao me engano para usar o ob também precisa usar `ob_end_flush()`
Comment: Em todas, consegue postar um exemplo que funcione e não burle a segurança do site ?
Comment: Até onde sei pra poder manipular a variável de sessão é necessário chamar a função `session_start();` antes de qualquer outro código php (`<?php session_start(); ...`,  sobre a segurança disso ja não sei dizer
Answer: Considerando que você não deve ter colocado todo o código aqui, eu assumo que o falta é o exit após o header no security.php:
header("Location: login.php");
exit;

Independente de isso resolver o seu problema ou não, é uma boa prática de programação em PHP você colocar o exit após a utilização do header('Location:...').
Também certifique-se que você esteja usando session_start() em algum lugar do seu código antes de usar o unset().
Comment: Todos os php´s iniciam com session_start(), mas não funciona nenhuma alteração, incluir exit em todas páginas que jogam um header no final..
Comment: Então tenta trocar o $_SESSION[xx]==null por isset($_SESSION[..])..
Comment: Consegui resolver, conforme resposta abaixo, obrigado!
Answer: para não editar a pergunta e ficar sem nexo consegui resolver o problema da seguinte maneira:
Em todas minhas páginas php, que o usuário ficará com a sessão ativa, contem um uma verificação inicia:
if(isset($_SESSION['id']) == null)
{
  echo '';
}

Porem, em minha página fechar.php alterei inteiramente o código, para apagar todos os dados da $_SESSION:
<?php
session_start();

// Apaga todas as variáveis da sessão
$_SESSION = array();

// Se é preciso matar a sessão, então os cookies de sessão também devem ser
apagados.
// Nota: Isto destruirá a sessão, e não apenas os dados!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
    $params["path"], $params["domain"],
    $params["secure"], $params["httponly"]
);
header("Location: login.php");
}

// Por último, destrói a sessão
session_destroy();
?>

Desta maneira, funcionou perfeitamente.

Sessão não faz logoff em php


Comment form is not working with ctools popup

Question: I want to display a comment form in popup in drupal 7 website.
I have created a custom module to display comment form in ctools modal and added a link in the views page. Comment form is displaying correctly in ctools modal but comment is not saving when submitting the form.
When we submit the comment form, it does not display any error and redirect to comment form.
I am also using Ajax comments module in the site.
Code snippets for the ctools
/**
 * Implements hook_menu().
 */
function custom_feature_menu() {

  $items = array();

  $items['modal/%ctools_js/comment-popup/%'] = array(
    'title' => t('Comment Block'),
    'page callback' => 'custom_feature_comment_callback',
    'page arguments' => array(1, 3),
    'access callback' => TRUE,
  );

  return $items;

}

/**
 * Callback for
 */
function custom_feature_comment_callback($js = NULL, $nid = NULL) {

  $node = node_load($nid);
  // setting these defaults is needed, otherwise warnings result in dblog

  if (!$js) {
    return drupal_get_form('comment_node_'.$node->type.'_form', (object)$edit);
  }

  $form_id = 'comment_node_' . $node->type . '_form';

  ctools_include('modal');
  ctools_include('ajax');

  $comment = (object) array('nid' => $node->nid);

  $form_state = array(
    'title' => 'Write a Reivew (' . $node->title . ')',
    'ajax' => true,
  );

  $form_state['build_info']['args'] = array($comment);

  $commands = ctools_modal_form_wrapper($form_id, $form_state);

  if (!empty($form_state['executed'])) {

    $commands = array();

    $commands[] = ctools_modal_command_dismiss(t('Your comment has been saved.'));
    $commands = ctools_ajax_command_reload();
  }

  //If form is submittedd
  print ajax_render($commands);

}

I have searched in google and follow the below reference but comment form is not saving comment.

http://internetdevels.com/blog/ctools-modal-api
https://drupal.org/node/1196150
http://deeson-online.co.uk/labs/insert-form-pop-modal-ctools-and-drupal-7

Thanks in advance.
Comment: Are you aware of the [Modal forms](https://drupal.org/project/modal_forms) module? It support the Comment form out of the box.
Comment: Oh, sorry, I knew about it but I thought that it only worked with user pages (login, register, forget password). Thanks, I will look into this.
Comment: Its only working when we reply to existing comment but not working for 'add new comment'.
Comment: @Chapabu, I have found the issue. There is action property in comment form which was redirecting to same form when we submit comment form. So, it seems that comment form is not working properly.
Answer: I have found the issue. There is #action property in comment form which was redirecting to same form when we submit comment form. So, it seems that comment form is not working properly.
I have set up a global variable to remove #action property of the comment form if comment form is displaying in ctools popup.
/**
 * Callback for
 */
function custom_feature_comment_callback($js = NULL, $nid = NULL) {

  $node = node_load($nid);
  // setting these defaults is needed, otherwise warnings result in dblog

  global $comment_popup;
  $comment_popup = 1;

  if (!$js) {
    return drupal_get_form('comment_node_'.$node->type.'_form', (object)$edit);
  }

  $form_id = 'comment_node_' . $node->type . '_form';

  ctools_include('modal');
  ctools_include('ajax');

  $comment = (object) array('nid' => $node->nid);

  $form_state = array(
    'title' => 'Write a Reivew (' . $node->title . ')',
    'ajax' => true,
    're_render' => FALSE,
    'no_redirect' => TRUE,
  );

  $form_state['build_info']['args'] = array($comment);

  $commands = ctools_modal_form_wrapper($form_id, $form_state);

  if (!empty($form_state['executed']) || !empty($form_state['ajax_commands'])) {

    $commands = array();

    $commands[] = ctools_modal_command_dismiss(t('Your comment has been saved.'));
    $commands[] = ctools_ajax_command_reload();
  }

  //If form is submittedd
  return ajax_deliver(array('#type' => 'ajax', '#commands' => $commands));

}

function custom_feature_form_alter(&$form, &$form_state, $form_id ) {

  if ($form_id == 'comment_node_article_form') {

    global $comment_popup;

    if ($comment_popup == 1) {

      $comment = $form_state['comment'];

      // If not replying to a comment, use our dedicated page callback for new
      // comments on nodes.
      if (empty($comment->cid) && empty($comment->pid)) {
        // Change the action to call our function.
        $form['#action'] = url('modal/nojs/comment-popup/' . $comment->nid);
      }

      $comment_popup = 0;
    }
  }

}


Triples of Numbers

Question: I have a question:
How many triples $(a,b,c)$ are there such that $$\frac{1}{a}+\frac{1}{b}+\frac{1}{c} = 1$$ and $a <b<c$? They have to be positive integers. Also find those triples.
I know that all of them have to be $\geq 2$. So do I just fix a number and count the other pairs?
If I choose $a = 3$ then I count the other pairs $(b,c)$? If I choose a very large $a$ then it seems that no triples will satisfy the condition since the sum will be too small.
Comment: @James Your question is well-written. +1 for telling us your thoughts. But I feel the tags should be changed. [combinatorics] doesn't seem to be relevant, and [number-theory] should be replaced by [elementary-number-theory].
Comment: If $a = 3$, then we must have $b \geq \ldots$ and $c \geq \dots$. Is this possible?
Comment: You can just fix a number and count. There's a clear upper bound for $a$, and for each $a$, see my comment to mixedmath's answer.
Answer: Well, $\frac{1}{3} + \frac{1}{4} + \frac{1}{5} < 1$, so we must have $a=2$. So we really just need $\frac{1}{b} + \frac{1}{c} = \frac{1}{2}$.
Since $\frac{1}{4} + \frac{1}{5} < \frac{1}{2}$, $b = 3$. That leaves $c = 6$.
I think a nice way to think about it is to view the number $1$ as $\frac{1}{1}$. We can decompose $\frac{1}{n}$ into $\frac{1}{n+1} + \frac{1}{n^2+n}$, then decompose one of those to get an expression for $\frac{1}{n}$ as the sum of three harmonic numbers. In this case, we see that $\frac{1}{1} = \frac{1}{2} + \frac{1}{2} = \frac{1}{2} + \frac{1}{3} + \frac{1}{6}$.
See the Leibniz Harmonic Triangle.
Answer: HINT
$$
\frac{1}{a} + \frac{1}{b} + \frac{1}{c} \lt \frac{1}{a} + \frac{1}{a} + \frac{1}{a},
$$
which shows that $a \leq \ldots$.1
(After fixing $a$, you can use the same idea again to complete the proof.)

1EDIT: Corrected the first inequality sign from $\gt$ to $\lt$.
Comment: +1 I wish this were the only hint given for a while.  A good one.
Answer: Suppose we fix a, small enough that solutions exist. Then we have some sort of equation of the form $\frac{1}{b} + \frac{1}{c} = K$, or that $1 + \frac{b}{c} = bK \implies \frac{b}{c} - bK = b(\frac{1}{c} - K) = -1 \implies b = \dfrac{-1}{\frac{1}{c} - K}$
That is to say, that there are still infinitely many solutions for just 2 variables (under the assumption that $c \not = 0$ and $\frac{1}{c} - K \not = 0$. I note that there are infinitely because these solutions fall in a range, and if the ordering is backwards then we simply switch the roles of the variables. So that does not play a big role.
Comment: For two variable case, one should handle it this way: $Kbc = b+c \Rightarrow K^2bc - K(b+c) + 1 = 1 \Rightarrow (Kb - 1)(Kc -1) = 1$.
Comment: Clever. Now I leave my answer so that your comment is also left.
Comment: @Soarer One can also observe that $Kbc = b+c$ does not have any solution unless $K\leq 2$, since $b+c \leq b \cdot c+ b \cdot c < 3bc$.
Comment: @Srivatsan Nice.

Triples of Numbers


Migration after server crash: maintenance mode and/or cache problem

Question: I had a crash of my previous server and I tried to rise my website from the dead. I had backups of all the files & of the database (PostgreSQL). I was not the one who set up the website and my knowledge of Drupal is pretty low.
From what I understood/gathered, it is a 7.54 version and it runs with multisite.
What I did so far:

Import my database backup in PostgreSQL (in the dumbest way possible: recreate the right database & user, import everything back in place);
Upload all the files to my new server (running Debian Jessie);
Give access to the sites/ directories to www-data user;
Clear the sites/mysite/css/ and sites/mysite/js/ directories;
Disable CSS & JS aggregation (using drush).

I did the latest because the style of the website was broken; that was enough to revive it.
I still have on major issue: when I log in, I get the maintenance message. I therefore tried to disable maintenance_mode with drush; it didn't work.
I saw it could be related to cache issues; I therefore tried to clear the cache (once again with drush with drush cc all). It put the whole site in maintenance, and not only when I'm logged in.
I am not sure where the problem comes from. Any hint or suggestion would be greatly appreciated!
Comment: If you're logged in with admin (using default login form "sitename.com/user/login"), you can try switching the maintenance setting, and clear site cache by navigating to "admin => configure => development => performance"
Comment: @Yogesh I can't access the administration pages; when I log with a user with administrator rights, I still get stuck with the maintenance message.
Comment: Try logging in with user 1, if you don't have password for this user you can reset it using [this doc](https://www.drupal.org/node/44164). You should be able to do anything after logging in with user 1.
Comment: @Yogesh I changed user 1 password and logged in, but I still get the same issue. I check roles with `drush user-information {user1}` and it only has `authenticated user `; it seems to me that could be a problem.
Comment: you can try setting administrator role to user 1 using steps provided in [this ans](https://drupal.stackexchange.com/a/169874).
Comment: @Yogesh It just did that but I'm still stuck. Once logged in, I tried to access `http://example.com/admin/` but I got an Error.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/65122/discussion-between-yogesh-and-mbr).
Answer: Here is finally how I solved the problem with Yogesh help: when I tried to access the admin section while logged in as an administrator, I got an error. I therefore checked the watchdog table. The image_dimensions table was somehow missing:
[...] Undefined table: 7 ERROR: relation "image_dimensions" does not exist [...]

I created the missing table, and everyhting was then working (access to the admin section, access to the user section and so on).


Enable customer profile permissions

Question: I was testing the customer profile permissions demo here: Customer Profile Demo
I noticed that it would not read my email, and each time instructs me to "enable customer profile permissions in the Amazon Alexa app" which I have done and it just repeats the message.
As I thought it would all be automated by voice, my only question is,

Would the end user have to go through this step of manually enabling permissions and typing in their password?
Answer: No, not all the processes can be automated through voice for security and privacy reasons. One major field here is password acquisition.
As stated in Developer documentation,

Configure your skill in the developer console to indicate that it
  requires customer contact information. As a result, when the customer
  enables the skill, the customer is prompted, in the Alexa app, to
  consent to provide the contact information.

Enable customer profile permissions


Python script to download Java JDK Windows

Question: I'm trying to download Java JDK from Oracle website with a Python script. The code is this:
import urllib2

def download(cookie, license, url, filename):
    print url
    print filename
    opener = urllib2.build_opener()
    opener.addheaders.append((cookie, license))
    f = opener.open(url)
    with open(filename, 'w+') as save:
        save.write(f.read())

cookie = 'Cookie'
license = 'oraclelicense=accept-securebackup-cookie'
url = 'http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-windows-x64.exe'
filename = 'jdk-8u131-windows-x64.exe'

download(cookie, license, url, filename)

The code downloads a file, but the downloaded file with this code has 203 576KB, when the original file should have 202 784KB and when I try to run it it says that is not possible to run this file on my computer.
With the same code, if I change the url and filename variables to the Linux version like this:
url = 'http://download.oracle.com/otn-pub/java/jdk/8-b132/jdk-8-linux-x64.tar.gz'
filename = 'jdk-8-linux-x64.tar.gz'

It works and downloads the file without problems. What can I change in the code to make it work in Windows?
Answer: I figured it out. I wasn't saving the file in binary mode so just need to change the mode from 'w+' to 'wb+' like this:
with open(filename, 'wb+') as save:
        save.write(f.read())


Transforming a time series with a negative number

Question: I have been given data to forecast however it has a negative figure within the data which then, when doing a log transformation to make the series stationary, the ARIMA script i have written won't work.
datan<-c(144627.7451,575166.2487,854245.7137,1230639.153,1160052.421,479928.7072,-261427.4238,1181746.229,168251.621,556741.5149,1840484.518,1704679.404,1878380.278,1865288.502,1849340.253,1965974.112,2093192.242,1912399.391,2633179.421,2134618.008,2070856.492,1238565.331)

freqdata<-4
startdata<-c(9,2)
horiz<-4
datats<-ts(datan,frequency=freqdata,start=startdata)
force.log<-"log"
datadates<-as.character(c("9q2","9q3","9q4","10q1","10q2","10q3","10q4","11q1","11q2","11q3","11q4","12q1","12q2","12q3","12q4","13q1","13q2","13q3","13q4","14q1","14q2","14q3"))
dataMAT<-matrix(0,ncol=freqdata,nrow=(length(datats)+freqdata),byrow=TRUE)
for (i in 1:freqdata)
  {dataMAT[,i]<-c(rep(0,length=i-1),lag(datats,k=-i+1),rep(0,length=freqdata-i+1))}
dataind<-dataMAT[c(-1:(-freqdata+1),-(length(dataMAT[,1])-freqdata+1):-(length(dataMAT[,1]))),]
dataind2<-data.frame(dataind)
lm1<-lm(X1~.,data=dataind2)
lm2<-lm(X1~X2+dataind2[,length(dataind2[1,])],data=dataind2)
library(lmtest)
library(car)
bptest1<-bptest(lm1)
bptest2<-bptest(lm2)
gqtest1<-gqtest(lm1)
ncvtest1<-ncvTest(lm1)
ncvtest2<-ncvTest(lm2)
if(force.log=="level")
  {aslog<-"n"}else
    {{if(force.log=="log")
       {aslog<-"y"}else
         {if(bptest1$p.value<0.1|bptest2$p.value<0.1|gqtest1$p.value<0.1|ncvtest1$p<0.1|ncvtest2$p<0.1)
           {aslog<-"y"}else
              {aslog<-"n"}}}}
if(aslog=="y")
  {dataa<-log(datats)}else
    {dataa<-datats}
startLa<-startdata[1]+trunc((1/freqdata)*(length(dataa)-horiz))
startLb<-1+((1/freqdata)*(length(dataa)-horiz)-trunc((1/freqdata)*(length(dataa)-horiz)))*freqdata
startL<-c(startLa,startLb)
K<-ts(rep(dataa,length=length(dataa)-horiz),frequency=freqdata,start=startdata)
L<-ts(dataa[-1:-(length(dataa)-horiz)],frequency=freqdata,start=startL)
library(strucchange)
efp1rc<-efp(lm1,data=dataind2,type="Rec-CUSUM")
efp2rc<-efp(lm2,data=dataind2,type="Rec-CUSUM")
efp1rm<-efp(lm1,data=dataind2,type="Rec-MOSUM")
efp2rm<-efp(lm2,data=dataind2,type="Rec-MOSUM")
plot(efp2rc)
lines(efp1rc$process,col ="darkblue")
plot(efp2rm)
lines(efp1rm$process,col="darkblue")
gefp2<-gefp(lm2,data=dataind2)
plot(gefp2)
plot(dataa)
pacf(dataa)
sctest(efp2rc)
cat("log series,y/n?:",aslog)

then i want to run arima to get the forecasts
library(tseries)
library(forecast)
max.sdiff<-3
arima.force.seasonality<-"n"
kpssW<-kpss.test(dataa,null="Level")
ppW<-tryCatch({ppW<-pp.test(dataa,alternative="stationary")},error=function(ppW){ppW<-list(error="TRUE",p.value=0.99)})
adfW<-adf.test(dataa,alternative="stationary",k=trunc((length(dataa)-1)^(1/3)))
if(kpssW$p.value<0.05|ppW$p.value>0.05|adfW$p.value>0.05)
  {ndiffsW=1}else
    {ndiffsW=0}
aaW<-auto.arima(dataa,max.D=max.sdiff,d=ndiffsW,seasonal=TRUE,allowdrift=FALSE,stepwise=FALSE,trace=TRUE,seasonal.test="ch")
orderWA<-c(aaW$arma[1],aaW$arma[6],aaW$arma[2])
orderWS<-c(aaW$arma[3],aaW$arma[7],aaW$arma[4])
if(sum(aaW$arma[1:2])==0)
  {orderWA[1]<-1}else
    {NULL}
if(arima.force.seasonality=="y")
  {if(sum(aaW$arma[3:4])==0)
    {orderWS[1]<-1}else
      {NULL}}else
        {NULL}
Arimab<-Arima(dataa,order=orderWA,seasonal=list(order=orderWS),method="ML")
fArimab<-forecast(Arimab,h=8,simulate=TRUE,fan=TRUE)
if(aslog=="y")
  {fArimabF<-exp(fArimab$mean[1:horiz])}else
    {fArimabF<-fArimab$mean[1:horiz]}
plot(fArimab,main="ARIMA Forecast",sub="blue=fitted,red=actual")
lines(dataa,col="red",lwd=2) #changes colour and size of dataa
lines(ts(append(fitted(Arimab),fArimab$mean[1]),frequency=freqdata,start=startdata),col="blue",lwd=2)
if(aslog=="y")
  {Arimab2f<-exp(fArimab$mean[1:horiz])}else
    {Arimab2f<-fArimab$mean[1:horiz]}
start(fArimab$mean)->startARIMA
ArimaALTf<-ts(prettyNum(Arimab2f,big.interval=3L,big.mark=","),frequency=freqdata,start=startARIMA)
View(ArimaALTf,title="ARIMA2 final forecast") #brings up table of the forecasts
summary(Arimab)

If anyone can help me figure out how to forecast this data with the negative i will be really grateful!!
Comment: Consider making a [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Is all of the code you posted relevant to your question?
Comment: @WillBeason i put in my whole code so that people could run it and see exactly what could be changed and where as before i have been told i didnt put enough information in
Answer: You could shift the data by adding a constat, e.g. datats <- datats + 500000,
so that all the values are positive and logs can be taken. Remember to undo this shift and recover the original level when obtaining forecasts (as you already did undoing the logarithmic transformation by taking the exponential).
Why do you take logarithms? The data do not seem to show an increasing variance. I would rather say that there is a level shift around observation $11$.
Comment: Once you create the dummy, for example: `d <- as.numeric(rep(0, length(datats)) + seq_along(datats)>10)`, you can include it through argument `xreg` in `arima` or `auto.arima`, e.g.: `forecast::auto.arima(datats, xreg=d)`. You can also use the package [tsoutliers](http://cran.r-project.org/package=tsoutliers),  e.g. `tso(datats, remove.method="bottom-up")`, which detects the level shift.
Comment: Thankyou for your answer! I had tried this but I wasnt sure if it would cause the forecasts to be inaccurate. I was told to force the logarithm as it created more accurate results...is this not true then?
Comment: I would use the original data and search for an ARIMA model  including as regressor a level shift at observation 11 (a dummy with zeros at observations 1 to 10 and ones at observations 11 to the end of the sample). After the series is adjusted for the shift at time point 11 the variance is relatively homogenous, so there is no need to rescale the data.
Comment: How exactly would i do that? I haven't come across that before


Atualizar o console sem ficar piscando C++

Question: Olá, estou fazendo um jogo da cobrinha, o jogo já está finalizado, porém, creio que pela alta frequência de system("cls"), o console fica piscando, e queria saber como arrumar isso
Aqui minha void com o desenho:
void Draw(){            //Void com todo o Draw;
    system("cls");
    cout << endl;

    for(int i = 0; i < largura+2; i++)              //Printa primeira linha
        cout << "#";

    cout << endl;

    for(int i = 0; i < altura; i++){
            for(int j = 0; j < largura; j++){

            obsPos = false;             //Seta obsPos como falso

            for(int q = 0; q < obsQuantidade; q++){
                if(obstaculoY[q] == i && obstaculoX[q] == j){           //Verifica se o obstaculo está naquela posição, caso esteja obsPos é setado para true;
                        obsPos = true;
                }
            }

            if(j == 0)                 //Printa paredes
                cout << "#";

            if (i == y && j == x){          //Printa cabeça da cobra
                setConsoleColour(DARK_GREEN);
                cout << "O";
                setConsoleColour(WHITE);

            }

            else if (i == FRUTAY && j == FRUTAX)      //Printa fruta
            {
                setConsoleColour(BRIGHT_RED);
                cout << "*";
                setConsoleColour(WHITE);
            }

            else if(obsPos == true){            //Printa o obstaculo com a condição do obsPos como true
                cout << "@";
            }

            else{
                bool printar = false;               //Criando variavel para dar print no corpo da cobra
                for(int k = 0; k < rabo; k++){
                    if(tailX[k] == j && tailY[k] == i){        //Para cada vez que o k for menor que o valor do rabo verificar se ele é igual a um espaço da cobra
                        setConsoleColour(BRIGHT_GREEN);
                        cout << "o";                    //Caso seja printa "o"
                        setConsoleColour(WHITE);
                        printar = true;                 //Caso não coloca variavel printar como true
                    }
                }

                if(!printar){            //Caso printar seja falso coloca espaço em branco
                    cout << " ";
                }

            }

            if(j == largura-1)                  //Printa paredes da direita
                cout << "#";

            }
        cout << endl;

}

Comment: Cara, eu acho que não tem como - afinal, tu estás usando o console para imprimir caracteres. Se isso te incomoda, tens que usar uma biblioteca gráfica.
Answer: O system("cls") é um grande problema para todos os iniciantes que querem fazer um joguinho no console, pois o uso do system já é algo perigoso como também o uso da função cls é péssimo nesse caso, pois ela é lenta somado ao ser uma função do system que também é pesada, por isso conseguimos ver a tela "piscando" com facilidade quando precisamos repetir ele varias vezes.
Entretanto, é possível sim evitar esse problema e conseguir fazer seu jogo funcionar, apesar de não perfeito, existem muitos métodos, inclusive de bibliotecas, que solucionariam seu problema como a conio.h e a curses.h, porém a escolha desses métodos depende de que tipo de limpeza de tela ou atualização de quadro você deseja fazer, nesse exemplo de um jogo da cobrinha creio que o melhor método e o menos datado de todos seria:

Montar o console como se fosse duas matriz com tamanhos que você precisar, a buffer e a frameAtual
Criar uma classe que guarda a matriz buffer(o frame que fica na tela), e a matriz  frameAtual(que guarda as informações mais recentes), junto das posições do player(que pode ser facilmente adaptado para uma cobrinha) e então com os métodos de movimentar o player, checar e atualizar a tela.
O método de atualização seletiva ira rodar um for rodando por toda a tela checando quais a diferenças entre o buffer e o frameAtual e passando as diferenças para tela em tempo real, depois atualizando o buffer de verdade, isso funciona exatamente pois a parte lenta de limpar o console não é o código em sí, é a velocidade de I/O do console do windows, que é muito baixa, então centenas de ifs e um update seletivo acabam sendo muito mais rápido e agradável aos olhos que limpar tudo e refazer.

Fiz um protótipo beem simplista com isso em prática para você usar de base para essa ideia usando apenas um 'A' de player, é um método perfeito para um jogo estilo cobrinha ou tetris, então creio que seja o mais ideal apesar de você precisar adaptar ou reescrever muita coisa que você já tem pronta:
#include <iostream> // acabei usando printf nas coisas por que dizem que é mais rápido kk
#include <windows.h>
#include <conio.h>  //kbhit

#define screenWidth 70
#define screenHeight 30

#define KEY_UP 80
#define KEY_DOWN 72
#define KEY_RIGHT 77
#define KEY_LEFT 75

using namespace std;

void ShowConsoleCursor(bool showFlag);
void setCursorPosition(int x, int y);

class game {
    //Frame atual e frame buffer
    char frameAtual[screenWidth][screenWidth], buffer[screenWidth][screenWidth];
    char Player;
    int plX, plY;

    public:
        //Inicia a posição do player na tela e seta os dois frames como vazio
        void Init() {
            Player = 'A';
            plX = 20; plY = 20;
            for (int y = 0; y < screenHeight; y++) {
                for (int x = 0; x < screenWidth; x++) {
                    frameAtual[x][y] = buffer[x][y] = ' ';
                }
            }
            frameAtual[plX][plY] = Player;
        }
        void MainL() {
            bool loop = true;
            DrawAll();
            while (loop == true) {
                UpdateBuffer();
                Move();
                SelDraw();
            }
        }
    private:
        //função bem simples para registrar o movimento
        void Move() {
            char keyPressed;
            if (kbhit()) {
                keyPressed = getch();

                switch(keyPressed){ //esse switch analisa qual tecla foi digitada
                    case KEY_UP: // Seta para cima
                        frameAtual[plX][plY] = ' ';
                        plY += 1;
                        frameAtual[plX][plY] = Player;
                    break;

                    case KEY_DOWN: // Seta para baixo
                        frameAtual[plX][plY] = ' ';
                        plY -= 1;
                        frameAtual[plX][plY] = Player;
                    break;

                    case KEY_RIGHT: // Seta para direita
                        frameAtual[plX][plY] = ' ';
                        plX += 1;
                        frameAtual[plX][plY] = Player;
                    break;

                    case KEY_LEFT: // Seta para esquerda
                        frameAtual[plX][plY] = ' ';
                        plX -= 1;
                        frameAtual[plX][plY] = Player;
                    break;
                }
            }
        }

        //primeira função de criar a tela vazia
        void DrawAll() {
            for (int y = 0; y < screenHeight; y++) {
                for (int x = 0; x < screenWidth; x++) {
                    printf("%c", frameAtual[x][y]);
                }
                printf("\n");
            }
        }
        //Atualização de frame seletivo - Checa as diferenças no buffer e no frame atual e corrige elas
        void SelDraw() {
            for (int y = 0; y < screenHeight; y++) {
                for (int x = 0; x < screenWidth; x++) {
                    if (frameAtual[x][y] != buffer[x][y]) {
                        setCursorPosition(x,y); printf("%c", frameAtual[x][y]);
                    }
                }
            }
        }

        //Atualizar o buffer setando oq está no frame mais recente nele
        void UpdateBuffer() {
            for (int y = 0; y < screenHeight; y++) {
                for (int x = 0; x < screenWidth; x++) {
                    buffer[x][y] = frameAtual[x][y];
                }
            }
        }
};

int main() {

    ShowConsoleCursor(false);

    game g;
    g.Init();
    g.MainL();
    return 0;
}
//Tirar o cursor da tela (opcional)
void ShowConsoleCursor(bool showFlag)
{
    HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);

    CONSOLE_CURSOR_INFO     cursorInfo;

    GetConsoleCursorInfo(out, &cursorInfo);
    cursorInfo.bVisible = showFlag;
    SetConsoleCursorInfo(out, &cursorInfo);
}
//Pode ser um gotoxy ou qualquer outra função para manipular a posição do cursor
void setCursorPosition(int x, int y)
{
    static const HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    std::coutflush();
    COORD coord = { (SHORT)x, (SHORT)y };
    SetConsoleCursorPosition(hOut, coord);
}


Selecionar colunas sem nome específico

Question: Estou desenvolvendo uma aplicação em C# que consome dados de uma planilha e, em dado momento, preciso de uma string de consulta que vai alimentar uma variável.
Por exemplo:
strComando1 = "SELECT TOP 2 ColunaGenerica1, ColunaGenerica2 FROM ["+ planilha +"]";

Queria saber se é possível e como posso fazer pra consumir dados das duas primeiras colunas, por exemplo, sem especificar o nome delas, uma vez em que o nome das colunas podem variar de acordo com a importação do usuário.
Provider e conexão:
    private static OleDbConnection conexao = new OleDbConnection();

    strConexao = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=0\"", caminhoArquivo);
    conexao.ConnectionString = strConexao;

    private static DataTable tabelaDeSaida;

Comment: Qual provider está usando ? coloca o código da conexão... comando... etc
Comment: Feito. Adicionei informações sobre o provider e a conexão.
Answer: Você pode usar o comando:
DataTable dtCols = conexao.GetSchema("Columns");

ou
DataTable dtCols = conexao.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new Object[] {null, null, "NomeDaTabela", null});

Ele irá retornar um DataTable, que tem as seguintes colunas (entre outras):
TABLE_NAME
COLUMN_NAME
ORDINAL_POSITION

A partir daí, basta pegar a coluna que você quer, da tabela que quiser e montar a query.
Exemplo:
conexao.Open();

DataTable dtCols = conexao.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, new Object[] { null, null, "tabela$", null });

DataRow[] rs = dtCols.Select("ORDINAL_POSITION <= 2");

string query = "Select ";
foreach (DataRow r in rs)
{
    query+= r["COLUMN_NAME"].ToString()+ ",";
}

query = query.Remove(query.Length-1);

query += " From tabela$ where 1=1;";

MessageBox.Show(query);

Resultado:

Select coluna1,coluna2 From tabela$ where 1=1;
Comment: Pensei em uma solução parecida, mas como pegar a primeira e a segunda colunas? Esse é o ponto
Comment: @rLinhares coloquei um exemplo =], e começa pelo 1

Selecionar colunas sem nome específico