Probability distribution of a step by step process

Question: I've come across a "sort of" simple probability problem but I don't know where to start to model it mathematically. The process is the following:

Flip a coin.
If I get tails I roll a die, write down its value and go back to step 1; otherwise the process goes to step 3.
Add up all the values obtained from rolling the dice and call it $X$.  (If I don't get tails the first time I flip the coin then $X = 0$.)

Is it possible to derive a PDF for the value $X$?
What would be the name of this process and how can I model it? I've simulated the process in Python and can't make sense of the shape of the resulting histogram of $X$.
Answer: The process is known as a compound process.
First, let's start by modeling the number of coin flips that come up heads.   Since we are flipping coins until we get a tail, the distribution of the number of heads before we see the first tail is what is of interest, and this is a geometric distribution.
The number distribution on the die is simple; it's uniformly distributed over the integers $1, \dots, 6$.
What we are interested in finding is the distribution of:
$$y = \sum_{i=1}^Nx_i\,\,\text{where  }N \sim \mathrm{Geometric}(p=1/2),\,x_i \sim \mathrm{Uniform}(1,2,3,4,5,6)$$
Unfortunately, there is no nice formula for this; even the distribution when $N=2\,\,(x_1 + x_2)$ is enumerated.  However, it can be approximated with a little effort.
Our approach is to calculate the distribution of $\sum x_i$ for each $N$, then add them together, weighting by the probability of $N$ calculated from the geometric distribution.  Since I'm not so familiar with Python, I've written the code in R:
foo <- function(x, p) {
  x_out <- rep(0, length(x) + 6)
  p_out <- rep(0, length(x) + 6)

  for (i in 1:6) {                         # Iterating over the next dice roll
    for (j in 1:length(x)) {               # Iterating over the current sum
      x_out[i+j] <- i + x[j]               # Adding the dice roll to the sum
      p_out[i+j] <- p_out[i+j] + p[j] / 6  # Calculating the probability
    }
  }

  x_out <- x_out[p_out > 0]
  p_out <- p_out[p_out > 0]
  list(x = x_out, p = p_out)
}

p_y <- rep(0, 100)
tmp <- list(x=1:6, p=rep(1/6,6))
p_y[tmp$x] <- 1/24 # 1/6 * 1/4

for (N in 2:16) {
  tmp <- foo(tmp$x, tmp$p)
  p_y[tmp$x] <- p_y[tmp$x] + tmp$p / (2^(N+1))
}

# Add in the 50% probability of a zero
p_y <- c(0.5, p_y)

We have to cut off our iteration at some point, so I've arbitrarily done so at $N = 16$.  This gives pretty good results:
> sum(p_y)  # ideally equal to 1
[1] 0.9999924

We are missing very little probability mass.
And a plot:
plot(p_y ~ c(0:100),
     xlab = "Sum of dice rolls",
     ylab = "Probability",
     type = "b",
     pch = 16)

Comment: The histogram I generated by simulating on Python is exactly the same! I'll read more on compound processes to have a better understanding, thank you! :)


How does the random coefficient model take care of autocorrelation?

Question: I'm working with time series data. Several variables among subjects are measured at intervals of two weeks over 1.5 years. The main goal is to estimate associations between different variables.
Consider a mixed model with AR(1) autocorrelation. In my sample, time points for measurements are irregular, so the spherical correlation between ordered observations in time may be imprecise. Alternately there is a random coefficient model. How does a random effect structure handle correlation between observations? If the autocorrelation between measurements within subject is constant no matter how far apart in time the measurements are, the model is not an option for me.
Comment: "But I cant se how the autocorrelation is taking care of just because intercept are a random effect within subjects" - because it doesn't.
Comment: See my suggested edits. Also, when you say your time series is irregular, do you mean you have measured $(X_1, Y_1), (X_2, Y_2), \ldots$ synchronously or you might have $X_s, Y_t$ where the indices $s$ and $t$ may or may not overlap?
Comment: Secondly, and it should be obvious, what is the nature of the relationship you're trying to estimate between two variables? There's more than one - most people consider cross-sectional relationships in this case. But there could be a lagged association, or a number of other things which could be called "trends".
Comment: @Tim Indeed, but perhaps you could speak to the idea of including time as a random slope?
Answer: The question is,

How does a random effect structure handle correlation between observations?

The answer is revealed by analysing a simple example of the model you describe.  It turns out the correlation does not depend on the time interval and therefore is unlikely to be appropriate in your application.

Consider a numeric response $Y$ for subject $j$ (with characteristics $\mathbf x_{j} = (x_{j1},x_{j2}, \ldots, x_{jp})$) at time $t_i.$  Model this as a sum of

fixed effects $\mathbf x_j\beta$ (for a constant but unknown parameter vector $\beta = (\beta_1,\beta_2,\ldots,\beta_p)^\prime)$),

a random effect $U_j$ varying among subjects, and

independent "error" $\varepsilon_{ij}$ associated with each observation of the response.

In mathematical notation this can be expressed as
$$Y_{ij} = \mathbf x_{j}\beta + U_j + \varepsilon_{ij}.$$
Standard assumptions are that all the random variables are uncorrelated and have constant variances and means so that (say)
$$\operatorname{Var}(U_j) = \tau^2$$
and
$$\operatorname{Var}(\varepsilon_{ij}) = \sigma^2.$$
(With no loss of generality, all means can be absorbed as an "intercept" in the fixed effect and thereby taken to be zero.)
Focus on a specific subject and compute the correlation among any two of its observations $(Y_{1j}, Y_{2j}, \ldots, Y_{nj})$ (which, with no loss of generality, we may take to be the first two).  A standard formula uses the variance-covariance matrix, so let's begin there.
$$\operatorname{Var}(Y_{ij}) = \operatorname{Var}(\mathbf x_j \beta + U_j + \varepsilon_{ij}) = \tau^2 + \sigma^2$$
(because $U_j$ is assumed uncorrelated with $\varepsilon_{ij}$) and
$$\operatorname{Cov}(Y_{1j}, Y_{2j}) = \operatorname{Cov}(\mathbf x_j \beta + U_j + \varepsilon_{1j},\ \mathbf x_j \beta + U_j + \varepsilon_{2j}) = \tau^2$$
(because $U_j,$ $\varepsilon_{1j},$ and $\varepsilon_{2j}$ are uncorrelated).
Consequently the correlation between any two pairs of observations of the same subject is
$$\rho_j = \operatorname{Cor}(Y_{1j}, Y_{2j}) = \frac{\operatorname{Cov}(Y_{1j},Y_{2j})}{\sqrt{\operatorname{Var}(Y_{1j})\operatorname{Var}(Y_{2j})}} = \frac{\tau^2}{\tau^2 + \sigma^2}.$$
This does not depend on the time interval $\tau_2 - \tau_1$ and therefore does not depend on any time interval.
Notice, too, that this model implies strictly positive correlations among the observations of any given subject.  Intuitively, this arises from the common (but random) influence $U_j$ pertaining to subject $j.$
Answer:
You could just ignore this problem. You can show through simulation that, with some extreme exceptions, an approximate but not exact answer to the variance covariance structure usually leads to reasonable estimation. You can safeguard this approach even more by using a generalized estimating equation (GEE) model.
If AR1 is the right model, treat the unmeasured time series observations as missing data and impute them. If your X, Y processes are asynchronous, it could be as simple as LOCF. Otherwise, multiple imputation could be used. Alternately, you can edit the generalized least squares fitting process to account for imbalanced design and populate the variance-covariance matrix according to the observed design.
Random effects models contain random intercepts or random slopes. In your example, including time as a random slope nested in subject induces a spherical-type correlation between adjacent observations. As always, fit a variogram to inspect the shape and nature of the temporal correlation.
Answer: Would be the MMRM model an option for you? It is a flavour of mixed models. If you are only interested in the fixed effects and just want to account for the random effects you could define your fixed effects, "shovel" your random effects in the error part of the function and set the covariance structure to 'unstructured'. This could work as long you are not interessted in the random effects and you have enough data.
I hope I could help somewhat.
Comment: Thanks RGG. Unfortunately I have not enough data. I've tried that option. And also I have clumps of zero in my data so I'm planning to use SAS nlmixed which don't have the option of R-side random effects.
Answer: You could use glm in combination with the corCAR1 correlation structure from the nlme package in R. This is for continuous irregular time measurements as you have. Although this is not exactly an answer to your question, because you do not have/need a random effect in gls models.
To answer your question, you could use a random linear (or quadratic,cubic, ...) slope of "week". With a random linear slope, you e.g. model a quadratic pattern in the variances over the weeks. And also a particular pattern for the correlations between any pair of weeks you select. E.g. Singer and Willet show the formula's in their book Applied Longitudinal Data Analysis: Modeling Change and Event Occurrence.


Is this set a subset of the given vector space?

Question: The set of all polynomials of degree greater than three together with the zero polynomial in the vector space $P$ of all polynomials with coefficients in $\Bbb{R}$.
I thought I understood generally how to do this but my book (Linear Algebra: Fraleigh, Beauregard, Wesley 1995) explains how to determine whether the subset is a subspace of the vector space. It seems like it already assumes the set is a subset.

How do I determine if a set is a subset of a vector space? Is it with the 8 axioms of vector addition and scalar multiplication?
How do I read this problem specifically? I'm not really sure how to write these out in set notation.

This isn't homework perse. I am studying for my final tomorrow though.
Comment: Well, it's obviously a subset, since every polynomial of degree $>3$ is a polynomial.  Did you mean to ask if it is a $\textit {subspace}
$?  If so, what about sums like $x^3+(-x^3+1)$?
Comment: it is not a subspace since it is not closed under addition, for example: $\left(x^{3}+x^{2}\right)-x^{3}=x^{2}$
Comment: Yeah sorry I meant subspace
Answer: To check that a subset is a subspace you need to check three axioms:
1.Closed under addition
2.Closed under scalar multiplication
3.Non empty
In your case is very simple since $deg((x^3+1)+(-x^3))=deg(1) <3$
Comment: Yeah I get the subspace axioms. I was just having a hard time reading the problem itself. Also, how do you come up with something like that without spending hours and hours just guessing different polynomials.
Answer: $P = \mathbb{R}[x]=\{a_0+a_1x+\ldots+a_nx^n \mid n\in \mathbb{N}, a_i\in \mathbb{R}\}.$
$S = \{\mathbf{0}\} \cup\{p\in P \mid \deg(p) > 3 \}.$
$S$ is a subset of $P$ $\iff \forall s\in S. \ s \in P.$
Take $s \in S.$ Then $s=\mathbf{0}$ or $s\in P$ with $\deg(p) > 3.$
So you just have to show that $\mathbf{0} \in P.$
Comment: is $\Bbb{R}|x|$ the set of all polynomials with a real coefficient? If so, can you explain how? I thought it would have been something like: $\{a_01, a_1x, a_2x^2, ... \}$ for $a_i \in \Bbb{R}$
Comment: I expanded the definition of $\mathbb{R}[x]$. Notice that this is an answer to your first question.
Comment: Thanks. So I was kind of right in my assumption. I'm guessing that using x is just simpler since x could be set equal to any mono / polynomial expression?
Comment: One remark: $\mathbb{R}[x]$ is not the set of polynomials with $a$ real coefficient, but the set of polynomials with real coefficients, i.e of the form I wrote in the answer. $x$ is just a variable and you can set it to any real value, but not to mono/polynomial expressions.
Comment: I gotcha. I didn't think it was something like $a(1+x+x^2+...+x^n)$ I only said monomial because out side of this problem it could be set to that. But since this problem specified polynomials, then monomials would not be included. Sorry for confusing my understanding.


Execute command from git configuration

Question: On macOS, the tool ghi (GitHub Issues on the command line) adds the following to ~/.gitconfig:
[ghi]
    token = !security find-internet-password -a username -s github.com -l 'ghi token' -w

It is my understanding that by starting with a !, it means that is a shell command. And indeed it is, as executing it returns the correct authentication token (stored in the macOS Keychain). But running git config --get ghi.token returns the command itself (with !), instead of its result, which was what I was expecting because it seems that ghi would use that to retrieve the key.
What is the git command, if any, to return the result of the command, instead of the command itself?
Answer: There is no such command; ghi reads the configuration value, strips the '!' and executes the result:
    value = ENV[var] || `git config #{flags} #{key}`
    value = `#{value[1..-1]}` if value.start_with? '!'

see ghi repository
git uses ! at some places the mark configuration values as programs instead of plain value; but there is not automatic evaluation behind.

Execute command from git configuration


Why is the union of a flag of Banach spaces not complete?

Question: Assume we have a directed set $L$, a Banach space $Z$ and a family of closed subspaces $Z_\gamma \subset Z$ with $\forall \gamma' \geq \gamma: Z_\gamma \subseteq Z_{\gamma'}$.
Why is in this case the space $\bigcup_{\gamma \in L} Z_\gamma$ in general no Banach space (but its completion is one)?
Answer: Consider $\mathcal{C}[0,1]$ and let $P_n$ be the set of all polynomials of degree $n$ or less.


What is the limit of the "restsums" of the harmonic series?

Question: I'm trying to determine the following limit:
$\lim_{n\to \infty} \sum_{k=n}^\infty \frac{1}{k} $
I know that
$ \sum_{k=1}^\infty a_k < \infty \implies \lim_{n\to \infty} \sum_{k=n}^\infty a_n = 0$,
which follows from Cauchy's convergence test. Considering the problem I'm working on right now, I would hope the first limit to be zero, too - even though the harmonic series diverges.
Many thanks in advance.
Comment: $\sum_{k=n}^\infty \frac{1}{k} = \infty$ for each $n$, so the limit is ...?
Comment: This is why Dominated Convergence requires the dominating function to be summable.
Comment: Another example is $$\lim_{n\to\infty}\sum_{k=n}^{2n}\frac1k$$ the terms tend to $0$, but the sum does not.
Comment: @MartinR I have thought about that way, too. Every element of the sequence is $\infty$, so the limit should be $\infty$, too, right? But there are constant sequences whose limits are different from that constant, such as $ a_n = \lceil 1/n \rceil  $.
Comment: @christophp: what limit do you get there? The limit of a constant sequence is always that constant. For example, the limit of that sequence is $1$.
Comment: @robjohn I figured zero, since 1/n tends to zero?
Comment: @christophp: you'd be figuring wrong, in that case.
Comment: @robjohn That was my counterexample all along. If that's wrong it would clear everything up. Thanks!
Comment: Consider the function $f(0)=0$ and $f(x)=1$ for $x\ne0$. What is $\lim\limits_{x\to0}f(x)$?
Comment: Right, I should have thought about continuity. Silly in retrospect, I wanted that sequence to converge too much :) it would have been very useful to me. Thank you very much!
Comment: For any $n>1$, $0<\frac1n<1$ so $\lceil \frac1n \rceil=1$. So although $\frac1n \rightarrow 0$, $\lceil \frac1n \rceil$ stays stuck at $1$ and can never be brought arbitrarily close to $0$.
Answer: The limit doesn't exist since $$\sum_{k=n}^\infty \frac{1}{k}$$is undefined for and $n\in \Bbb N$. Check the on Harmonic series (mathematics) Wikipedia.


Linter - Parsing error: Unexpected token {

Question: O professor passou alguns exercicios, um deles era usar o Git e executar um linter para verificar vários arquivos de código. Aqui ele me deu nesse código mas sinceramente nao consegui entender e nem identificar.
    // Você nao pode modificar as linhas de 2 à 5:
    const lib = {
    abc: 123,
    def: 234,
    };

    object =abc {
      def: lib.def,
      abc: lib.abc,
      xyz: 567,
    };

    console.log('O valor de abc est' + object.abc);

Comment: `object = abc` era para ser um objeto com propriedades `def`, `abc` e `xyz`?
Comment: Acredito que sim. Agora nao entendi o motivo do erro de Parsing selecionando token {
Comment: mas repare que se `object = abc` era para ser um object qual o nome da variável `object` ou `abc`? mude para `const object` e chame o `object.abc` já deverá funcionar
Comment: Obrigado pela dica
Answer: O erro é de sintaxe, mais especificamente nessa parte:
object =abc {
  def: lib.def,
  abc: lib.abc,
  xyz: 567,
};

o correto seria:
object = {
  def: lib.def,
  abc: lib.abc,
  xyz: 567,
};

Pois você está atribuindo um objeto à variável object, e o "abc" não tem sentindo onde estava.
Comment: pode ter sentido se colocar o `abc` entre aspas, assim chama o `object["abc"]`
Comment: @PedroPinto, é uma das interpretações possíveis
Comment: const lib = {
           abc: 123,
          def: 234,
         };

         const object  {
           def: lib.def,
          abc: lib.abc,
          xyz: 567,
        };

        console.log('O valor de abc est' + object);

e agora o erro no linter muda para:
 Unexpected string concatenation  prefer-template (para a ultima linha)
Comment: @MarceloMedeirosdosSantos Essa vírgula no final depois do 567 também não ajuda.
Answer: O linter recomenda utilizar uma novidade : ES2015 (ES6) nomeada "Littéraux de gabarits" (em frances) ou "template literals".
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals
É entao possivel formatar uma linha de texto escrevendo diretamente o nome da variavel 'inline'.
Para resolver o problema, deve-se trocar
    console.log('O valor de abc est' + object);`

por
    console.log(`O valor de abc est ${object}`);

Comment: Oi Marcelo! Esta tua resposta não é a resposta ao problema. O problema era como outros indicaram a sintaxe errada na declaração do objeto. _Template literals_ é útil, mas se não corrigires a sintaxe `object =abc {` vai dar o mesmo erro na mesma. Acho que a resposta do Samir merece ser marcada como aceite/correta.
Comment: Oi @Sergio .. é que depois de usar o que nosso amigo Samir escreveu surgiu um outro erro para  Unexpected string concatenation prefer-template (para a ultima linha) e a resposta foi esta que eu passei. Desculpe por postar no local errado ;)
Comment: O código sem erros ficou assim:

        // Vous ne pouvez pas modifier les lignes 2 à 5:
        const lib = {
        abc: 123,
        def: 234,
        };

        const object = {
        def: lib.def,
        abc: lib.abc,
        xyz: 567,
        };

        const str = `La valeur de abc est ${object}`;

       console.log(str);


Socket and buffers

Question: I know standard c library functions fwrite and fread are a sort buffering wrappers of write and read system calls, buffers are used for performance reasons I totally understand.
what I don't understand is the role of buffers in socket programming functions write and read.
can you help me understand what they are used for, highlighting differences and similarities with files buffers?
I'm a newbie in socket programming...
Answer: When the kernel receives packets it has to put those data somewhere. It stores it in the buffer. When your app does the next read it can fetch the data from those buffers. If you have a UDP connection and your app doesn't read those buffers it gets full and the kernel starts to drop the received packets. If you have a TCP connection it will acknowledge the packets as long as there is free space in the buffers, but after that it will signal that it cannot read more.
Write buffers are necessary because the network interface is a scarce resource, the kernel typically cannot send immediately a packet. If you do a big write() it could be chopped up to hundreds of packets. So the kernel will store that data in the buffers. The buffer also does a good job if you do a lot of small writes, see Nagle's algorithm.
Answer: Imagine if you sent your information one byte at a time. You'd be generating a 100 byte packet to send 1 byte, and if it's a TCP connection, depending in implementation, waiting until you got a syn/ack before sending more? Sounds pretty inefficient to me.
Instead, you use a buffer to store up a large amount of data and send that across in a single packet, just like storing up data before writing to disk.
Comment: this strategy is called http://en.wikipedia.org/wiki/Nagle%27s_algorithm and can be disabled.
Comment: @yi_H I knew it had a name :-) Thanks! And yes, it can be disabled if you feel you know better how to send the packets than the implementers of your networking library.
Comment: No, it can be disabled to send the packets immediately. Latency could be more important than wasted bandwith.
Comment: @yi_H You imply that by sending immediately you're reducing latency, which isn't always the case. But this is exactly what I meant by implying that you know better how to send packets than the implementers of the library. The idea is they have it optimized, and you're going to say "No, turn that off - I need it to work differently". That can be dangerous because chances are you (you being the average developer) are not better equipped to solve those problems than the people who wrote the standard networking library.
Comment: It looks like your understanding of the their optimization is incomplete. It's not like that you optimize something and it gets superior to everything else. You need an objective/cost function. http://en.wikipedia.org/wiki/Optimization_%28mathematics%29#Overview In this case they optimized it for *banwith*, which is good for most of the applications (so it's a good default). For the rest it's just a hindrance.   http://en.wikipedia.org/wiki/Nagle%27s_algorithm#Interactions_with_real-time_systems
Comment: @yi_H No, I'm understanding it perfectly well. To say it's a hindrance means you fully understand the objectives and the costs. In the hands of most developers, those flags are not tools, but weapons.

Socket and buffers


Transformation of a Taylor series: "doubling" the derivative order

Question: Suppose a function $f(z)$ has a convergent Taylor expansion:
$$f(z)=\sum_{n=0}^{\infty} c_n \frac{z^n}{n!}$$
Are there general tools to compute $$g(z) = \sum_{n=0}^{\infty} c_{2n} \frac{z^n}{n!}=\sum_{n=0}^{\infty} \, f^{(2n)}(0)\frac{z^n}{n!} \text{ ?} $$
I came across this general problem in a more specific context explained in this question.
One possible way is to do an integral transform
$$\dfrac{1}{s} \int_0^{\infty} e^{-z/s} f(z) dz$$
 to remove the factorials, then replace $s \to \sqrt{s}$
 and do the inverse transform. However, this easily leads to very complicated integrals, and does not seem to work for my particular problem.
Answer: See my answer to this post for a solution which is based on an integral formula for the gamma function.


Does frequentist statistics support the use of priors?

Question: My understanding of the main difference between Frequentist vs Bayesian stats is that the former treats parameters as variables with fixed but unknown values whereas the latter treats them as random variables.
From that perspective, I get the impression that priors (and posteriors) would only make sense in Bayesian statistics. Is this understanding correct?
Comment: Yes, but there is a lot of overlap in practise.eg frequentist ridge regression ~ Bayesian linear regression with normal priors
Answer: You are right in the sense that in Bayesian statistics the space of parameters $\Theta$ is endowed with the structure of a probability space $(\Theta, \mathcal{A},\pi)$ where $\mathcal{A}$ is a $\sigma$-algebra and $\pi$ a probability (prior) so it make sense to ask questions of the form
$$
B\in \mathcal{A},\quad \int_B f(\theta)\pi(d\theta)
$$
Where this would not make sense in a frequentist setting.


Measure of fit to simulated data for item response theory model

Question: Starting with randomly generated person ability parameters $\textbf{z}$ and item parameters $(\boldsymbol \alpha,\boldsymbol{\beta})$, I simulated data representing correct/incorrect responses of $N$ people on $M$ items.
Using the $\text{mirt}$ R package, I can derive estimates $\boldsymbol{z^*}, \boldsymbol{\alpha^*},\boldsymbol{\beta^*}$ of the aforementioned parameters, which effectively constitute a person/item model.
Though there are plenty of fit statistics that characterize the extent to which the model fits the data, I'm more interested in the fidelity of estimated parameters to the parameters used to generate the simulated data.
That is, how close (in some sense) is $\boldsymbol \alpha$ to $\boldsymbol{\alpha^*}$, for instance.
I'm wondering if this can this be a good measure of model fitness, at least in the case of simulated data.
Answer: It is not uncommon in IRT to use simulation studies to measure model fitness. You would call $z$, $(\alpha,\beta)$ your true values, and surely you would like to find out how well your model performs in uncovering these. Note that you would do that with multiple simulated data, obtaining many instances of estimates $z^*_i, \alpha^*_i, \beta^*_i$. You can compare those to the true values for example using the RMSE (root mean square error).
For a nice practical example, see Kang, Cohen and Sung (2009). For discussions about simulation studies in IRT, have a look at Luecht and Ackerman (2018) and Yen (1981).

Kang, T., Cohen, A. S., & Sung, H.-J. (2009). Model Selection Indices
  for Polytomous Items Applied Psychological Measurement, 33, 499-518.
Luecht, R., & Ackerman, T. A. (2018). A technical note on IRT
  simulation studies: Dealing with truth, estimates, observed data, and
  residuals. Educational Measurement: Issues and Practice.
Yen, W. M. (1981). Using simulation results to choose a latent trait
  model. Applied Psychological Measurement, 5, 245–262.


Juntar o resultado de dois comandos Select's - PostgreSQL

Question: Minha necessidade é unir o resultado de dois comandos select's para que me seja retornado tudo de uma vez, por exemplo nesse comando:
SELECT codigosuprimento, suprimento, count (codigosuprimento) quantidade, estoqueminimo,
count (codigosuprimento) - estoqueminimo as saldo
    FROM public.estoque, public.suprimento where usado = '0' and codigosuprimento = 155 and
    public.estoque.codigosuprimento = public.suprimento.codigo group by codigosuprimento, suprimento, estoqueminimo order by suprimento;

Eu trago a situação atual do suprimento de codigo 155 no estoque, Meu retorno é assim:

E nesse comando :
SELECT public.estoque.codigosuprimento,COUNT (public.estoque.codigosuprimento) as qtdSuprimento
FROM public.entrega, public.entregaitem, public.estoque
WHERE public.entrega.codigo = public.entregaitem.codigoentrega and codigosuprimento = 155 and
public.entregaitem.codigoestoque = public.estoque.codigo and public.entrega.data >= CURRENT_DATE - 30
GROUP BY public.estoque.codigosuprimento
ORDER BY codigosuprimento

Eu trago quantos suprimentos foram requisitados nos últimos trinta dias, e meu retorno é assim:

Minha necessidade seria unir os resultados para que tivesse algo semelhante a isso:
codigosuprimento | suprimento | quantidade | estoqueminimo | saldo | qtdSolicitada
        155      |  50F0Z00   |     54     |        10     |   44  |       19

Fiz um teste e coloquei uma query assim:
SELECT codigosuprimento, suprimento, count (codigosuprimento) quantidade, estoqueminimo,
count (codigosuprimento) - estoqueminimo as saldo,
(SELECT COUNT (public.estoque.codigosuprimento) as qtdSuprimento
FROM public.entrega, public.entregaitem, public.estoque
WHERE public.entrega.codigo = public.entregaitem.codigoentrega and codigosuprimento = 155 and
public.entregaitem.codigoestoque = public.estoque.codigo and public.entrega.data >= CURRENT_DATE - 30) as trinta
FROM public.estoque, public.suprimento where usado = '0' and codigosuprimento = 155 and
public.estoque.codigosuprimento = public.suprimento.codigo group by codigosuprimento, suprimento, estoqueminimo order by suprimento;

E desse modo ela me trouxe o resultado esperado, porém quando fui testar para trazer sem a condição de trazer apenas para o suprimento de código 155 ela já me trouxe resultados sem sentido. Tentei desse modo a query e me trouxe os resultados errados:
SELECT codigosuprimento, suprimento, count (codigosuprimento) quantidade, estoqueminimo,
count (codigosuprimento) - estoqueminimo as saldo,
(SELECT COUNT (public.estoque.codigosuprimento) as qtdSuprimento
FROM public.entrega, public.entregaitem, public.estoque
WHERE public.entrega.codigo = public.entregaitem.codigoentrega and
public.entregaitem.codigoestoque = public.estoque.codigo and public.entrega.data >= CURRENT_DATE - 30) as trinta
FROM public.estoque, public.suprimento where usado = '0' and
public.estoque.codigosuprimento = public.suprimento.codigo group by codigosuprimento, suprimento, estoqueminimo order by suprimento;

Comment: Já tentou dar um `(select1...) UNION (select2...)`?
Comment: Mesmo colocando as colunas "adicionais" como `null`?
Comment: @Zulian já, porém para usar o `UNION` é necessário que ambos os retornos possuam o mesmo numero de colunas
Comment: O problema é que ele trouxe o conteúdo do segundo select na segunda linha sendo que eu preciso que seja na mesma
Comment: Um subselect fica mas custoso para o db mas acho que te atenderia
Comment: Assim como eu coloquei na minha pergunta @CaiqueRomero?
Comment: @CaiqueRomero tu teria algum exemplo de como fazer com subselects?
Comment: Ao inves de você preencher 155  você coluna a coluna codigo do primeiro select
Comment: @CaiqueRomero, como assim?
Comment: Demonstrei na resposta, veja se consegui te ajudar
Answer: SELECT codigosuprimento
  , suprimento
  , count (codigosuprimento) quantidade
  , estoqueminimo
  , count (codigosuprimento) - estoqueminimo AS saldo
  , (
     SELECT COUNT (estoque2.codigosuprimento) as qtdSuprimento
     FROM public.entrega
        , public.entregaitem
        , public.estoque AS estoque2 --Renomeio a tabela para relacionar ambas as querys
     WHERE public.entrega.codigo = public.entregaitem.codigoentrega
        AND public.estoque.codigosuprimento = estoque2.codigosuprimento-- Relaciono as 2 querys
        AND public.entregaitem.codigoestoque = estoque2.codigo
        AND public.entrega.data >= CURRENT_DATE - 30
    ) AS trinta
FROM public.estoque
   , public.suprimento
WHERE usado = '0'
   AND codigosuprimento = 155
   AND public.estoque.codigosuprimento = public.suprimento.codigo
GROUP BY codigosuprimento
  , suprimento
  , estoqueminimo
ORDER BY suprimento;

Comment: Perfeito funcionou como precisava, muito obrigado :)
Comment: Fico feliz que deu certo :)


C++ - Using a map to store callback functions

Question: I'm attempting to use a map to store functions to be called at certain times.
typedef std::function<void(rapidjson::Document&)> Callback;

std::map<std::string, Callback> _callbackDict = {
    { "foo", HandleFoo },
    { "bar", HandleBar },
};

When I attempt to store them it leads to an error:
error: could not convert '{{"foo", ((FooBar*)this)->FooBar::HandleFoo}, {"bar", ((FooBar*)this)->FooBar::HandleBar}}' from '<brace-enclosed initializer list>' to 'std::map<std::__cxx11::basic_string<char>, std::function<void(int, int)> >'

MCVE
#pragma once
#include <map>
#include <iostream>
#include <functional>

typedef std::function<void(int, int)> Callback;
class FooBar
{
private:
    std::map<std::string, Callback> _callbackDict = {
        { "foo", HandleFoo },
        { "bar", HandleBar },
    };
public:
    FooBar();
    void HandleFoo(int a, int b);
    void HandleBar(int a, int b);
    ~FooBar();

};

Comment: @J.Doe It's the issue I mentioned in my 1st comment.
Comment: ^^^ These need to be `static` member or global functions just to note.
Comment: @πάνταῥεῖ I've included code which reproduces the error stated in the question.
Answer: The following code compiles:
namespace rapidjson { struct Document; }

void HandleFoo(rapidjson::Document&) {}
void HandleBar(rapidjson::Document&) {}

typedef std::function<void(rapidjson::Document&)> Callback;
std::map<std::string, Callback> _callbackDict = {
    { "foo", HandleFoo },
    { "bar", HandleBar },
};

Note that FooBar::Run() isn't relevant to your problem and doesn't need to be included in your question.
Answer: It's still not clear exactly what you're trying to do.  The smallest change to get your code to compile was already given in a comment; make your functions static:
namespace rapidjson {   struct Document; }

typedef std::function<void(int, int)> Callback;
class FooBar
{
    std::map<std::string, Callback> _callbackDict = {
        { "foo", HandleFoo },
        { "bar", HandleBar },
    };
public:
    static void HandleFoo(int a, int b);
    static void HandleBar(int a, int b);
};

But you really need to get a good C++ book and read it; this is supposed to be a Q-and-A site, not help-me-with-my-code.


Include Div tag in jsp

Question:

    <%out.print("
"+rs.getString(8)+"
"); %>

I want to print the div content in jsp tag.What i should do to display div in jsp's output.Please help me out.I would appreciate your good solutions.
Comment: despite of the single line `<%out.print(...);%>` i don't know why the other code is in the question. Please format it to make the question more readable and helpful for others
Answer: You don't have to use:
<%out.print("
"+rs.getString(8)+"
"); %>

You can simple use:

<%=rs.getString(8)%>

In a JSP file you can use any html tag directly.
Comment: No need of <%out.print%> ah?
Comment: If i use only <%=rs.getString(8)%> it won't works.
Comment: try first with `Some Text for Testing`. Does it work? if so then the issue is in  `<%=rs.getString(8)%>`. Is the rs defined?
Comment: if i use individually both codes are working fine.But when i execute both at a time i will not get any output!!

Include Div tag in jsp


What possibilities can cause "Service Unavailable 503" error?

Question: we have a asp.net MVC application deployed to a server, and but when there is too many request to the server, the client will just get a "503 service unavailable" error.
But if I deployed the application to another server ( lower hardware configuration ), everything worked fine, even more requests it can handle well.
My question is what possible configuration can cause the previous server to just throw out a 503 error ? (which means the requests didn't reach our application).
Comment: Closed? Is it not useful to know what some or all of the many answers are? Stack Overflow is strange. Must not provide all types on information, JUST ONE SPECIFIC TYPE! ;)
Comment: In fact there are [many possible reasons](http://www.microsoft.com/technet/prodtechnol/windowsserver2003/library/iis/55f71614-ef1b-4015-b9c8-a42c1e700c25.mspx?mfr=true).
Comment: Such strange activities of Stack overflow is behind the scene of us. Anyway, it is my favorite site for the genius programmer in this site.
Answer: Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...

Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]
Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.

In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.
What is a Crash (technically)... in ASP.NET and what to do if it happens?
Comment: Yes. Please also check if the Identity being used by the application pool still works.
Answer: If the server doesn't have enough memory also will cause this problem. This is my personal experience with Godaddy VPS.
Answer: Primarily what that means is that there are too many concurrent requests and further that they exceed the default 1000 queued requests. That is there are 1000 or more queued requests to your website.
This could happen (assuming there are no faults in your app) if there are long running tasks and as a result the Request queue is backed up.
Depending on how the application pool has been set up you may see this kind of thing. Typically, the app pool's Process Model has an item called Maximum Worker Processes. By default this is 1. If you set it to more than 1 (typically up to a max of the number of cores on the hardware) you may not see this happen.
Just to note that unless the site is extremely busy you should not see this. If you do, it's really pointing to long running tasks
Comment: What you are saying will lead to Server Too Busy error. The question is Service Unavailable. These two issues are totally different. Check my answer.
Comment: Sorry Shiv. This is not correct. http://support.microsoft.com/kb/943891
Comment: No problem at all, Shiv. Just wanted to reaffirm that although high number may end up in issues... the root cause would always be a crash [or the service being unavailable due to the App Pool getting disabled - 503]. You can reproduce this error very easily.
Comment: Shiv Kumar is correct.
Comment: @MemoryLeak, you'll need to look at your application pool and the settings and compare them across the two servers. Also look for any conflicts with regards to the .NET version the app pool has been configured for and make sure that is the version your app requires. Alos look for other applications that share the same app pool.
Comment: Too many requests could probably also cause your app to crash and as a result your get the 503 error. You may also want to check your Event logs to see if you can see in clue in there. Most likely some unhanded exception that causes this?
Comment: In my case just restarted it worked fine.

Reference Link : https://blog.hubspot.com/marketing/http-503-server-unavailable
Answer: We recently encountered this error, root cause turned out to be an expired SSL cert on the IIS server.  The Load Balancer (infront of our web tier) found the SSL expired, and instead of handling the HTTP traffic over to one of the IIS servers, started showing this error.  So basically IIS unable to server requests, for a totally different reason :)


Conditional display of views based on comparing node taxonomy and user taxonomy

Question: I'm using drupal 7 and working on a site that displays nodes based on a user's taxonomy option. A quick example, i want users to make a blog entry and select a taxonomy option "Target audience". The target audience contains selected "Interests" of logged in users. Both "target audience" attached to node and "Interest" attached to user profile are from the same taxonomy vocabulary, so that when a user selects a target audience, he matches a user interest.
Is it possible to build a single view of all blog enteries and then display parts of the view based on certain conditions like "if blog entry is tagged with taxonomy value which is equal to the interest of logged in user,  then display blog enteries which match the logged in user's interest.
Another use case is this: taxonomy value location = New York. Blogger makes a post and selects target audience = New York. User logs in with selected location = New York (mandatory during registration), view checks if target audience = user location, then displays only posts tagged with "New York". Another user logs in with location = Washington, but there are no posts with tag = Washington, views empty field is then displayed or default display is used (when all conditions fail).
I'm also using panels. currently with panels, to achieve this, i have to build a separate view for each user with selected taxonomy option. This makes it cumbersome because, for instance, to display for all users logged in from 52 cities, you have to create 52 views. My intention is to build a single view that decides what to display based on the checked conditions.
Help is greatly appreciated. Thanks
Answer: First, your view needs to be set up with a display of type "Content Pane". For this to be possible you need to enable the Views Content Panes module which is part of Ctools.
Next, you need to add a contextual filter (also called an argument) for your taxonomy field. The option to do this is under Advanced on the Views UI for the view. The process is similar to adding other parameters to a view, so I'll not cover it in detail.
Once the contextual filter has been added you need to ensure it can be supplied by the panel you are going to add it to. To do that, click on the Edit link next to "Argument input" under Pane settings. Set the source of the argument to be "from context" and the required context to be "term ID of first term".
On the panel editor, you need to add a context for the logged in user. On the contexts tab for the panel, select "user" for the type of context to be added, then press the add context button. Choose suitable identifiers for the user context and select the "logged in user" option, then hit Finish.
Now from the same tab, under Relationships, you should be able to find an option to add a taxonomy context via the user context. It'll be labelled something like "Taxonomy term from User (on User: fieldname [field_fieldname])". Add it and assign it a meaningful identifier.
Now finally you should be able to add your view display pane to the panel. On the content tab, you'll find it under "View Panes" on the add content dialogue. After you click on it you should see the settings for it, which should consist of a selector linking the contextual filter from the view to the context from the panel. If there is only one taxonomy term context available, the correct value will probably be already correctly set. Save everything and test.
Good luck!


SAPI STT in javascript

Question: I'm new to javascript and was wondering if there are any tutorials on how to implement speech to text and speech recognition through SAPI. The only examples I've found so far are TTS and how to spit back text. And the questions already posted aren't really giving me any info I can take from.
I know that you have to create an ActiveXObject, but I can't really understand the Microsoft SAPI website since none of the examples are in javascript and I don't know any of the syntax. I plan on making an HTML app that can use speech recognition to preform tasks in a program.
Appreciate the help.
Answer: SAPI objects aren't marked Safe For Scripting (because they're not) and can't easily be used from JavaScript.   I've done it, but you have to turn off tons of internet security options in order to do so.  I wouldn't pursue that path, particularly for a public-facing website.
Comment: I'm just kind of locked up right now because this speech recognition has to work in IE. Do you know of any other ways to do STT that will work with JavaScript and IE?
Comment: @Rigial9 Does it have to be a website?  If you can make it a standalone app (say, a WinPhone universal app), there are a lot more options.  SR on websites is still really experimental.
Comment: The prototype we're doing right now is basically just one giant script that uses node.js and socket.io for back and forths. I'm sure in the future it will probably become a standalone app, but for now it's just a website. If it wasn't developed in IE I would have some options but I guess I'm stuck now. Thanks for all the help.

SAPI STT in javascript


how can i see recurring payment details on my website?

Question: Currently i am using ubercart for recurring payment everything is working fine i can see status of mine recurring payment on paypal account
But how can i see recurring payment details on my website i have searched so many times on google but not got any relative article.
When i go to /admin/store/orders/39/recurring that page always shows blank details  .
Answer: I'm able to see my memberships at <code>/admin/store/orders/recurring</code> (this is Drupal 6). From there I can edit the recurring fees and search based on a number of different properties.
Comment: I don't think that PayPal Website Payments Pro supports recurring payments. It could be that this is what's causing the discrepancy.
Comment: will you please let me know the entire process which module you have used ,i have used commerce subscription with recurring module in drupal 7 after that i created product and added feature recurring for 1 day after checkout completion i go to  /admin/store/orders/39/recurring but its not showing under this tab
Comment: i think i am missing some configuration of module, i am using paypal wps for payment,role is also granting everything is working fine except recurring fee details, i am not able to conclude where i am missing while configuring module
Comment: @Vikram8888 `i have used commerce subscription with recurring module` is that a Drupal Commerce module? ... I thought you said you were using Ubercart...
Comment: yes i am using ubercart ,its so urgent for me to know the solution becoz i have to deliever my project within 2 days
Comment: @Vikram8888 there is a Drupal 6 tutorial [here](https://www.drupal.org/documentation/modules/uc_recurring), I hope this helps.
Comment: @Vikram8888 Do you see anything at the `/admin/store/orders/recurring` page?
Comment: i concluded only credit card payment works with recurring payment but when i added Credit card (includes PayPal Website Payments Pro) payment gateway on review order page i am getting error like We were unable to process your credit card payment." Please verify your details and try again. If the problem persists, contact us to complete your order"
Comment: but when i implement Credit card (includes Test gateway) recurring payment is working fine i can see recurring payment details on my website,but i am not able to access with  Credit card (includes PayPal Website Payments Pro) getting error on review order page


Internal server error when programmatically updating about 100 nodes

Question: I'm writing a function that unpublishes a bunch of event-type nodes within a date range. My query pulls about 100 nodes, but I'm apparently maxing out the available memory. Here is the code in question:
$sql = "SELECT node.nid AS nid FROM node node  LEFT JOIN content_type_event node_data_field_event_date ON node.vid = node_data_field_event_date.vid WHERE (DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') >= '2014-09-10' AND DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') <= '2015-09-10') AND (node.type in ('event'))";

$nids = mysql_query($sql);
$report = "";

while ($nid = mysql_fetch_array($nids)) {
    $node_id = $nid['nid'];

    $node = node_load($node_id);

    $node->status = 0;

    node_save($node);
    $report = $node->title . " unpublished.";
}
drupal_set_message($report);

Any suggestions greatly appreciated.
Answer: Give your server more memory ;)

Better to use EntityFieldQuery (but this will not speed up your script ..)
You could replace the while loop with foreach (array_keys($result['node']) as $node_id)
In the worst case you'll need to limit the $result or $nids array to 10 or something .. and run the script several times, maybe in cron ?

Or run an update query (also possible without php)
$sql = "UPDATE node node LEFT JOIN content_type_event node_data_field_event_date ON node.vid = node_data_field_event_date.vid SET node.status = 0 FROM WHERE (DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') >= '2014-09-10' AND DATE_FORMAT(ADDTIME(STR_TO_DATE(node_data_field_event_date.field_event_date_value, '%Y-%m-%dT%T'), SEC_TO_TIME(-25200)), '%Y-%m-%d') <= '2015-09-10') AND (node.type in ('event'))";

mysql_query($sql);

Comment: Thanks for this! I should have mentioned that I'm in an old D6 installation (I know, I know), so EntityFieldQuery isn't available. Sigh . . .
Comment: ah okey .. just lift the php limit thoe ... or run an update statement, see my edit


Emacs: Insert word at point into replace string query

Question: Is there an analogue to inserting the word after point into the isearch query by hitting C-w after C-s but for the replace string (and replace regexp) queries?
I also enjoy Sacha Chua's modification of C-x inserting whole word around point into isearch:
http://sachachua.com/blog/2008/07/emacs-keyboard-shortcuts-for-navigating-code/
This too would be really useful in some cases if it could be used in replace string.
I'd be very thankful for any tips!
Thank you!
Comment: [An alternate answer](https://unix.stackexchange.com/a/636687/99066)
Answer: This will do it, although it isn't as fancy as C-w in isearch because you can't keep hitting that key to extend the selection:
(defun my-minibuffer-insert-word-at-point ()
  "Get word at point in original buffer and insert it to minibuffer."
  (interactive)
  (let (word beg)
    (with-current-buffer (window-buffer (minibuffer-selected-window))
      (save-excursion
        (skip-syntax-backward "w_")
        (setq beg (point))
        (skip-syntax-forward "w_")
        (setq word (buffer-substring-no-properties beg (point)))))
    (when word
      (insert word))))

(defun my-minibuffer-setup-hook ()
  (local-set-key (kbd "C-w") 'my-minibuffer-insert-word-at-point))

(add-hook 'minibuffer-setup-hook 'my-minibuffer-setup-hook)

EDIT:
Note that this is in the standard minibuffer, so you can use it use it anywhere you have a minibuffer prompt, for example in grep, occur, etc.
Comment: Thanks for the quick answer! This is definitely close enough and has the advantage of being more general! Thanks!
Answer: Two answers:

Replace+ automatically picks up text at point as the default value when you invoke replace commands.
More generally, Icicles does something similar to what scottfrazer's code (above) does, but it is more general.  At any time, in any minibuffer, you can hit M-. (by default) to pick up text ("things") at point and insert it in the minibuffer.  You can repeat this, to either (a) pick up successive things (e.g. words) of the same kind, accumulating them like C-w does for Isearch, or (b) pick up alternative, different things at point.  More explanation here.
Answer: I think this exists in Emacs already - you just start replace with M-S-% and then press M-n (while the minibuffer is empty), this fills in the word under cursor, there are more useful things you can do with this, check http://endlessparentheses.com/predicting-the-future-with-the-m-n-key.html?source=rss#disqus_thread.


Find all k, such that $A_{k}= \left \{\sigma ^{k}|\sigma \in S_{n} \right \}$ is a subgroup of $S_{n}$

Question: Find all odd k, such that $A_{k}= \left \{\sigma  ^{k}|\sigma \in S_{n}  \right \}$ is a subgroup of $S_{n}$
Comment: How did you show that $A_5$ is a subgroup? Also, this is somewhat unfortunate notation, since $A_n$ usually refers to the alternating group.
Answer: If $n\geq 5$ and $k$ is odd, then the set $\{x^k~|~x\in S_n\}$ is a subgroup of $S_n$ if an only if $g.c.d.(n!,k)=1$.
Here we use the classical finite group theoretical fact that the map $x\to x^k$ is a bijection of a finite group $G$ if and only if $g.c.d.(|G|,k)=1$.
If $g.c.d.(n!,k)=1$, then the map $x\to x^k$ is a bijection of $S_n$ and therefore $\{x^k~|~x\in S_n\}=S_n$ is a subgroup.
Conversely, suppose that $\{x^k~|~x\in S_n\}$ is a subgroup. Since $y^{-1}x^ky=(y^{-1}xy)^k$, then this subgroup is normal. For $n\geq 5$ the group $S_n$ has only $3$ normal subgroups, namely $S_n, A_n,1$.
Since $k$ is odd, for an odd permutation $x$ the permutation $x^k$ is also odd. Therefore $\{x^k~|~x\in S_n\}\neq A_n, 1$. Therefore $\{x^k~|~x\in S_n\}=S_n$ and the map $x\to x^k$ is a bijection of $S_n$, which implies $g.c.d.(n!,k)=1$.
If $n\geq 6$ and $k$ is even, then the set $\{x^k~|~x\in S_n\}$ is a subgroup of $S_n$ if and only if $k$ is divisible by $l.c.m.(2,3,\dots,n)$.
Indeed, if $k$ is divisible by by $l.c.m.(2,3,\dots,n)$, the for all $x\in S_n$, we have $x^k=1$, therefore $\{x^k~|~x\in S_n\}=1$ is a subgroup.
If $k$ is not divisible by $l.c.m.(2,3,\dots,n)$, then the set $\{x^k~|~x\in S_n\}$ is not empty.
Suppose that $\{x^k~|~x\in S_n\}$ is a subgroup of $S_n$. This subgroup is non-empty normal subgroup which contains only even permutations. Therefore $\{x^k~|~x\in S_n\}=A_n$.
Denote by $H=\{x^2|x\in S_n\}$. This set is obviously a subset of $A_n$.
If $x$ is even cycle, then $x^2$ is a product of two cycles of the same length.
If $x$ is odd cycle, then $x^2$ is again an odd cycle.
Therefore the element $x\in S_n$ is a square if and only if for every even $r$ the number of cycles of the length $r$ in $x$ is even. Since the element $y=(12)(3456)$ does not satisfy this condition, it is not a square. Therefore $y$ belongs to $A_n\setminus H$, and $H\neq A_n$.
Finally  $\{x^k~|~x\in S_n\}=\{x^{k/2}~|~x\in H\}$ is a proper subset of $A_n$, i.e. not equal to $A_n$. We have contradiction.
Oops, I didn't catch that the question is stated for $k$ odd only.
Comment: This is good, but the map is not a homomorphism, so it doesn't have a kernel in the group theoretician's sense -- showing map is not 1--1 is all you need. And do you mean $k~{\rm mod}(n!)$
Comment: @Timur Nasybullov:  On reflection I see how this is easily repaired to deal with $k\leqslant n$, but I am puzzled by $k>n$.
Comment: @Timur Nasybollov: I think that their point was that since $x \mapsto x^k$ may not be an homomorphism, you can't use the vocabulary of kernel (when you say "nontrivial kernel"). The proper vocabulary would be "this map is not injective because...".
Comment: @ancientmathematician
I agree that the maps $x\to x^k$ is not a homomorphism. By the word "kernel" I ment the preimage of the indetity. Now I corrected the solution for odd $k$. There were a mistake which was really not obvious for k>n.


Converter java.time.Ser para java.time.LocalDate

Question: Olá.,
Estou lendo a apostila da Caelum sobre java testes jsf web services design patterns.
O problema é que não consigo ler a data(eu substitui o Calendar pelo LocalDate na classe Negociacao) por ter essas tags(byte e int) que aparecem quando gero o xml.
E dá esse erro:
com.thoughtworks.xstream.converters.ConversionException: Cannot convert type java.time.Ser to type java.time.LocalDate

Tentei ler como mostra esse site, mas dá esse erro:
com.thoughtworks.xstream.converters.ConversionException: Text '' could not be parsed at index 0 : Text '' could not be parsed at index 0

Esse é o xml:
<negociacao>
    <preco>42.3</preco>
    <quantidade>100</quantidade>
    <data resolves-to=\"java.time.Ser\">
        <byte>3</byte>
        <int>2015</int>
        <byte>11</byte>
        <byte>8</byte>
    </data>
</negociacao>

Essa é a classe que lê para ler o xml:
import java.io.InputStream;
import java.util.List;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import br.com.caelum.argentum.modelo.Negociacao;
import br.com.caelum.argentum.util.LocalDateConverter;

public class LeitorXML {

    public List<Negociacao> carrega(InputStream inputStream){

        if(inputStream == null){
            throw new NullPointerException("a lista esta vazia");
        }

        LocalDateConverter conv = new LocalDateConverter();
        XStream stream = new XStream(new DomDriver());
        stream.registerConverter(conv);
        stream.alias("negociacao", Negociacao.class);
        return (List<Negociacao>) stream.fromXML(inputStream);
    }
}

Essa é o método da classe LeitorXMLTest:
@Test
public void carregaXmlComUmaNegociacaoEmListaUnitaria() {
    String xmlDeTeste = "<list>" +
              "<negociacao>" +
                  "<preco>43.5</preco>" +
                  "<quantidade>1000</quantidade>" +
                  "<data resolves-to=\"java.time.Ser\">" +
                      "<byte>3</byte>" +
                      "<int>2015</int>" +
                      "<byte>11</byte>" +
                      "<byte>8</byte>" +
                  "</data>" +
                  "</negociacao>" +
              "</list>";

    LeitorXML leitor = new LeitorXML();
    InputStream xml = new ByteArrayInputStream(xmlDeTeste.getBytes());

    List<Negociacao> negociacoes = leitor.carrega(xml);

    for (Negociacao negociacao : negociacoes) {
        System.out.println(negociacao.getData());
    }

    assertEquals(1, negociacoes.size());
    assertEquals(43.5, negociacoes.get(0).getPreco(), 0.00001);
    assertEquals(1000, negociacoes.get(0).getQuantidade(), 0.00001);
}

Comment: Parece que o código do *converter* que você pegou naquele fórum simplesmente não vai funcionar porque ele tenta fazer o parse diretamente de uma `String`. Você precisaria de um *converter*mais complexo para lidar com esse caso, mas infelizmente não tenho tempo de entrar nessa questão. Porém, uma alternativa seria simplesmente representar a data usando um formato textual, como `2015-12-30` e criar um converter para trabalhar sempre nesse formato.`
Answer: Como o utluiz falou no comentário, eu teria que representar a data em formato textual e assim fiz.
Mudei a classe Negociacao, no lugar de LocalDate outra classe que tem uma String:
import java.time.LocalDate;

public class Data {

    private String datastr;

    public Data(LocalDate data){
        this.datastr = data.toString();
    }

    public Data(String datastr){
        this.datastr = datastr;
    }

    public LocalDate getData() {
        return LocalDate.parse(datastr);
    }

    public String getDatastr() {
        return datastr;
    }

}

Fiz outro Converter, com base na resposta dessa pergunta:
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class LocalDateConverter implements Converter {

    @Override
    public boolean canConvert(Class type) {
        return AbstractMap.class.isAssignableFrom(type);
    }

    @Override
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {

        AbstractMap map = (AbstractMap) source;

        for(Object obj : map.entrySet()){
            Entry entry = (Entry) obj;

            writer.startNode(entry.getKey().toString());
           writer.setValue(entry.getValue().toString());
           writer.endNode();
        }

    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        reader.moveDown();
        Data data = new Data(reader.getValue());
        reader.moveUp();

        return data;
    }
}

E o xml ficou assim:
<negociacao>
    <preco>42.3</preco>
    <quantidade>100</quantidade>
    <data>
        <datastr>2015-11-12</datastr>
    </data>
</negociacao>

Demorou, mas consegui fazer.


Group of isometries of $\mathbb{R}^n$

Question:
Determine the group of isometries of $\mathbb{R}^n$ equipped with the
  sup metric.

My wild guess is $(a_1,\ldots,a_n)\mapsto(\pm a_{\sigma(1)},\ldots,\pm a_{\sigma(n)})+(c_1,\ldots,c_n)$ where $(c_1,\ldots,c_n)$ is constant, the choice of $\pm$'s are the same for all elements in the domain, and $\sigma$ is a permutation of $(1,2,\ldots,n)$. What I note was that subtracting the function by a constant, changing the sign in one entry, and permuting the entries preserve the isometric property.
So we can assume $f(0,\ldots,0)=(0,\ldots,0)$. For any vector $(a_1,\ldots,a_n)$, $\|f(a_1,\ldots,a_n)-(0,\ldots,0)\|=\|(a_1,\ldots,a_n)-(0,\ldots,0)\|$, so $\|f(a_1,\ldots,a_n)\|=\max|a_i|$. Therefore, for some $k$, there are infinitely many vectors $(a_1,\ldots,a_n)$ with $\|f(a_1,\ldots,a_n)\|=|a_k|$. Among them, there are infinitely many $(a_1,\ldots,a_n)$ such that $\|f(a_1,\ldots,a_n)\|$ is the absolute value of its $j$-th position. By permuting the entries, we can assume $j=k=1$. These vectors have the property that the first entries of $f(a_1,\ldots,a_n)$ and $(a_1,\ldots,a_n)$ coincide in absolute value. Since we can change the sign in one entry, assume infinitely many of them coincide with the same sign.
I was thinking, from here we may be able to prove the same result for any vector, i.e., the first entries of $f(a_1,\ldots,a_n)$ and $(a_1,\ldots,a_n)$ are equal. Then, we can move on to the second, third, all the way up to the $n$-th entry. But I got stucked here.
Comment: Think about what an isometry fixing $0$ has to do when restricted to the extremal points of the unit ball. Your wild guess is correct.
Comment: Can somebody write up an answer perhaps - @pola? It can be a CW one if you don't want credit.
Comment: I managed to prove that the isometry sends the extremal points into themselves (it's very difficult for me :P). But I cannot prove that it maps "correctly", and I don't know how to continue from here.
Comment: Notice that every vector of the standard basis is uniquely a combination of $2^{n-1}$ of the extremal points and conversely, such a combination of norm $1$ of $2^{n-1}$ of the extremal points is $\pm$ a standard basis vector (prove this by induction).
Comment: By combination I mean of course a convex combination.
Comment: What is a combination of norm 1? Does it mean the arithmetic mean? Anyway, I haven't been able to prove it, but can you give a direction on how to complete the proof after this? I'm not sure how to make use of it, because the norm function is not linear.
Comment: Yes, you can say an arithmetic mean instead. If an arithmetic mean of $2^{n-1}$ extremal points has norm one then it is $\pm$ a basis vector. Now this tells you that every standard basis vector is sent to a standard basis vector. And since you certainly assume that your isometry is surjective, it is linear if it fixes zero, so it is determined by its action on the standard basis.
Comment: So, there's a theorem of Mazur-Ulam (I didn't know this theorem, just did a quick search). It makes everything much easier. Thanks a lot!
Comment: No problem. By the way, this result on the isometry group holds for all $\ell^p$ norms on $\mathbb{R}^n$ for $p \neq 2$ by a theorem of Banach and Lamperti.
Answer: Theorem. The isometries of $\mathbb{R}^n$ with respect to the sup metric are precisely the functions of the form
$$
f(p) \;=\; Ap + b
$$
where $A\in\textit{O}(n)$ is a Euclidean symmetry of the unit cube $[-1,1]^n$ and $b\in\mathbb{R}^n$.
Proof: It is easy to see that maps of the given form are isometries.  We must show that every isometry has this form.
Let $d$ denote the sup metric.  We shall refer to balls in $\mathbb{R}^n$ with respect to $d$ as "cubes". Here are some definitions that we can make using only $d$:

If $p,q\in\mathbb{R}^n$, a midpoint of $p$ and $q$ is a point $m\in\mathbb{R}^n$ for which
$$
d(p,m) \;=\; d(q,m) \;=\; \frac{1}{2} d(p,q).
$$
Two points $p,q\in\mathbb{R}^n$ are diagonal from one another if they have a unique midpoint.
A corner of a cube is a point on the boundary that is diagonal from the center point.  Each cube has $2^n$ corners.
Two cubes are adjacent if they have exactly $2^{n-1}$ corners in common.  Each cube has precisely $2n$ different cubes adjacent to it.
The intersection of two adjacent cubes is a facet of each.  A face of a cube is any intersection of its facets.

Now, let $f$ be an isometry of $\mathbb{R}^n$.  By composing with a translation, we may assume that $f$ fixes the origin.  From the above discussion, it is clear that $f$ must permute the corners of the unit cube $[-1,1]^n$ in a face-preserving way. Composing with a Euclidean symmetry of the cube, we may assume that $f$ fixes each of the corners.  At this point, we wish to show that $f$ is the identity map.
To do so, consider the subdivision of the unit cube $[-1,1]^n$ into $2^n$ subcubes of radius $1/2$.  These subcubes are precisely those that have the origin and a corner of the large cube as opposite corners, and therefore $f$ must map each of these subcubes to itself.  Furthermore, since $f$ fixes the facets of the large cube, $f$ must fix the corners of each of these subcubes.  Repeating this process, we find that the $4^n$ canonical subcubes of radius $1/4$ are invariant under $f$, and so forth.  But every point in the unit cube is the intersection of some nested sequence of these subcubes, and therefore $f$ fixes every point in $[-1,1]^n$.
To get outside the unit cube, observe that any cube $C$ adjacent to the unit cube must map to itself under $f$.  Moreover, since $f$ fixes a facet of $C$, it must fix all of the corners of $C$, and therefore must fix $C$ pointwise by the argument above.  Continuing in this fashion, we can prove that every cube in the integer lattice is fixed by $f$ pointwise, and therefore $f$ is the identity map.

Group of isometries of $\mathbb{R}^n$


Can an AWS Classic Load Balancer redirect traffic from a public ip address to a ec2 instance with only private ips?

Question: I have a classic load balancer that has public ip addresses. Do the ec2 instances that it routes traffic to need public ip addresses as well, or will it successfully redirect the traffic to a private ip address? They're all located in different subnets in the same VPC.
The Classic Load Balancer allowed me to add the instances with only private ip addresses without any sort of complaints or errors.
Answer: Your internet facing load balancers need public IP addresses. Your EC2 instances do not require public IP addresses, the ELB can load balance to private IPs. Private IPs sometimes make the traffic a little cheaper than public IPs, but not 100% sure in this situation.
You seem to have already done this, so I'm curious why you didn't just try it and see what happens.
Comment: Classic and Application load balancers always communicate with the instances behind them using the instance's private IP address, even if the instance happens to have a public IP address -- which, as you point out, is not needed.
Comment: Oh it's in production and I was 99% sure it was OK, but I wanted to check before actually moving traffic around since I wasn't quite sure how the Classic Load Balancer worked and couldn't find exact documentation on it's behavior. Thank you both for your insight!


Como remover caracteres indesejados de uma lista de strings?

Question: Sou novo em python e não consegui achar uma resposta para minha dúvida.
Recebo uma lista de textos do banco de dados e o transformo em uma lista de strings conforme abaixo:
textosPuros = df['texto']
# print(textosPuros)

textoMinusculo = textosPuros.str.lower().str.split(' ')

# print(textoMinusculo)

textoLimpo = [item for item in textoMinusculo if item not in ['\n', '\t', '/', '.', '-', '(', ')']]

Numa tentativa de limpar as strings para que possa trabalhar com elas normalizadas, implementei a última linha, mas, mesmo assim, tenho caracteres ruins:
[['\testá', 'tossindo', 'noite.mãe', 'fez', 'inalação', 'com', 'berotec', 'essa', 'noite,com', 'melhora', '.está', 'usando', 'o', 'piemonte', 'há', '2', 'cuidou', '', ',', '----', 'com', '', 'febre.é', 'muito', 'ansioso', 'e', 'agitado.\nex.f:beg', 'corado,com', 'taquipnéia', 'leve', 'afebril', 's/sinais', 'meníngeos', 'otosc:nl', 'cavum:hiperemia', 'pulmões:esc+sibilos', 'abdome', 'nl\t'],['mais strings','episódio\n\nap\n-','\t0000000000\t'],['outra lista','menopausea.\n\nexames']]

Como faço para retirar estes caracteres indesejados? Como

\t \n : . , - _
Comment: Possível duplicata de [Como remover caracteres de uma string?](https://pt.stackoverflow.com/questions/120389/como-remover-caracteres-de-uma-string)
Comment: [Remover caracteres não numéricos de uma string em Python](https://pt.stackoverflow.com/q/254748/5878)
Comment: boa tarde amigo, veja se isso te ajuda: https://stackoverflow.com/questions/29251378/replace-n-in-a-string-in-python-2-7
Comment: @Anderson, é uma lista não uma string simples
Comment: @HenriqueMendes se é uma lista de string, basta percorrer a lista e aplicar as soluções dadas. Não muda praticamente nada.
Comment: Ele me retorna um erro : AttributeError: 'list' object has no attribute 'replace' sempre que tentei
Comment: Eu preciso retornar este valor para a lista.
Answer: Isto deve funcionar
novo = []
for x in lista:
    item = x
    for y in ['\n', '\t', '/', '.', '-', '(', ')']:
        item = item.replace(y, "")
    novo.append(item)

ou
novo = []
for x in lista:
    novo.append(x.translate(None, "\n\t/.-()"))

Comment: A primeira resolveu bastante coisa sim! Muito obrigado!


General form for the recurrence relation $a_{n+1} - a_n = 4^n$

Question: So... I just learned about discrete, and I'm trying to solve this problem, finding the general term I guess :
$$
a_1 = 1,\qquad a_{n+1} - a_n = 4^n\, \text{ for all } n\geq 1
$$
I looked at some examples and found that the solution is $a_n = \frac{1}{3}(4^n - 1)$.
Can anyone explain this?
Comment: $a_{n+1} =a_1+ \sum_{i=1}^n(a_{i+1} - a_{i}) =1+ \sum_{i=1}^n 4^i = \sum_{i=0}^n 4^i$. Looks like the partial sum of a geometric series
Comment: After you ask a question here, if you get an acceptable answer, you should "accept" the answer by clicking the check mark ✓ next to it. This scores points for you and for the person who answered your question. You can find out more about accepting answers here: [How do I accept an answer?](http://meta.math.stackexchange.com/questions/3286/), [Why should we accept answers?](http://meta.math.stackexchange.com/questions/3399/).
Answer: Start with what you know: for every $n\geq 1$,
$$
a_{n+1}-a_n = 4^n \tag{1}
$$
Now, what happens if you sum this equation (1), for $n$ ranging from $1$ to some $N\geq 1$?
$$
\sum_{n=1}^N (a_{n+1}-a_n) = \sum_{n=1}^N 4^n \tag{2}
$$
But the left-hand-side is a telescopic series:
$$
\sum_{n=1}^N (a_{n+1}-a_n) = (a_{N+1} - a_N) + (a_N-a_{N-1})+\dots + (a_2-a_1) = a_{N+1} - a_1
$$
but the right-hand-side is a geometric sum, equal to $$
4\cdot\frac{4^N-1}{4-1} = \frac{4}{3}(4^N - 1)
$$
Therefore, you end up with
$
a_{N+1} - 1 = \frac{4}{3}(4^N - 1)
$ or equivalently
$$
a_{N+1} = \frac{1}{3}(4^{N+1} - 1)
$$
for $N\geq 1$.
Comment: why does the equivalent answer to  a(N+1) - 1 = 4/3(4^N - 1) is a(N+1) = ⅓(4^N+1 - 1)
Comment: Expand the right-hand side in two terms; add 1 to both sides.
Comment: @AJTech Is it clearer?
Answer: Let a_n=c(lamda)^n be a solution to a_n+1 - a_n = 4^n
so we have c(lamda)^n)(lamda-1)=4^n
which is c(lamda-1)=(4/lamda)^n
so if lamda is 4 RHS is 1 so c(4-1)=1 so c=1/3
therefore a_n=1/3 (4)^n solves a_n+1 - a_n = 4^n
yet a_1=1 so then a_1= 1/3 (4) needs to be adjusted by 1/3
so we have a_n=1/3 (4^n-1)


How to solve local changes to file overwritten when pulling after a git update-index --assume-unchanged?

Question: I have a config file storing my local database connection details etc: application.ini.
After I initially pulled the project the application.ini file is tracked.
So I decided to use:
git update-index --assume-unchanged application.ini
After which I made changes to the file regarding my mysql connection.
All was alright and I am certain that the (tracked) application.ini file on the repo was changed so now when I use:
git pull

I get:
From github.com:username/repo
   669826e..64872d9  master     -> origin/master
Updating ef81735..64872d9
error: Your local changes to the following files would be overwritten by merge:
        application/configs/application.ini
Please, commit your changes or stash them before you can merge.

git status:
Your branch is behind 'origin/master' by 36 commits, and can be fast-forwarded.
  (use "git pull" to update your local branch)

nothing to commit, working directory clean

git stash save 'application.ini changes':
No local changes to save

Comment: what if you try to `pull` again? Do you get the same error?
Comment: yes, `git pull` and `git pull -v`
Answer: To revert --assume-unchanged, which is causing you problems,  use --no-assume-unchanged.
Perform this command:
$ git update-index --no-assume-unchanged application.ini

Then before doing a pull, stash your local changes:
$ git stash

Do git pull:
$ git pull

Pop application.ini saved changes from stash:
$ git stash pop

Comment: Thanks it worked, however before the `git stash pop` step I said `git update-index --assume-unchanged application.ini`. Now when I tye `git status` I have (Changes not staged: application.ini)
Comment: Yeah you can do that before or after `stash pop`. Please accept the answer if it solved your issue ;)


Replacing a HTML tag with Grunt-Replace

Question: I'm working on a grunt file for work.  We work locally with our files being in html and when we implement them into our CMS they need to be converted to aspx.
I'm trying to replace all instances of  with <imod:ScriptPlaceHolder id="#nameOfFile" runat="server" type="FileInclude" url="#pathToFile"></imod:ScriptPlaceHolder>
I'm using "grunt-replace": "^0.8.0."  This task is registered under default and build.  I've tried using a regex to match the name, and I've been looking at the documentation for far too long.  Here is what my grunt file with replace looks like:
replace: {
      dist: {
        options: {
          patterns: [
            {
              match: '/script src="/g',
              replacement: function() {
                'asp:PlaceHolder runat="server" url="';
              }
            }
          ]
        },
        files: [
          {expand: true, flatten: true, src: ['<%= config.dist %>/index.html'], dest: 'dist/'}
        ]
      }
    },

Answer: With some help from Matthew Kime, I was able to get this working.  In my regex I had to search for 2 periods because I'm using grunt-rev to version my files.  I also used the file name stripped of it's extension to name the files dynamically.
Here is the conclusion I was able to arrive at.
// replace script tags to imod placeholders
    replace: {
      dist: {
        options: {
          patterns: [
            {
              match: //g'
also, your replacement function needs to return a value. obviously if you're replacing with a static string then you can use a string for the argument instead.
Comment: You are completely correct about needing a return.  I'll be bookmarking the link you included, it was extremely helpful.
Comment: ah, i stepped on your data extraction with that regex.

Replacing a HTML tag with Grunt-Replace


Determine the isomorphism class of M/T(M)

Question:
Let $M=\Bbb{Z}\oplus\Bbb{Z}\oplus\Bbb{Z}$ and $T: M\rightarrow M$ given by $T(x,y,z)=(4x+2z,2y,2x+10z)$. Show the cokernel $M/T(M)$ is an abelian group of order $72$, and determine its isomorphism class.

I tried to solve it by looking at when the linear system has solution over Z, but it didn't get me anywhere.
I feel like this should not be an awefully hard question, but I don't know how to start. Can you give me some help? Thank you very much.
Comment: $T(M)=\{b\in \mathbb{Z}^{3}: Ax=b\}$ where $A=\left(
  \begin{array}{ccc}
    4 & 0 & 2 \\
    0 & 2 & 0 \\
    2 & 0 & 10 \\
  \end{array}
\right)
$
Answer: $T(M)$ has generators $(4,0,2)$, $(0,2,0)$, $(2,0,10)$, so we have the relations matrix
$$\left(
  \begin{array}{ccc}
    4 & 0 & 2 \\
    0 & 2 & 0 \\
    2& 0 & 10 \\
  \end{array}
\right)$$
Computing the Smith normal form for this matrix gives
$$\left(
  \begin{array}{ccc}
    2 & 0 & 0 \\
    0 & 2 & 0 \\
    0& 0 & 18 \\
  \end{array}
\right)$$
and hence $M/T(M) \cong \mathbb{Z}/2 \oplus \mathbb{Z}/2 \oplus \mathbb{Z}/18$ which has order $72$.
Answer: If you try to solve $Ax=b$ where
$A= \left(
  \begin{array}{ccc}
    4 & 0 & 2 \\
    0 & 2 & 0 \\
    2& 0 & 10 \\
  \end{array}
\right)$
 and  $b=\left(\begin{array}{c}b_{1}\\b_{2}\\b_{3}\end{array}\right)$
you need check which condition $b_{1}, b_{2}$ and $b_{3}$ must have in order to have a solution in $\mathbb{Z}^{3}$.
In this case $T(M)=36\mathbb{Z}\oplus 2\mathbb{Z}\oplus9\mathbb{Z}$
So
$\begin{eqnarray}\frac{M}{T(M)}&=&\frac{\mathbb{Z}\oplus\mathbb{Z}\oplus\mathbb{Z}}{36\mathbb{Z}\oplus 2\mathbb{Z}\oplus9\mathbb{Z}}\\
&\cong&\frac{\mathbb{Z}}{36\mathbb{Z}}\oplus\frac{\mathbb{Z}}{2\mathbb{Z}}\oplus\frac{\mathbb{Z}}{9\mathbb{Z}}\\
&\cong& \mathbb{Z}_{36}\oplus\mathbb{Z}_{2}\oplus\mathbb{Z}_{9} \end{eqnarray}$
I hope it helps you.
Comment: If I can see well the last entry $b_3$ is always even. Actually $T(M)=2\mathbb Z\oplus2\mathbb Z\oplus18\mathbb Z$.


Undefined index q

Question: I have 2 websites on the same server.
They both use the same modules.
In one of them, I get the following notices:

Notice: Undefined index: q in current_path() (line 355 of /var/www/drupal/includes/path.inc).
  Notice: Undefined index: q in l() (line 2424 of /var/www/drupal/includes/common.inc).
  Notice: Undefined index: q in arg() (line 2792 of /var/www/drupal/includes/bootstrap.inc).

Does anyone have any idea about what can cause these notices?
The website is working perfectly, and I know I can put some error_reporting in the settings.php, but it won't solve the problem.
Comment: What version of Drupal?
Comment: Sorry, drupal 7.21
Comment: Do you have any URL rewriting module or htaccess rules added ?
Comment: I have Boost (with htaccess rules. works perfect) and Redirect modules active.
Answer: Line 355 of /includes/path.inc contains this code:
return $_GET['q'];

So, we can suppose, that $_GET['q'] is undefined. According to documentation, this variable is initialized in drupal_path_initialize function during bootstrap. It's code:
function drupal_path_initialize() {
  if (empty($_GET['q'])) {
    $_GET['q'] = variable_get('site_frontpage', 'node');
  }
  $_GET['q'] = drupal_get_normal_path($_GET['q']);
}

Maybe, the function drupal_get_normal_path gives undefined value for 'site_frontpage' var?
Comment: I have changed drupal_path_initialize to include the following code at the end:

But it's never empty in this function. it always contains good value.
Comment: do you still get this error: Undefined index: q in current_path() (line 355 ?
Comment: As I wrote earlier, that was a stupid mistake I made somewhere in the theme unset($_GET['q']) for some stupid reason. Thanks for the help!
Answer: Never mind,
That was a stupid mistake of mine in my custom theme.

Undefined index q


How to load json and value out of json in Pig?

Question: I have a json and value out of json

000000,{"000":{"phoneNumber":null,"firstName":"xyz","lastName":"pqr","email":"firstname.lastname@example.com","alternatePickup":true,"sendTextNotification":false,"isSendTextNotification":false,"isAlternatePickup":true}}

I'm trying to load this json in pig using elephant bird json loader but unable to do that.
I'm  able to load the following json

{"000":{"phoneNumber":null,"firstName":"xyz","lastName":"pqr","email":"firstname.lastname@example.com","alternatePickup":true,"sendTextNotification":false,"isSendTextNotification":false,"isAlternatePickup":true}}

Using following script -
REGISTER json-simple-1.1.1.jar;
REGISTER elephant-bird-pig-4.3.jar;
REGISTER elephant-bird-hadoop-compat-4.3.jar;

json_data = load 'ek.json' using com.twitter.elephantbird.pig.load.JsonLoader() AS (json_key: [(phoneNumber:chararray,firstName:chararray,lastName:chararray,email:chararray,alternatePickup:boolean,sendTextNotification:boolean,isSendTextNotification:boolean,isAlternatePickup:boolean)]);

dump json_data;

But when I include value out of json
json_data = load 'ek.json' using com.twitter.elephantbird.pig.load.JsonLoader() AS (id:int,json_key: [(phoneNumber:chararray,firstName:chararray,lastName:chararray,email:chararray,alternatePickup:boolean,sendTextNotification:boolean,isSendTextNotification:boolean,isAlternatePickup:boolean)]);

it is not working!! Appreciate the help in advance.
Answer: You can use builtin JsonStorage and JsonLoader()
a = load 'a.json' using JsonLoader('a0:int,a1:{(a10:int,a11:chararray)},a2:(a20:double,a21:bytearray),a3:[chararray]');

In this example data is loaded without a schema; it assumes there is a .pig_schema (produced by JsonStorage) in the input directory.
a = load 'a.json' using JsonLoader();

Answer: JsonLoader allows loading only of correct json, while your format is actually CSV. There are three options for you ordered by incresing complexity:

Adjust your input format and make id part of it
Load data as CSV (as 2 fields: id and json, then use custom UDF to parse json field into a tuple)
Write custom loader that will allow you your original format.


AT91 ARM EMAC polling issue

Question: I am using atmel's lwip example. Interfacing with PHY is ok. It can link and even auto negotiate. Netif is going up. But when i start polling netif nothing happens. Ive narrowed down problem to EMAC_Poll
unsigned char EMAC_Poll(unsigned char *pFrame, unsigned int frameSize, unsigned int *pRcvSize)
{
    unsigned short bufferLength;
    unsigned int   tmpFrameSize=0;
    unsigned char  *pTmpFrame=0;
    unsigned int   tmpIdx = rxTd.idx;
    volatile EmacRxTDescriptor *pRxTd = rxTd.td + rxTd.idx;

    ASSERT(pFrame, "F: EMAC_Poll\n\r");

    char isFrame = 0;
    // Set the default return value
    *pRcvSize = 0;

    // Process received RxTd
    while ((pRxTd->addr & EMAC_RX_OWNERSHIP_BIT) == EMAC_RX_OWNERSHIP_BIT) {
        // Never got there.
        ...
    }
    return EMAC_RX_NO_DATA;
}

typedef struct {
   volatile EmacRxTDescriptor td[RX_BUFFERS];
   EMAC_RxCallback rxCb; /// Callback function to be invoked once a frame has been received
   unsigned short idx;
} RxTd;

/// Describes the type and attribute of Receive Transfer descriptor.
typedef struct _EmacRxTDescriptor {
    unsigned int addr;
    unsigned int status;
} __attribute__((packed, aligned(8))) EmacRxTDescriptor, *PEmacRxTDescriptor;

There is while loop, but condition is never goes true.
I have very vague presentation what is RxTd and what exacly this condition means. However i can not see how thise RxTd Would change to pass condition. All references of RxTd leads to same emac.c module. Most of them in that polling function and rest in EMAC_ResetRx function.
static void EMAC_ResetRx(void)
{
    unsigned int Index;
    unsigned int Address;

    // Disable RX
    AT91C_BASE_EMAC->EMAC_NCR &= ~AT91C_EMAC_RE;
    // Setup the RX descriptors.
    rxTd.idx = 0;
    for(Index = 0; Index < RX_BUFFERS; Index++) {

        Address = (unsigned int)(&(pRxBuffer[Index * EMAC_RX_UNITSIZE]));
        // Remove EMAC_RX_OWNERSHIP_BIT and EMAC_RX_WRAP_BIT
        rxTd.td[Index].addr = Address & EMAC_ADDRESS_MASK;
        rxTd.td[Index].status = 0;
    }
    rxTd.td[RX_BUFFERS - 1].addr |= EMAC_RX_WRAP_BIT;
    // Receive Buffer Queue Pointer Register
    AT91C_BASE_EMAC->EMAC_RBQP = (unsigned int) (rxTd.td);
}

I do not realy understand last line, but it looks like that rxTd is auto filled with AT91 itself. If it is so, there may be packing/aligment problem, but Atmel added __attribute__ ((packed, aligned(8))) on RxTd structure definition. Any way, can someone describe mechanism of data input or tell me where proble might be?
By the way i am using gcc, if that matters.
UPD:
Ive checked RSR and notice that it is start with 0, then goes to 2 after second. 2- means new data was captured.
UPD:
So i've read about function of emac in datasheet for my chip. I was right. That RBQP register must point to array of descriptors. Each descriptor consists of address and status field. The datasheet states that "bit zero of address field is written to one to show the buffer has been used". Then ARM uses another rx descriptor from that array. I guess by "has been used" they mean that that buffer is filled with frame data and ready to be processed. This must mean that data just not going to that buffer. But it must be there because REC goes high. Additionaly i've checked that RE in NCR is up and MI is enabled. I have no idea what is wrong.
Answer: I've spend whole week to solve it. The funny thing is that if i've dump memory and looked at all those addresses - The data was there whole time! So the key was to disable I and D caching and MMU itself. Hope it will help someone.

AT91 ARM EMAC polling issue


print json object like {key:value} by jq utiliity

Question: i have json:
{
  "ssh_key":
    {
      "id": 123,
      "public_key": "ssh-rsa 1233123333333333333dafseg345345345",
      "name": "MY.PUB.KEY",
      "fingerprint": "94:45:54:22:3f:55:ff:55"
    }
}

i can't print only 1 object {"id":123} with jq, i tryed like this:
jq '.ssh_key | to_entries[] | {"id": .key, "value": .value.id}'
jq: error (at <stdin>:1): Cannot index number with string "id"

Comment: `jq '.ssh_key | {id}'`?
Comment: If you actually want just the id (not an object), `jq -r .ssh_key.id`
Comment: Thanks, it works!
Answer: This is the working solution:
jq '.ssh_key | {id}'

which outputs:
{
  "id": 123
}


Exportação .csv com complemento de linhas com base em um número fixo

Question: Tenho uma tabela no MySQL de produtos. Preciso criar uma exportação .csv deles.
Os produtos estão no banco da seguinte forma:
cod    produto    valor    pagina
123    caderno     1,00    1
456    lápis       1,00    1
789    borracha    1,00    1
1122   régua       1,00    2
1123   cola        1,00    2
1122   caneta      1,00    3

Preciso definir uma quantidade fixa de linhas por página. Quando o limite não for atingido preciso completar com espaços vazios. Vamos imaginar que o limite seja 5.
Esperado:
cod    produto    valor    pagina
123    caderno     1,00    1
456    lápis       1,00    1
789    borracha    1,00    1
 -        -          -     -
 -        -          -     -
1122   régua       1,00    2
1122   cola        1,00    2
 -        -          -     -
 -        -          -     -
 -        -          -     -
 1122   caneta      1,00   3
 -        -          -     -
 -        -          -     -
 -        -          -     -
 -        -          -     -
 -        -          -     -

Isso pode ser feito no MySQL ou PHP, mas alguém tem ideia de como eu poderia fazer?
Tenho a seguinte query:
$pagina = 0;
$quantidade = 24;
$inicio     =  ($quantidade * $pagina) - $quantidade;
$export = $conn->prepare("SELECT
  f.prod_produto,f.prod_marca,
  f.prod_tipo1,f.prod_tipo2,
  SUBSTRING_INDEX(f.prod_preco,'.',1) AS prod_preco,
  SUBSTRING_INDEX(f.prod_preco,'.',-1) AS prod_centavos,
  REPLACE(f.prod_gramatura,',','.') AS prod_gramatura,
  (CASE
  WHEN f.prod_pais = 0 THEN 'BRA' ELSE   p.iso3
  END) AS pais,
  prod_pagina AS pagina
  FROM
  produto AS f
  LEFT JOIN cep_paises AS p
  ON p.numcode = f.prod_pais
  WHERE
  prod_periodo = '16'
  ORDER BY prod_pagina ASC
  LIMIT  $inicio,$quantidade");
$export->execute(array());

while($dados = $export->fetch()){
   //exibe produtos
  echo $dados[0]."
";
}
if($export->rowCount() < $quantidade){
  $conta = $quantidade - $export->rowCount();
  while($conta <= $quantidade){
    echo $conta++;
        //preenche as linhas em branco
  }
}

Isso me provoca o seguinte erro:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MariaDB server version for the right syntax to use near '-24,24' at
  line 18' in
  C:\Users\server\htdocs\sistemas\modulos\produtos\export.php:92 Stack
  trace: #0
  C:\Users\server\htdocs\sistemas\modulos\produtos\export.php(92):
  PDOStatement->execute(Array) #1 {main} thrown in
  C:\Users\server\htdocs\sistemas\modulos\produtos\export.php on line 92
Answer: $paginaAtual = "";
$limite = 5;
$conta = 0;
while($dados = $export->fetch()){
   //exibe produtos
  if($paginaAtual ==""){ //define a primeira pagina
      $paginaAtual = $dados["pagina"];
      $conta = 0;
  }elseif($paginaAtual != $dados['pagina']){//verifica se mudou de pagina
       while($conta < $limite){ // verifica se ficou algum item a menos
           echo "-        -          -     -"
            $conta++;
       }
       $paginaAtual = $dados["pagina"];
       $conta = 0;
  }
   $conta++
  echo $dados["produto"]."
";
}
while($conta < $limite){ // verifica pela ultima vez
       echo "-        -          -     -"
        $conta++;
   }

Comment: O que seria:  CAMPO == CAMPO2 ?
Comment: vc pode substituir por variaveis q deseja utilizar ai $val == $val2
Comment: retornou um erro ao tentar fazer, anexei o erro na sua resposta, sabe o que poderia ser?
Comment: Adicionei a minha pergunta a query original para você ver como ficou
Comment: oi, qual erro não estou vendo aqui
Comment: Adicionei a minha pergunta, tinha adicionado na sua mais não mostrou mesmo.
Comment: Parece que tem algo de errado com o limit  -24,24 ele limite é essas suas linhas:   $quantidade = 24;
 $inicio     =  ($quantidade * $pagina) - $quantidade;
Comment: "-24,24"  no seu limit está sendo passado um valor negativo, tente alterar o valor de pagina $pagina = 0;  para $pagina = 1;
Comment: Parou de dar erro , mais não esta contando os vazios
Comment: Entendi o que aconteceu, ela não esta quebrando as paginas como no exemplo acima, ele calcula os 24 como um todo, mais preciso que ele calcule pela coluna pagina como mostrado no exemplo
Comment: Veja, aumentei as quantidades e retornou: rowcount50
quantidade50 , a quantidade de paginas que eu coloco ele vai somando as paginas ao inves de quebra-las como eu quero
Comment: alterei a resposta, remove o limit do seu SQL, e altera o seu while
Comment: 90% , porque deu certo, mais somente na primeira pagina, por exemplo, no meu caso na pagina 06 teria que acontecer essa regra mais não foi, ja quebrei a cabela nos loops mais não encontrei o que poderia ser
Comment: deixa eu entender somente  na  ultima  pagina  não está acontecendo o preenchimento das linhas restantes ?
Comment: sim, mais é porque assim, meu limite é 24 com isso na pagina 1 tem 10 ele completa, a pagina 3 tem 24, a pagina 3 tem 24, e por ai vai, na pagina 6 tem 9 ele deveria completar até 24 mais não completou
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/70510/discussion-between-otacio-barbosa-and-marcos-brinner-pikatoons).


There exists rational number $a_n$, $(x^2+\frac{1}{2}x+1)\mid(x^{2n}+a_nx^n+1)$

Question: Let $n\in \mathbb{N}$. Prove that there exists a rational number $a_n$ for which $$(x^2+\frac{1}{2}x+1)\mid(x^{2n}+a_nx^n+1)$$
My attempt :
I try $n=2$,
$(x^2+\frac{1}{2}x+1)(x^2-\frac{1}{2}x+1)=x^4+\frac{7}{4}x^2+1$
$a_2 = \frac{7}{4}$
Comment: Can you imagine there are two votes to close the question as "off topic"?! I quote what is certainly not off-topic, from the Help Center: "Understanding mathematical concepts and theorems, Mathematical problems such as one might come across in a course or textbook, Solving mathematical puzzles."
Comment: It isn't, of course. Just some people at this site are very, very sick, and often forget to take their meds. They can vote to close only with a reputation of 3000 or more, so they know enough math to realize that this is _not_ off-topic. They're just misusing the power of their reputation, the poor bastards. Don't take it personally.
Comment: I don't understand why this is off topic.
Comment: @Professor Vector. Thank you :)
Answer: just an idea
The roots of the left polynom are
$$x_1=\frac{-1+i\sqrt {15} }{4}=e^{it}$$
$$x_2=\frac {-1-i\sqrt {15} }{4}=e^{-it} $$
they are also roots of the right one
$$e^{2int}+a_ne^{int}+1=0$$
$$e^{-2int}+a_ne^{-int}+1=0$$
thus
$$a_n=-\frac {\sin (2nt)}{\sin (nt)} $$
$$=-2\cos (nt) $$
For example,
$$a_2=-2\cos (2t)=2 (1-2\cos^2 (t)) $$
$$=2-4\frac {1}{16}=\frac {7}{4} $$
Comment: Correct, and since $\cos t=(e^{it}+e^{-it})/2=-1/4,$ you have the explicit expression $a_n=-2 T_n(-1/4),$ where $T_n$ are the Chebyshev polynomials of first kind (https://en.wikipedia.org/wiki/Chebyshev_polynomials).
Comment: @ProfessorVector Thanks a lot Professor. I did not think about Chebyshev.
Comment: Thank you, Salahamam_Fatima and ProfessorVector. Can this problem be solved using knowledge at high school level ?
Comment: @carat I'll give it a try.
Comment: Nice way of thinking about it! +1s to all in this thread.
Answer: We define $$p_n(x)=x^{2n}+a_n\,x^n+1,$$ so we have to prove
$$\left.x^2+\frac12\,x+1\right|p_n(x).$$
This is clearly true for $n=1$ with $a_1=1/2$, and it was shown for $n=2$ with $a_2=7/4$. Induction step: we assume it's true for $n=k-1$ and $n=k$.  Then, as can be seen by expanding the products,
$$p_{k+1}(x)=(x^{2k}+1)\left(x^2+\frac12\,x+1\right)-\frac12\,x\,p_k(x)-x^2\,p_{k-1}(x),$$ if only $$a_{k+1}=-\frac12\,a_k-a_{k-1},$$ so $$\left.x^2+\frac12\,x+1\right|p_{k+1}(x).$$
Comment: Since $a_1, a_2 \in \mathbb{Q}$, so $a_n \in \mathbb{Q}, \;\forall n \in \mathbb{N}$. Thank you very much, Professor Vector.


C++ Google test - exporting additional information like 'author' and 'project' to XML report

Question: I am using the output parameter of google test like

--gtest_output=xml:Reports\fooReport.xml

However some XML attributes like author and project won´t be exported as the tool gtest2html might expect.
Is there a property like 'author' available in gtest at all? If so, where would I assign it?
Answer: Explanation
In GoogleTest, those fields that you see in gtest2html like 'author', 'project', etc. are not available in the xml output by default. Those are custom field expected to be found by gtest2html.
However, you can add them to the same xml element using RecordProperty function provided by GoogleTest.
The final section of the documentation explains:

Calling RecordProperty() outside of the lifespan of a test is allowed. If it's called outside of a test but between a test suite's SetUpTestSuite() and TearDownTestSuite() methods, it will be attributed to the XML element for the test suite. If it's called outside of all test suites (e.g. in a test environment), it will be attributed to the top-level XML element.

So, in order to make your xml output compatible with gtest2html, you need those fields in the outermost xml element (which has the tag "testsuites").
Solution
So, in main or in a test environment (you don't have to use one, but it is strongly recommended in the documentation), before any test is started, you need to add below call:
::testing::Test::RecordProperty ("project", "MyProject");

This will then add this to the xml output:
<testsuites ... project="MyProject" name="AllTests">

(I know it is quite late as an answer, but hopefully this will help someone)