How to implement Aly's permutation test for comparison of variances in R?

Question: The excerpt below is from "Permutation, Parametric and Bootstrap Tests of Hypotheses", Third Ed. by Phillip Good (pages 58-61), section 3.7.2..
I am trying to implement this permutation test in R (see further below) to compare two variances. I am thinking now about how to calculate the p-value, and whether the test allows for different alternative hypothesis (greater, less, two-sided) and I am not sure on how to proceed.
Could you shed some light on this and perhaps give me some criticism about the code? Many thanks!

<code># Aly's non-parametric, permutation test of equality of variances
# From "Permutation, Parametric and Bootstrap Tests of Hypotheses", Third Ed.
# by Phillip Good (pages 58-61), section 3.7.2.

# Implementation of delta statistic as defined by formula in page 60
# x_{i}, order statistics
# z = x_{i+1} - x_{i}, differences between successive order statistics
aly_delta_statistic <- function(z) {
  z_length <- length(z)
  m <- z_length + 1
  i <- 1:z_length
  sum(i*(m-i)*z)
}

aly_test_statistic <- function(sample1, sample2 = NULL, nperm = 1) {

  # compute statistic based on one sample only: sample1
  if(is.null(sample2)) {
    sample1 <- sort(sample1)
    z <- diff(sample1)
    return(aly_delta_statistic(z))
  }

  # statistic based on randomization of the two samples
  else {
    m1 <- length(sample1)
    m2 <- length(sample2)
    # allocate a vector to save the statistic delta
    statistic <- vector(mode = "numeric", length = nperm)
    for(j in 1:nperm) {
      # 1st stage resampling (performed only if samples sizes are different)
      # larger sample is resized to the size of the smaller
      if(m2 > m1) {
         sample2 <- sort(sample(sample2, m1))
         m <- m1
      } else {
         sample1 <- sort(sample(sample1, m2))
         m <- m2
      }
      # z-values: z1 in column 1 and z2 in column 2.
      z_two_samples <- matrix(c(diff(sample1), diff(sample2)), ncol = 2)
      # 2nd stage resampling
      z <- apply(z_two_samples, 1, sample, 1)
      statistic[j] <- aly_delta_statistic(z)
    }
    return(statistic)
  }
}
</code>
Comment: Take a look at my answer.  I hope it helps.
Answer: Yes I think you can test equality against the possibility that population 1 has a variance larger than population 2 or less than population 2 or if you have no reason to expect the result one way or the other.
In the text it seems that Phil is doing a two-sided test because he talks about as extreme or more extreme value than you get under the null hypothesis.  If it was one-sided he should say as large or larger or on the other side as small or smaller.  As he finds only 2 out of the 16 possible permutations he gets a p-value of 2/16 = 0.125. He then says accept the null hypothesis whereas many of us would prefer to say do not reject.
Regarding the R code I am not an expert in R so I cannot tell you about the accuracy of the code.  If it was taken from the book it is likely correct or there would probably be an errata sheet with a correction.
Whether you use a parametric test for the equality of the variances or non-parametric approaches like bootstrap or permutation tests it is very difficult to reject the null hypothesis with small sample sizes especially 4 samples in each group as Phil did here.  But I think he did it for simplicity to explain the method simply and thoroughly.
Comment: The code is my own. I would like to have this test implemented in R and the code in the OP is my first approach at it. However I am not sure about a few aspects of the test. For instance, the book takes sample 1 as the one to calculate the observed/reference statistic, and uses permutations involving the two samples to find the statistic distribution under the null hypothesis. I am unsure if one needs to pick one of the samples as the reference or not. I would find it strange that there would be such an asymmetry...
Comment: From the book, it seems the test is two-sided... However I remember reading that one can only do a two-sided test if the statistic distribution has two tails. The statistic $\delta$ seems to fall in the range from 0 to Inf, so it ought not to have a left tail... Challenging, I reckon,  the concept of existing a two-sided alternative hypothesis for this test...
Comment: The null hypothesis is equality of variances so it doesn't matter which statistic is first.
Comment: Even if the two samples are not equal in size?
Comment: BTW, did you say that 2/16 is 0.25 by mistake or were you multiplying 0.125 by 2 because of the two-sidedness of the test?
Comment: In the case of unequal sample size the two samples are pooled because under the null hypothesis the distributions are equal.
Comment: They're pooled but prior to pooling the bigger one is resized to the size of the smaller one, right?
Comment: @plant I am very sorry of course 1/8 =0.125 but the null hypothesis would still not be rejected.  I will edit my answer accordingly.
Comment: In principle, I agree with you that the test should be about equality of variances, i.e. it is symmetric and hence it should not matter which sample is chosen as reference. Yet, I cannot reconcile that fact with this passage: _with 2 out of 16 rearrangements yielding values of the statistic **as, or more, extreme than the original**, we should accept the null hypothesis_, as this passage, to me, suggests that the alternative is necessarily one-sided.
Comment: don't you mind up voting my question to draw more attention?
Comment: Extreme can be extremely high or extremely low.  That is why I made the comment large or larger and small or smaller for the two possible one-sided tests.
Comment: Sure I think it is a good enough question.  I will do that.  Not sure that will bring more attention.  The post has not been up very long.
Comment: If you at some point find my answer the best you can use the check mark to accept it.


Array exponentiation

Question: I have a string, for example
a = 'Thank you for your answer'

and I need to  get the length of each word from the string and raising them to a power next word, for this example:
result = ((((5**3)**3)**4)**6)

How do I do that?
Comment: I think your `((((5**3)**3)**4)**5)` is `((((5**3)**3)**4)**6)` instead (the last number is `6`)
Comment: I doubt that anyone will give an answer that improves on @太's, but I would encourage you to wait longer, in future, before awarding the greenie. A quick selection may discourage other, possibly better, possibly just interesting, answers, and imo is a discourtesy to others who may still be preparing their answers. There's no rush, so why not wait awhile? Many here wait at least a couple of hours.
Answer: inject will do:
s = 'Thank you for your answer'

s.split(/\s+/)
# => ["Thank", "you", "for", "your", "answer"]

s.split(/\s+/).map{|w| w.length}
# => [5, 3, 3, 4, 6]

s.split(/\s+/).map{|w| w.length}.inject(:**)
# => 9495567745759798747473242269561957154220965833619944966279779990829008230644811159033118931771413600093027632988162967109246892505325376987457275390625

((((5**3)**3)**4)**6)
# => 9495567745759798747473242269561957154220965833619944966279779990829008230644811159033118931771413600093027632988162967109246892505325376987457275390625

Comment: A couple of small points: 1. `s.split(/\s+/)` is the same as `s.split`. 2. `map { |w| w.length }` can be simplified to `map(&:length)`.

Array exponentiation


Customizing a Views HTML

Question: I'll start off saying I'm pretty new to Drupal.
I'm trying to customize the way a view displays. I want it to look like the Industry News section on this page: http://www.silverfishdevelopment.com/clients/maafs
However I'm confused as to what I want to actually edit. Do I want to create a custom views-view.tpl.php file? Or style output, or row style, etc?
And if I create a new tpl file, what are the variables I can use?
I was trying to follow this: http://www.wdtutorials.com/2011/06/29/drupal-7-how-create-custom-template-view#.VPXOIXXN9cY but couldn't get it to print out the $fields data.
Or am I approaching this all wrong?
If you know of a great tutorial too I'd appreciate that as well.
I'm a little overwhelmed with all of it. Thanks for any help you can give.
Answer: I found that Semantic Views worked best for me in this situation. It cuts down on the amount of HTML outputted by Drupal Views and allows you to define the HTML tag that wraps each field as well as add a CSS class.
Answer: The bulk of your HTML can be controlled via the Manage Fields section of your content type that you are displaying.
To add a bit more flexibility and configuration option to your content type, you can install Display Suite.
After installing DS and DS extras, you can enable "Field Templates" in DS settings.  This will allow you to change the HTML for each of your fields.
This way, views just simply displays your data rather than controlling its appearance.  You would set your view to show "Display Suite" with whatever view mode you choose.  I think this is a better route when new to Drupal.
If you'd rather go the views template route, you can see a couple starting points by going to "Advanced > Theme: Information" in your view settings.  You can also check out This LInk that explains what template names to use.
Comment: Ok, another question then. If I use DS how do I change just the first news article to look different?
Comment: In that case, you would set your views block to show just 1 article (the top one).  Then create an attachment display and attach it to the single article display.  The attachment display would be the one that displays the list of teasers.

Customizing a Views HTML


Interpreting main effects in the presence of an interaction in logistic regression

Question: I am carrying out logistic regression to determine which factors affect whether lasers are effective bird deterrent devices. In my model, a success (1) is when a bird flies away and a failure (0) is when they do not.
I built a model, but I am having some trouble interpreting it.
In my model, I have:

Laser colour (categorical, 2 levels)
Light (continuous)
Light x laser colour

From the beta coefficient for laser colour, I calculated an odds ratio for laser colours and found that colour A is 6x better than colour B. The statement that colour A is more effective than colour B is consistent over all light levels, but the magnitude of this difference changes (as evidenced by the interaction term in the model). I determined (from plotting predicted probabilities) that the lasers are very similar when it is dark (both effective) and bright (both not effective) but differ at intermediate light levels.
My question is:
Does it make any sense to interpret the odds ratio from the laser colour main effect? Can interpret the 6x as the average difference, or the maximum difference, or is it not meaningful at all in the presence of the interaction?
Comment: Definitely not the maximum difference. Conceivably could be the average difference, I believe, depends on how valid the logistic model is here. You have to look at the raw data- don't just plot predicted probabilities, also plot the means. However, you imply there is a U-shaped function (both ineffective at dark and both ineffective at bright, but ok in the middle) which means your model is invalid. You could address that by adding a quadratic term.
Comment: Hi Alex, Thanks for your response. I did look at the proportion of successful responses for light levels in binned increments. These values seem to follow the predicted probability curve quite closely, although I don't believe I tested this statistically. I'm not sure there is a U-shaped function because both lasers work well (are effective) in the dark and neither works well in daylight (are ineffective). The difference between them is greatest at intermediate light levels. Given this information, do you think it makes sense to include light as a linear term?
Answer: Given color A as the reference color, and the the equation/notation below
$$
\frac{p}{1-p} = e^{\beta_0 + \beta_1 color + \beta_2 light + \beta_3 color*light}
$$
$\beta_1$ can be interpreted as the effect when $light=0$, if that is possible for your variable.
If light is always positive or negative, then we can also say something about the maximum or minimum. Lets assume $light>0$ for now.
The odds ratio of color A is $e^{\beta_0 + \beta_2 light}$. If $\beta_2$ is positive, then the minimum odds ratio of the reference color is $e^{\beta_0}$ since light is also positive. And if $\beta_2$ is negative, then $e^{\beta_0}$ is the maximum odds ratio.
The odds ratio of color B is $e^{\beta_0 + \beta_1 + \beta_2 light + \beta_3 light}$. If $\beta_2 + \beta3 >0$, then the minimum odds ratio of the non-reference color is $e^{\beta_0 + \beta_1}$. If $\beta_2 + \beta3 <0$, then it is the maximum odds ratio.
To answer your question directly, lets assume $light>0$. If $\beta_2 + \beta3 >0$, then $100(\beta_1-1)\%$ would be color B's minimum percent change in odds ratio over color A. If $\beta_2 + \beta3 <0$, then it is the maximum.


Intuition or guide on this question regarding subspaces/vector spaces

Question: So I had an exam two days ago and admittedly, I couldn't do this last question very well. I was wondering if someone could give me a guide on how to do this or how to think about it? I'll post what I did in the exam.
Question
Let $V$ be a vector space over a field $\mathbb{F}$ and $U$ a subspace of $V$. For any $\textbf{v}$ in $V$ we define the set
$$\textbf{v} + U = \{\textbf{v} + \textbf{u}|\textbf{u}\in U\}.$$
We write $V/U$ for the set of all of these sets,  $$V/U = \{\textbf{v} + U|\textbf{v} \in V\},$$
and we define addition and scalar multiplication on $V/U$ by
$$(\textbf{v}_1 + U) + \textbf{v}_2 + U) = (\textbf{v}_1 + \textbf{v}_2) + U \quad \text{and} \quad \alpha(\textbf{v}+U) = (\alpha \textbf{v})+U.$$
You may assume these operations are well defined.
i) Find the identity element for addition in $V/U$. Prove that your answer is correct.
ii) Prove that the vector distributive law holds in $V/U$. (That is, the one involving a scalar and two vectors, not two scalars and a vector.)
iii) Let $\textbf{v}_1,\textbf{v}_2$ be in $V$. Show that $\textbf{v}_1 + U = \textbf{v}_2 + U$ if and only if $\textbf{v}_1 - \textbf{v}_2$ is in $U$.
iv) $\textbf{You may now assume}$ that $V/U$ is a vector space over $\mathbb{F}$, with operations defined as above. Prove that if $V$ is finite-dimensional, then $V/U$ is also finite-dimensional and
$$\dim V/U = \dim V - \dim U.$$
My attempts
Firstly, I'm not sure what the "standard" name for these type of subspaces are, as I've never encountered them before, so I was lost on what it even meant to "add" an element to another subspace (referring to $V/U$).
i) I claimed that the identity element is $U$ since for any $\textbf{w} = \textbf{v}_1 + U$ in $V/U$, the additive inverse is $-\textbf{w} = -(\textbf{v}_1 + U) = -\textbf{v}_1 + U$ (by definitions of the addition/scalar multiplication).
$\textbf{w} + (-\textbf{w}) = U +(-1)U = (1-1)U = 0U = U$.
ii) I used the same reasoning (and the definitions to show that $\lambda (\textbf{w}_1 + \textbf{w}_2) = \lambda \textbf{w}_1 + \lambda \textbf{w}_2$.
iii) & iv) I had no clue how to start or think about.
Thinking about it again, I'm confused how $U$ can be an identity element of a set... when $U$ is itself a set (with elements in it)..
Comment: In an algebraic structure like a group, ring, field, vector space, etc., the members can be any objects at all. A vector sub-space U of the vector space V can also be the 0 vector of some other vector space.
Answer: The sets $\mathbf{v} +U$ are not subspaces technically (they are not closed under addition), but the standard name for them is "cosets" (of $U$). Your intuition for $(i)$ and $(ii)$ are correct.
For $(iii)$, suppose first that $\mathbf{v_0} = \mathbf{v}_1 - \mathbf{v}_2 \in U$. Then for any $\mathbf{u} \in U$, we have $\mathbf{v}_2+\mathbf{u} = \mathbf{v}_1 + (\mathbf{u}-\mathbf{v_0})$, which shows that $\mathbf{v}_2 + U \subseteq \mathbf{v}_1 + U$, and also $\mathbf{v}_1 + \mathbf{u} = \mathbf{v}_2 + (\mathbf{u}+\mathbf{v}_0)$, which shows that $\mathbf{v}_1+U \subseteq \mathbf{v}_2+U$. Conversely, suppose that $\mathbf{v}_1+U=\mathbf{v}_2+U$. Take any $\mathbf{u} \in U$. Then $\mathbf{v}_1+\mathbf{u} \in \mathbf{v}_1+U$, and so also by assumption, it is in $\mathbf{v}_2+U$. So there is some other $\mathbf{u}' \in U$ so that $\mathbf{v}_1+\mathbf{u} = \mathbf{v}_2+\mathbf{u}'$. Then $\mathbf{v}_1-\mathbf{v}_2=\mathbf{u}'-\mathbf{u} \in U$.
Part $(iv)$ is a well-known result that is known by the name "Rank-Nullity Theorem". A more abstract version is also known by the name "First Isomorphism Theorem". You should be able to find a proof by just searching on Google.
Answer: These questions are on fundamental properties for quotient spaces, as defined above by $V/U = \{ v + U \mid v \in V \} $.
i) The additive identity of $V/U$ is $0 + U$ or $U$.
ii) I am assuming that you are referring to the distributive property of $a(u + v) = au + av$ for $\forall a,b \in F$ and $\forall u,v \in V$.
This can be simply proven by using the definition of addition and scalar multiplication on $V/U$.
For $v_1, v_2 \in V$ and $\lambda \in F$, $\lambda((v_1 + U) + (v_2 + U)) = \lambda ((v_1 + v_2) + U)$ by definition of addition.
By definition of scalar multiplication, $\lambda ((v_1 + v_2) + U) = \lambda (v_1) + \lambda(v_2) + U = \lambda (v_1) + U + \lambda(v_2) + U$. Thus, the vector distributive law holds in $V/U$.
iii) If $v_1 + U = v_2 + U$, let $u_1, u_2 \in U$ s.t. $v_1 + u_1 = v_2 + u_2$. Then, $v_1 - v_2 = u_2 - u_1 \in U$. Thus, $v_1 - v_2 \in U$.
If $v_1 - v_2 \in U$, for $u \in U$,
$ v_1 + u = v_2 + ((v_1 - v_2) + u) \in v_2 + U$
$v_2 + u = v_1 + ((v_2 - v_1) + u) \in v_1 + U$
Thus, $v_1 + U \subset v_2 + U$ and $v_2 + U \subset v_1 + U$ and $v_1 + U = v_2 + U$.
iv) Indeed, $V/U$ is a vector space over $F$. As $V/U \subset V$, if $V$ is finite-dimensional, $V/U$ is also finite-dimensional (basis for $V$ spans $V/U$). We can prove this by using the quotient map $\pi: V \rightarrow V/U$ which is defined such that $\pi(v) = v + U $ for $v \in V$.
$\textrm{null }\pi = U$ since if $v \in \textrm{null } \pi$, $\pi(v) = v + U = 0 + U$, so $v - 0 \in U$, and $ v \in U$. Thus, $U = \textrm {null } \pi$. $\textrm{range } \pi = V/U$ by definition of $V/U$.
By using the Rank-Nullity theorem, we can note that $\textrm{dim } V = \textrm{dim } U + \textrm{dim } V/U$. Thus, $\textrm{dim } V/U = \textrm{dim } V - \textrm{dim } U$.


Lagrange's Theorem for further elementary consequences

Question: Question: Let $G$ be a finite group, and let $H$ and $K$ be subgroup of $G$. Prove: suppose $H$ and $G$ are not equal, and both have order the same prime number $p$, Then $H\cap K=\{e\}$.
This is my proof steps:
Proof: $G$ is finite, $H, K$ subgroup of $G$. therefore $H\cap K$ subgroup of $G$, also is subgroup of both $H$ and $K$
Then the order of $H\cap K$ is a common divisor of order of $H$ and the order of $K$. since $p$ is prime number. Show that $G$ is cyclic group and that any a belong to $G$ is its generator.  Therefore $H,K, H\cap K$ are cyclic group too, because every subgroup of a cyclic group is cyclic. Since $H$ not equal $G$, Then …..
I just did here, because I feel I miss some part. Can anyone give me some advises! Thanks so much
Comment: It is not true in general, that $G$ is a cylcic group. But you already did all the work: $ord(H\cap K)$ devides $ord(K) = ord(H) = p$ prime. Just answer the following questions to yourself: Can $ord(H \cap K)$ be equal to $p$? What can it equal?
Comment: no! order(H∩K) can not equal p, it should be {e}
Comment: From where is this "*Show that $G$ is cyclic group*" coming in the middle of the proof of something else?
Answer: You can't assume $G$ is cyclic, nor can you prove it, becasue not all finite groups are cyclic.
Your proof is very good up to where you say the order of $H \cap K$ is a common divisor of the orders of both the groups $H$ and $K$.  At this point, note that the only divisors of a prime $p$ are 1 and $p$ itself.  What does this mean about $H \cap K$?  How many elements can it have?
Comment: @megan When $H \cap K$ has order 1, you are correct that $H \cap K$ must be the identity (it can only have one element).  When $H \cap K$ has order $p$, then it has $p$ elements, and also it is a subgroup of $H$ and $K$, and both $H$ and $K$ have $p$ elements. What does this mean?
Comment: H equal K, therefore it is contradiction, because H not equal K
Comment: when their order prime p equal 1 therefore H∩K ={e}, otherwise when their order prime p not equal 1, since H and K not equal each other , H∩K ={e}?


Serial port monitoring application for Windows CE?

Question: I have an application on a Windows CE device that tries to receive data over a serial port. This isn't working and now I'm looking for some simple application to run on that device that'd let me check if there is any data coming in. Is there something like HyperTerminal that let's me monitor a serial port on mobile devices?
Best would probably be an application where the source code is available, so that I can adjust it to the specifics of the device I'd like to run it on (some commonly used system DLLs are not available).
Answer: When I was doing a lot of serial comms based work on windows mobile I found ZTerm for PPC an invaluable tool. It supports a direct serial connection so you can use it to talk to serial ports, modems etc. And also supports socket based comms so you can use it as telnet to talk to remote systems.
Answer: In Windows CE you communicate with a serial port almost the same way as you do in classic Win32. The only difference is that overlapped I/O is not supported.
So I guess it would be easy to adapt an existing C++ library to your needs. There are many articles available in Code Project. This is one example article.
Answer: Try to check this out. If I'm not mistaken I used this to check COM ports functionality (I was too lazy to download it all again and check whether this is exactly the version I used...). It is a basic application that sends and receives data over a chosen COM port. Basic, but you can expand the functionality.


How to interpret bracket, curly bracket, and the asterisk in Probability formula?

Question: At the bottom of page #3 of this paper, it steates:

$m_{jt}=\exp\{X_tB_j\}$
$X_t=[X_{1t} | X_{2j}] $
$X_{1t}=[1, x_{Djt} | X_t^*]$

May I know how should I interpret the bracket, curly bracket, and the asterisk?
Thanks in advance.
Answer: The curly brackets are like ordinary brackets - they are just meant as parantheses to single out the argument of the exponential.
The asterisk is defined on the top of the next page of the article.
I am not sure what the brackets and the pipe signify - it could be an inner product, maybe the covariance of the two random variables. Or it could be a conditioning of sorts. Maybe it will be clearer later in the article.
Answer: I agree with the previous answer. However, it should be emphasized that the notations at stake are not at all specific to probability theory.


Exibir menor, média e maior até uma linha vazia ser digitada

Question: Tenho o seguinte código:
qtdNumeros = int(input())
if qtdNumeros <= 0:
    menor = "Nenhum"
    media = "Nenhuma"
    maior = "Nenhum"
else:
    menor = maior = soma = float(input())
    for proximo in range(1, qtdNumeros):
        valor = float(input())
        soma += valor
        if valor < menor:
            menor = valor
        elif valor > maior:
            maior = valor
    media = soma / qtdNumeros
print("Menor Lido:", menor)
print("Média dos Lidos:", media)
print("Maior Lido:", maior)

Gostaria de implementar o seguinte:
Ao invés de eu passar uma quantidade de entrada, eu inserir entrada até que uma linha vazia seja digitada e ai ele processar e exibir o menor, a media e o maior e, ao invés de digitar um número negativo, digitar somente uma linha vazia.
Poderiam me ajudar? Como iniciante não estou conseguindo :(
Answer: Python já possui funções prontas para identificar o menor e o maior valor de uma lista, bem como calcular a média da mesma.

Para identificar o menor valor: min
Para identificar o maior valor: max
Para calcular a média: statistics.mean

Assim, basta criarmos um laço de repetição infinito, pois não sabemos quantos números serão informados e interrompemos o laço quando uma linha vazia for recebida.
from statistics import mean

numbers = []

while True:
    number = input()

    if number == '':
        break

    numbers.append(float(number))

print('O menor valor informado foi', min(numbers))
print('O maior valor informado foi', max(numbers))
print('A média dos valores foi', mean(numbers))

Com Python 3.8, utilizando o walrus operator (por vezes citado em português como operador morsa - porque aparentemente o := lembra as presas de uma morsa) , você pode fazer o laço de repetição como segue:
from statistics import mean

numbers = []

while (number := input()) != '':
    numbers.append(float(number))

print('O menor valor informado foi', min(numbers))
print('O maior valor informado foi', max(numbers))
print('A média dos valores foi', mean(numbers))

O que são Assignment Expressions do Python 3.8?

E, caso não puder utilizar as funções min, max e mean para resolver o problema, basta você iterar sobre a sua lista e aplicar as condições necessárias.

Para identificar o menor valor, comece assumindo que o primeiro valor da lista é o menor valor, percorra a lista inteira e para cada valor compare com o menor valor atual; se for menor, atualize o valor deste;
Para identificar o maior valor, comece assumindo que o primeiro valor da lista é o maior valor, percorra a lista inteira e para cada valor compare com o maior valor atual; se for maior, atualize o valor deste;
Para calcular a média, como esperado, basta calcular a soma de todos os valores e dividir pela quantidade;
Answer: Fiz algumas alterações no código e coloquei alguns blocos try/except porque no código da pergunta não existia validação e quando se passava um valor diferente do esperado o código dava erro. No entanto, no segundo try/except, coloquei um if para não exibir a mensagem em caso de saída da execução.
Coloquei um primeiro while para só aceitar o primeiro valor quando fosse realmente válido.
Depois removi o for que existia e o troquei por um while verificando se o valor de entrada era igual a uma string vazia, assim não seria necessário colocar um número fixo de valores e o laço terminaria ao receber um valor vazio e dava o resultado final, foi removido também o if inicial porque não havia a necessidade dele existir.
O novo código ficou assim:
menor = "Nenhum"
media = "Nenhuma"
maior = "Nenhum"
qtdNumeros = 0
valor_valido = False
while valor_valido == False:
    try:
        entrada = input()
        menor = media = maior = soma = float(entrada)
        qtdNumeros = qtdNumeros + 1
        valor_valido = True
    except:
        print("Insira um valor valido!")
while entrada != '':
    entrada = input()
    try:
        valor = float(entrada)
        qtdNumeros = qtdNumeros + 1
        soma += valor
        if valor < menor:
            menor = valor
        elif valor > maior:
            maior = valor
        media = soma / qtdNumeros
    except:
        if entrada != '':
            print("Insira um valor valido!!")
print("Menor Lido:", menor)
print("Média dos Lidos:", media)
print("Maior Lido:", maior)


Docker logstash not register defined log to elasticsearch

Question: I'm new in ELK. I want to up a server with docker compose base on this tutorial. My spring boot microservice write in a log-file at host ./logstash/logs, So I map it to logstash container as follows:
logstash:
   ...
   volumes:
     ...
     - ./logstash/logs:/usr/share/logstash/logs:ro,Z

And I changed logstash.conf as follows:
input {
    file {
        type => "log"
        path => "/usr/share/logstash/logs/my-service.log"
    }
}
## Add your filters / logstash plugins configuration here

output {
    elasticsearch {
        hosts => "elasticsearch:9200"
        index => "firs-log"
        user => "logstash_internal"
        password => "${LOGSTASH_INTERNAL_PASSWORD}"
    }
}

When I run the containers, No index created in elasticsearch:

My logstash logs is as follows:
> 2024-02-24 14:36:45
> /usr/share/logstash/vendor/bundle/jruby/3.1.0/gems/concurrent-ruby-1.1.9/lib/concurrent-ruby/concurrent/executor/java_thread_pool_executor.rb:13:
> warning: method redefined; discarding old to_int 2024-02-24 14:36:45
> /usr/share/logstash/vendor/bundle/jruby/3.1.0/gems/concurrent-ruby-1.1.9/lib/concurrent-ruby/concurrent/executor/java_thread_pool_executor.rb:13:
> warning: method redefined; discarding old to_f 2024-02-24 14:36:39
> Using bundled JDK: /usr/share/logstash/jdk 2024-02-24 14:36:47 Sending
> Logstash logs to /usr/share/logstash/logs which is now configured via
> log4j2.properties 2024-02-24 14:36:48 [2024-02-24T11:06:48,011][INFO
> ][logstash.runner          ] Log4j configuration path used is:
> /usr/share/logstash/config/log4j2.properties 2024-02-24 14:36:48
> [2024-02-24T11:06:48,014][INFO ][logstash.runner          ] Starting
> Logstash {"logstash.version"=>"8.12.1", "jruby.version"=>"jruby
> 126.96.36.199 (3.1.4) 2023-11-02 1abae2700f OpenJDK 64-Bit Server VM 17.0.10+7 on 17.0.10+7 +indy +jit [x86_64-linux]"} 2024-02-24 14:36:48 [2024-02-24T11:06:48,016][INFO ][logstash.runner          ] JVM
> bootstrap flags: [-Xms1g, -Xmx1g, -Djava.awt.headless=true,
> -Dfile.encoding=UTF-8, -Djruby.compile.invokedynamic=true, -XX:+HeapDumpOnOutOfMemoryError, -Djava.security.egd=file:/dev/urandom, -Dlog4j2.isThreadContextMapInheritable=true, -Dlogstash.jackson.stream-read-constraints.max-string-length=200000000,
> -Dlogstash.jackson.stream-read-constraints.max-number-length=10000, -Dls.cgroup.cpuacct.path.override=/, -Dls.cgroup.cpu.path.override=/, -Xms256m, -Xmx256m, -Djruby.regexp.interruptible=true, -Djdk.io.File.enableADS=true, --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED, --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED, --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED, --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED, --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED, --add-opens=java.base/java.security=ALL-UNNAMED, --add-opens=java.base/java.io=ALL-UNNAMED, --add-opens=java.base/java.nio.channels=ALL-UNNAMED, --add-opens=java.base/sun.nio.ch=ALL-UNNAMED, --add-opens=java.management/sun.management=ALL-UNNAMED] 2024-02-24 14:36:48 [2024-02-24T11:06:48,017][INFO ][logstash.runner          ]
> Jackson default value override
> `logstash.jackson.stream-read-constraints.max-string-length`
> configured to `200000000` 2024-02-24 14:36:48
> [2024-02-24T11:06:48,018][INFO ][logstash.runner          ] Jackson
> default value override
> `logstash.jackson.stream-read-constraints.max-number-length`
> configured to `10000` 2024-02-24 14:36:48
> [2024-02-24T11:06:48,024][INFO ][logstash.settings        ] Creating
> directory {:setting=>"path.queue",
> :path=>"/usr/share/logstash/data/queue"} 2024-02-24 14:36:48
> [2024-02-24T11:06:48,026][INFO ][logstash.settings        ] Creating
> directory {:setting=>"path.dead_letter_queue",
> :path=>"/usr/share/logstash/data/dead_letter_queue"} 2024-02-24
> 14:36:48 [2024-02-24T11:06:48,126][INFO ][logstash.agent           ]
> No persistent UUID file found. Generating new UUID
> {:uuid=>"8a4c26a8-9959-48ea-abf5-cba7f4e0e008",
> :path=>"/usr/share/logstash/data/uuid"} 2024-02-24 14:36:48
> [2024-02-24T11:06:48,454][INFO ][logstash.agent           ]
> Successfully started Logstash API endpoint {:port=>9600,
> :ssl_enabled=>false} 2024-02-24 14:36:48
> [2024-02-24T11:06:48,700][INFO ][org.reflections.Reflections]
> Reflections took 70 ms to scan 1 urls, producing 132 keys and 468
> values 2024-02-24 14:36:48 [2024-02-24T11:06:48,864][INFO
> ][logstash.javapipeline    ] Pipeline `main` is configured with
> `pipeline.ecs_compatibility: v8` setting. All plugins in this pipeline
> will default to `ecs_compatibility => v8` unless explicitly configured
> otherwise. 2024-02-24 14:36:48 [2024-02-24T11:06:48,875][INFO
> ][logstash.outputs.elasticsearch][main] New Elasticsearch output
> {:class=>"LogStash::Outputs::ElasticSearch",
> :hosts=>["//elasticsearch:9200"]} 2024-02-24 14:36:48
> [2024-02-24T11:06:48,955][INFO ][logstash.outputs.elasticsearch][main]
> Elasticsearch pool URLs updated {:changes=>{:removed=>[],
> :added=>[http://logstash_internal:xxxxxx@elasticsearch:9200/]}}
> 2024-02-24 14:36:49 [2024-02-24T11:06:49,088][WARN
> ][logstash.outputs.elasticsearch][main] Restored connection to ES
> instance {:url=>"http://logstash_internal:xxxxxx@elasticsearch:9200/"}
> 2024-02-24 14:36:49 [2024-02-24T11:06:49,089][INFO
> ][logstash.outputs.elasticsearch][main] Elasticsearch version
> determined (8.12.1) {:es_version=>8} 2024-02-24 14:36:49
> [2024-02-24T11:06:49,089][WARN ][logstash.outputs.elasticsearch][main]
> Detected a 6.x and above cluster: the `type` event field won't be used
> to determine the document _type {:es_version=>8} 2024-02-24 14:36:49
> [2024-02-24T11:06:49,101][INFO ][logstash.outputs.elasticsearch][main]
> Not eligible for data streams because config contains one or more
> settings that are not compatible with data streams:
> {"index"=>"firs-log"} 2024-02-24 14:36:49
> [2024-02-24T11:06:49,101][INFO ][logstash.outputs.elasticsearch][main]
> Data streams auto configuration (`data_stream => auto` or unset)
> resolved to `false` 2024-02-24 14:36:49 [2024-02-24T11:06:49,109][INFO
> ][logstash.outputs.elasticsearch][main] Using a default mapping
> template {:es_version=>8, :ecs_compatibility=>:v8} 2024-02-24 14:36:49
> [2024-02-24T11:06:49,112][INFO ][logstash.javapipeline    ][main]
> Starting pipeline {:pipeline_id=>"main", "pipeline.workers"=>16,
> "pipeline.batch.size"=>125, "pipeline.batch.delay"=>50,
> "pipeline.max_inflight"=>2000,
> "pipeline.sources"=>["/usr/share/logstash/pipeline/logstash.conf"],
> :thread=>"#<Thread:0x77c98da8
> /usr/share/logstash/logstash-core/lib/logstash/java_pipeline.rb:134
> run>"} 2024-02-24 14:36:49 [2024-02-24T11:06:49,151][INFO
> ][logstash.outputs.elasticsearch][main] Installing Elasticsearch
> template {:name=>"ecs-logstash"} 2024-02-24 14:36:49
> [2024-02-24T11:06:49,672][INFO ][logstash.javapipeline    ][main]
> Pipeline Java execution initialization time {"seconds"=>0.56}
> 2024-02-24 14:36:49 [2024-02-24T11:06:49,681][INFO
> ][logstash.inputs.file     ][main] No sincedb_path set, generating one
> based on the "path" setting
> {:sincedb_path=>"/usr/share/logstash/data/plugins/inputs/file/.sincedb_9391fb0a817f4b225df7fa90e990b01b",
> :path=>["/usr/share/logstash/logs/my-service.log"]} 2024-02-24
> 14:36:49 [2024-02-24T11:06:49,683][INFO ][logstash.javapipeline
> ][main] Pipeline started {"pipeline.id"=>"main"} 2024-02-24 14:36:49
> [2024-02-24T11:06:49,688][INFO ][filewatch.observingtail
> ][main][cbe1433791fc583a55e100262676d95761e4d64e46aab200140ca5435ba5c2c8]
> START, creating Discoverer, Watch with file and sincedb collections
> 2024-02-24 14:36:49 [2024-02-24T11:06:49,696][INFO ][logstash.agent
> ] Pipelines running {:count=>1, :running_pipelines=>[:main],
> :non_running_pipelines=>[]}

Where is the problem? Why my-service.log not register by logstash?
I want to register my-service.log by logstash in elasticsearch.
Answer: The roles of your "logstash_internal" may cause the problem. I suggest you kindly checking the roles & users in Kibana. Stack Management-> Kibana->User or Roles.
Typically there are built-in users but if you use a custom user, you should assign the roles to the user to enable Logstash to read log files.


Como converter uma string para um número em Lua?

Question: Em Lua, como converter um valor do tipo string para o tipo número (inteiro, float etc.)?
Answer: O Lua realiza uma conversão automática entre os tipos string e number e vice-versa em tempo de execução.
> print(1+"20")
21
> print(1 .. "2")
12

Caso você queira converter explicitamente um number para uma string, utilize a função tonumber.
> local a = tonumber("999")
999

> local phi = tonumber("1.61803")
1.61803

> print(tonumber("100e20"))
1e+22

Além disso, é tonumber aceita uma base, que pode variar entre 2 e 36, como segundo argumento.
> print(tonumber("A",16))
10

> print(tonumber("101010",2))
42

Comment: O último exemplo não funciona em Lua 5.3. Funcionava por acaso nas versões anteriores. `tonumber("101010",2)` funciona em todas as versões. Quer dizer, se vai dar uma base, use um string.
Comment: @lhf corrigido!


How can I add a wrapper around my nodes?

Question: How can I wrap my nodes (output in teaser view) in a
 element?

My title

  //
 <--- add this

...

...

...

    ...
  //
 <--- add this

Answer: Copy the corresponding twig template of your view into your module/theme and name it properly after the view's display, fe. views--{type, fe. unformatted}--my-view-id--my-block.html.twig.
Comment: Or even just add a class on the View in the config.


Wiremock stubbing error: "Unrecognized field \"timestamp\" (class com.github.tomakehurst.wiremock.common.Errors), not marked as ignorable"

Question: here I come because I have not found any solution to my problem. I'm actually trying to stub a response with wiremock (that call to the Mocked service is be done via FeignClient). My intention is to get a fake response with the real feign client, not in a test, but in the real application. Therefore, In this case, I'm not stubbing the WireMockServer in a test, but in the spring boot application class, however when stubbing there the response I'm having a super weird error that I have investigated a lot so far without success.
Here is the code I'm using so far:
@EnableFeignClients
@SpringBootApplication
public class CrmApplication
      implements CommandLineRunner
{
    private final ConfigurableApplicationContext context;private final ConfigurableApplicationContext context;

    @Autowired
    public CrmApplication( ConfigurableApplicationContext context )
    {
        this.context = context;
    }

    public static void main( String[] args )
    {
        log.info( "Starting the CRM Validator" );
        SpringApplication.run( CrmApplication.class, args );
        log.info( "Finishing the CRM Validator" );
    }

    @Override
    public void run( String... args )
    {
        final WireMockServer server = new WireMockServer( options().port( 8000 ) );
        server.start();
        log.info( "Wiremock has started in the following url: {}", "http://localhost:8000\n\n" );

        String resultJson = "{\"id\":1,\"hasJudicialRecords\":false}";

        MappingBuilder mappingBuilder = get( urlPathEqualTo( "/api/v1/judicial-registry/1") )
              .willReturn( aResponse().withStatus( 200 )
                                      .withHeader( "Content-Type", "application/json" )
                                      .withBody( resultJson ) )
        stubFor( mappingBuilder );

    }
}

This is actually failing in the stubFor( mappingBuilder ); line, and this is the exception I got:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:822) ~[spring-boot-2.4.5.jar:2.4.5]
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:803) ~[spring-boot-2.4.5.jar:2.4.5]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:346) ~[spring-boot-2.4.5.jar:2.4.5]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1340) ~[spring-boot-2.4.5.jar:2.4.5]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1329) ~[spring-boot-2.4.5.jar:2.4.5]
    at com.crm.demo.CrmApplication.main(CrmApplication.java:31) ~[main/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.4.5.jar:2.4.5]
Caused by: com.github.tomakehurst.wiremock.common.JsonException: {
  "errors" : [ {
    "code" : 10,
    "source" : {
      "pointer" : "/timestamp"
    },
    "title" : "Error parsing JSON",
    "detail" : "Unrecognized field \"timestamp\" (class com.github.tomakehurst.wiremock.common.Errors), not marked as ignorable"
  } ]
}
    at com.github.tomakehurst.wiremock.common.JsonException.fromJackson(JsonException.java:53) ~[wiremock-jre8-2.28.0.jar:na]
    at com.github.tomakehurst.wiremock.common.Json.read(Json.java:55) ~[wiremock-jre8-2.28.0.jar:na]
    at com.github.tomakehurst.wiremock.client.HttpAdminClient.safelyExecuteRequest(HttpAdminClient.java:486) ~[wiremock-jre8-2.28.0.jar:na]
    at com.github.tomakehurst.wiremock.client.HttpAdminClient.executeRequest(HttpAdminClient.java:454) ~[wiremock-jre8-2.28.0.jar:na]
    at com.github.tomakehurst.wiremock.client.HttpAdminClient.addStubMapping(HttpAdminClient.java:131) ~[wiremock-jre8-2.28.0.jar:na]
    at com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:298) ~[wiremock-jre8-2.28.0.jar:na]
    at com.github.tomakehurst.wiremock.client.WireMock.register(WireMock.java:293) ~[wiremock-jre8-2.28.0.jar:na]
    at com.github.tomakehurst.wiremock.client.WireMock.givenThat(WireMock.java:104) ~[wiremock-jre8-2.28.0.jar:na]
    at com.github.tomakehurst.wiremock.client.WireMock.stubFor(WireMock.java:108) ~[wiremock-jre8-2.28.0.jar:na]
    at com.crm.demo.CrmApplication.run(CrmApplication.java:31) ~[main/:na]
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:819) ~[spring-boot-2.4.5.jar:2.4.5]
    ... 10 common frames omitted

So one question would be, does wiremock only work in testing?
I have tried changing the JSON, and its fields but that does not seem to work, so if any of you know whow to solve that issue would be helpful, or if you also know how to stub an api request  that is called by @FeignClient (not in a test but in the real spring application run) as an alternative maybe could work too.
Thank you!.
Comment: This is very strange behaviour. There's no reason it shouldn't be possible to run WireMock alongside your production Spring app - I've seen it done quite a few times before. One hypotheses is that another dependency is changing the Jackson configuration somehow at the global scope. If this is the case, switching to the standalone JAR might stop it happening (since Jackson is shaded in that one).
Answer: Right after server.start() you need:
configureFor("localhost", server.port());

Comment: Or just `configureFor(server.port());`


PHP Autoload function load from different directories

Question: I have a MVC that is structored like this
<code>Modules
-Mod1
  -controller
  -Model
  -View
-Mod2
 -controller
 -Model
 -View
</code>
and than I have an autoload function that I need it to load all the files in the directory Model, regardless of what Module it is
<code>// Autoload all models files in all Modules.
function models_autoload($class)
{   $classFile = str_replace(' ', DIRECTORY_SEPARATOR, ucwords(str_replace('_', ' ',  strtolower($class) )));
    $classFile.='.php';
    $files=LUCID_MODULES.'./model/'.$classFile;
    if(file_exists($files)==FALSE)
    {
        return FALSE;
    }
    include ($files);
}

spl_autoload_register('models_autoload');
</code>
my question is, how do I specify in my auto load function above to look recursively in all the Modules for a Model Directory and include all files in  models directories.
Comment: So you want to load model classes from outside of the particular mod being called?  Doesn't sound like you have separated your logic very well, or you need to create library of classes common to all mods.
Comment: No, not from outside. thank you
Answer: Integrate this function:
http://php.net/manual/en/function.glob.php
It will end up giving you a list of all models in all Module directories that you can just iterate through.
Are they all the same namespace? (Assuming you're using namespaces)


Prove that there will be atleast one even number in the sum of odd numbered digit and its reverse,if the number is of the form 4n+1.

Question: Prove that there will be at least one even number in the sum of odd numbered digit and its reverse,if the number of digits is of the form $4n+1$.
If the number of digits is of the form $4n+3$ ,there exist number whose sum of the number and its reverse contains all odd numbers.
Comment: 33 is a countert example
Comment: odd numbered digits
Comment: I just found $7$-digits such numbers like $3241968+8691423=11933391$ they are exactly $50000$. Actually I expected an even number, but not so "nice" :) The $3$-digits are $100$
Comment: "The 3-digits are 100." 100+001=101.zero is an even number.
Answer: $$\sum_{i=0}^{n-1}{10^i(d_i+d_{n-i-1})} = \sum_{i=0}^{m-1}{10^i(2x_i+1)}$$
$$d_i \in\left\{0, 1, 2, 3, 4, 5, 6, 7, 8, 9\right\}$$
$$x_i \in\left\{0, 1, 2, 3, 4\right\}$$
$$m \in\left\{n, n+1\right\}$$
Let $m=n+b, b\in\left\{0, 1\right\}$
$$\sum_{i=0}^{n-1}{10^i(d_i+d_{n-i-1})} = \sum_{i=0}^{n+b-1}{10^i(2x_i+1)}$$
$$\sum_{i=0}^{n-1}{10^i(d_i+d_{n-i-1}-2x_i-1)} = \begin{cases}0 & b=0\\10^n(2x_n+1) & b = 1\end{cases}$$
$$\sum_{i=0}^{n-1}{10^i(d_i+d_{n-i-1}-2x_i-1)} = 10^n(2x_n+1)b$$
Because the carry of the sum of two numbers is always 1 or 0,
$$\sum_{i=0}^{n-1}{10^i(d_i+d_{n-i-1}-2x_i-1)} = 10^nb$$
Let $y_i=d_i+d_{n-i-1}-2x_i-1$
$$\sum_{i=0}^{n-1}{10^iy_i} = 10^nb$$
By the fact that $2x_i+1$ is the sum of $d_i+d_{n-i-1} \bmod 10$
$$2x_i+1 = d_i+d_{n-i-1}+p_i \bmod 10 = d_i+d_{n-i-1}+p_i-10q_i$$
$$p_i, q_i\in\left\{0, 1\right\}$$
$$y_i = 10q_i-p_i \in\left\{-1, 0, 9, 10\right\}$$
$n$ is odd, so let $n=2k+1$
$$y_i = d_i+d_{2k-i}-2x_i-1$$
For $i=k$
$$y_k = 2(d_k-x_k)-1 \in \left\{-1, 9\right\}$$
For $i=k+t, -k \leq t \leq k$
$$y_{k+t} = d_{k+t}+d_{k-t}-2x_{k+t}-1$$
$$y_{k+t}-y_{k-t} = 2(x_{k+t}-x_{k-t})$$
Consider the range of $x_i$
$$-8 \leq y_{k+t}-y_{k-t} \leq 8$$
Consider all possible values of $y_i$
$$y_{k+t} = y_{k-t}$$
All $10^i$ terms must be canceled out, except for $i=n$, so we have following rules.

If $y_i\in\left\{-1,9\right\}$, then $y_{i-1}\in\left\{9, 10\right\}$ and $\exists j<i$ such that $y_j=10$
If $y_{i}\in\left\{9, 10\right\}$, then $y_{i+1}\in\left\{-1, 9\right\}$ or $i=n-1$

Now replace $i$ by $k+t$ and $k-t$, and assume $t\geq 0$.

If $y_{k+t}=y_{k-t}\in\left\{-1,9\right\}$, then
$$y_{k+t-1}=y_{k-t+1}\in\left\{9, 10\right\}$$
$$y_{k-t-1}=y_{k+t+1}\in\left\{9, 10\right\}$$
and $\exists j<k-t$ such that $y_j=10$
If $y_{k+t}=y_{k-t}\in\left\{9, 10\right\}$, then
$$y_{k-t-1}\in\left\{-1, 9\right\}$$
$$y_{k-t+1}=y_{k+t-1}\in\left\{-1, 9\right\}$$
$y_{k+t+1}\in\left\{-1, 9\right\}$ or $t=k$

If $y_{k+t}=9$ for some $t$, because $y_{2k}=y_0\in\left\{0, 10\right\}$ would never be 9, it is sure that $t\neq k$, then
$$y_{k+t-1}=y_{k-t+1}=y_{k+t+1}=y_{k-t-1}=9$$
This will make $y_{i}=9$ for all $i$, which violates $\exists j<k-t$ such that $y_j=10$.
So no $y_i$ could be 9. We can simply the rules.

$y_i\in\left\{-1, 0, 10\right\}$
If $y_{k+t}=y_{k-t}=-1$, then
$$y_{k+t-1}=y_{k-t+1}=10$$
$$y_{k-t-1}=y_{k+t+1}=10$$
If $y_{k+t}=y_{k-t}=10$, then
$$y_{k-t-1}=-1$$
$$y_{k-t+1}=y_{k+t-1}=-1$$
$y_{k+t+1}=-1$ or $t=k$

We already know that $y_k=-1$, so
If $t$ is odd, then
$$y_{k+t}=10$$
If $t$ is even, then
$$y_{k+t}=-1$$
We know that $y_0 = 10$, because no term will cancel it if $y_0 = -1$, so k is odd.
Let $k = 2v+1$
$$n=2k+1=4v+3$$
Comment: really great answer ! Sadly, this post is downvoted,so i cant expect any more answers.


Find x-axis value given a tail probability of an custom PDF estimated using approxfun(density()) in r

Question: I know qnorm() function returns the z-statistic of the applicable normal distribution that corresponds to a given probability (see example below).
qnorm(p = 0.75, mean = 0, sd = 1, lower.tail = T)

What I am looking for is a way to do the same but for a custom distribution that I have estimated using the density() function in base R. The probability density function of my custom distribution has been approximated using approxfun(). See below example. I am interested in a way to get the x-axis value corresponding to some lower tail (alternatively upper tail) probability of my choice. In the figure below I have added a red line at x= 1 to illustrate what i mean: assume that P(X<x=1) = 0.75 in the figure below - Is there a way for me to find out that x = 1 is the value on X that yields P(X<x) = 0.75?
set.seed(0)
x <- rnorm(n = 100, mean = 0, sd = 1) # Generate a reproducible RV
f <- approxfun( density(x) )          # This is my approximated PDF

plot(f, -4, 3)
abline(v = 1, col = "red", lw = 2)

Comment: A kernel density estimate is a [mixture](https://stats.stackexchange.com/questions/321542).  The percentage point function of a mixture can be (and usually must be) [found numerically](https://stats.stackexchange.com/a/411671/919).
Comment: I don't have enough reputation to comment, but see [here](https://stats.stackexchange.com/questions/108342/how-to-get-percentiles-from-empirical-density-in-r). However, in most cases you could simply use the quantiles of the sample that you used to estimate the density.
Answer: This is a pretty trivial problem but I still want to share my solution if anyone has the same problem in the future (evaluate an integral at an unknown upperbound given the value of the integral).
I found a good solution here that is much better (i.e. faster and more compact) than the my original solution.
My original (tedious and slow) solution:
    density_at_upperbound <- function(data,
                              lowtailprob,
                              step = 10^(-4),
                              tol = 10^(-5)){

  PDF          <- approxfun(density(data, kernel = "gaussian")) # An approx. of the estimated PDF
  lowlim       <- min(data)                                     # Integrate from here...
  uplim        <- lowlim                                        # ...to here
  integral     <- 0                                             # Initialize this variable
  h            <- 2*step # needs to be so

  while( abs((lowtailprob) - integral) > tol) { # re-iterate as long as absolute diff between the
                                                # low tail probability and P(<uplim) is too high
    h            <- h/2 # Neccesary correction
    while((lowtailprob) - integral > 0){
      uplim      <- uplim + h
      integral   <- as.numeric(integrate(PDF, lowlim, uplim)[1]) #Parse only the numerical estimation of the integral at place [1]
    }
    uplim <- uplim - h # Neccesary correction
    if(h == 0){break}
  }
  return(list(c("Estimated density at upperbound: ", PDF(uplim)),
              c("Estimated upperbound: ", uplim)))
}

The solution using the link:
Dens <- function(data, lowtailprob){
     f   <- approxfun(density(data))
     int <- function(upper){integrate(f, min(data), upper)$value - lowtailprob}
     f(uniroot(int, c(min(data), max(data)))$root)
   }


error: too few arguments to function `void alpha(std::string*, student)'

Question: Okay, I would like to explain what I am trying to do prior to the code with the issue. I am creating a student record system. I am trying to pull information from a text file into the record system. I am trying to store the information using arrays on a heap.
I am mostly concerned with the first few errors as I feel that those lead to the following ones. Any help would be greatly appreciated as I have looked through many forums and they have not lead me in the correct direction. Thanks in advance!
Code:
#include "address.h"
#include "student.h"
#include "date.h"
#include "record.h"
#include "name.h"

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

#define pArray
#define students
#define Request

using namespace :: std;

enum {sNUMBER=50};

//Function Prototypes
void tPrint(string*,student pArray);
void sPrint(string*,student pArray);
void alpha(string*,student pArray);
int generate();
//Function Definitions
void tPrint(string*,student pArray, alpha)
{
    if (alpha != 0)
    {
        alpha(pArray);
    }//end if
    int i;
    for (i=0; i<sNUMBER;i++)
    {
        pArray->tPrint();
        pArray+=1;
    }//end for
};//end tPrint
void sPrint(string*,student pArray)
{
    if (alpha != 0)
    {
        alpha(pArray);
    }//ennd if
    int i;
    for (i=0; i<sNUMBER;i++)
    {
        pArray->sPrint();
        pArray+=1;
    }//end for
};//end sPrint
void alpha(string*,student pArray)
{
    int i;//counter
    int j;//counter
    for (i=0;i<sNUMBER-1;i++)
    {
        for (j=0;j<sNUMBER-1-i;j++)
        {
            //combine first and last names into full names
            if (strcmp((pArray->GetsName().GetfName())+=" " +=(pArray->GetsName().GetlName()),((pArray+1)->GetsName().GetfName())+=" "+=((pArray+1)->GetsName().GetlName()))>0)
            {
                swap(pArray[j],pArray[j+1]);
            }
        }//end for
    }//end for
};//end alpha

int generate ()
{
    srand(sNUMBER);
    ofstream data;
    data.open ("data.txt");
    if (data.is_open())
    {
        int i; // counter
        int j; // counter

        //Name info
        string new fName[sNUMBER];
        string new lName[sNUMBER];
        //Address info
        string new add1[sNUMBER];
        string new add2[sNUMBER];

        //variables to generate names
        string new fName1[5] = {"Alfred","Robert","Ryan","Hank","Richard"};
        string new fName2[5] = {"Hannah","Lacie","Crystal","Kayce","Susan"};
        string new lName1[5] = {"Smith","Jones","Allison","Johnson","Moore"};
        string new lName2[5] = {"Howard","Williams","Pinkston","Cooley","Vernon"};
        string new fNames[2] = {fName1,fName2};
        string new lNames[2] = {lName1,lName2};

        // variables to generate addresses
        string new adds1[5] = {"159 faternity st.","399 Dorm Blvd.","222 faternity st.", "777 Dorm Blvd", "82 Canal street"};
        string new adds2[10] = {"Apartment A", "Apartment B", "Apartment C", "Apartment D", "Apartment E","Apartment F", "Apartment G", "Apartment H", "Apartment I"};

        for (i=0;i<sNUMBER;i++)
        {
            for (j=0; j<5; j++)
            {
                strCopy(fName[i],fNames[i>25][j]);
                strCopy(lName[i],lNames[i>25][j + floor(i/5)-(i>25)*(floor(i/5)-6)- 4*((j+i/5)>5)]);

            }
        }

        for (i=0;i<sNUMBER;i++)
        {
            for (j=0; j<10; j++)
            {
                strCopy(add1[i],adds1[j]);
                strCopy(add2[i],adds2[j + floor(i/10)-(i>25)*(floor(i/10)-11)- 4*((j+i/10)>10)]);

            }
        }

        //deallocate unneeded variables
        delete [] fName1;
        delete [] fName2;
        delete [] lName1;
        delete [] lName2;
        delete [] fNames;
        delete [] lNames;

        for (i=0; i<sNUMBER;i++)
        {
            // name info
            Data << fName[i] << "\n"; // first name
            Data << lName[i] << "\n"; // last name
            // address info
            Data << add1[i] <" \n"; // add 1
            Data << add2[i] <" \n"; // add 2
            Data << "Indianapolis  \n"; // city
            Data << "IN  \n"; // state
            Data << "46168 \n"; // zip
            // birthdate
            Data << rand()%28 + 1  << " \n"; //day

            Data << rand()%12 + 1 << " \n";//month
            Data << 2011 -(rand()%49 + 12)<< "\n";//year
            //graddate
            Data << rand()%28 + 1 << " \n";//day

            Data << rand()%12 + 1 << " \n"; // month
            Data << 2011 + (rand()%6+2)<< " \n"; // year
            //performance info
            Data << (rand()%16)/(float rand()%4)<<" \n"; //gpa
            Data << (rand()%300)<< " \n"; //credits

        }

        //Deallocate rest of memory
        delete [] fName;
        delete [] lName;
        delete [] add1;
        delete [] add2;

        data.close();
    }
    else
    {
        cout << "Your file did not open. Sorry \n";
    }
    return 0;
}//end generate}

Here are the errors:
C:\Users\main.cpp||In function 'void tPrint(std::string*, student)':|
C:\Users\main.cpp|25|error: too few arguments to function 'void alpha(std::string*, student)'|
C:\Users\main.cpp|32|error: at this point in file|
C:\Users\main.cpp|37|error: expected primary-expression before '->' token|

Comment: Please take the time to format the code in your question appropriately (using the "{}" editor control).
Comment: I'm not sure what happened. I will try it again.
Comment: Next, read the errors.  The reason you're getting "too few arguments to function ... alpha" is because you declare and later define it with two arguments and call it with one.  If correcting these leads to further problems, come back and ask us about those.
Comment: Edit has been re-done. Sorry about that.
Comment: The "{}" control refers to the control bar over the text bar.  It's after a large open quote and before something that looks like a monitor.  You can't format code just by putting braces around it.
Comment: This is part of a final project that I have put together. So, yes it is. I would like to point out that I am not asking anyone to do my homework as I have the attitude, "if I don't know how to do it what is the point"? I am asking for guidance that is all. It is hard to learn how to program in C++ when you have been given a java book.
Comment: I knew about that, yet that was the exact thing that created the format issue in the first place. Again, I am sorry for that.
Comment: Thank you David for the help. I will work on that and hopefully I won't have to come back. I must commend you as you have put that in terms that a beginner, like myself, can understand! Major kudos!
Answer: 1) The three #defines in your code are probably just plain wrong
#define pArray
#define students
#define Request

Especially "pArray", since you use it as a parameter name later on.
2) You're comparing a function against zero. That doesn't make sense, since the test will always succeed.
if (alpha != 0)
{
    alpha(pArray);
}//end if

EDIT: Wait, I see, there's an (incorrectly declared) parameter "hiding" the global name "alpha". Well, that obviously cannot work either, since the parameter has no name ("alpha" is actually the type).
3) As already stated in a comment by David Thornley, you try to call the function with a single argument, which obviously cannot work, since you declared it with two arguments. (Actually you call it with no arguments at all, since the pArray #define will be "expanded" to empty-string)
4) The syntax you try to use to declare variables is just plain wrong
string new fName[sNUMBER];

I do not even know what that is supposed to mean.
And there is probably so much more...
Comment: I agreed that the #define with pArray, etc. Was wrong. I went searching through the wonderful web and came up with that. Thank you for the information. I will take all of this into consideration.
Answer: You really need to get a tutorial or introductory text on C++. There are so many things wrong that I wouldn't know where to begin... the #define's in the beginning of the file make no sense (what do you intend with that? the real effect is that the preprocessor will discard those words), you should not handle strings through pointers (pass references, if possible constant references), you are declaring a tPrint function with two arguments, and defining a different tPrint overload with three, the last of which is incorrect, as alpha is not a type. The first and second argument (after preprocessor substitutions) are unnamed so they cannot be used...
And all that before getting to the first actual line of code...
Comment: I agree about finding the additional text on C++ as this has been one of the most grueling things ever. I have spent the last 4 months literally teaching myself this stuff with virtually no help. Thus, why my code looks horrid. Again, I appreciate everything that you all have brought to the table. I will look into these and continue on.
Answer: The error is: too few arguments to function void alpha(std::string*, student).
When we lookup in the code you typed:alpha(pArray);.
But the function signature is: void alpha(string*,student pArray);
So pass a string as parameter will fix the error but there there are a lot of other wrong things in your code:

void tPrint(string*,student pArray, alpha) What is alpha? I only see an empty define
string new fName[sNUMBER]; Wont compile. I think you mean string* name = new fName[sNUMBER]; And what is a fName?
Many more strange things...

Maybe a C++ tutorial fits you better: see here
Comment: Okay, I knew that I did something wrong with the new lines. fName is my shortened version for First name which is defined in my name.cpp file.
Answer: Your big problem is the #defines.  What you are doing with those is defining the identifiers as, literally, nothing.  Where there was a pArray, there is now nothing.  In C++, any line beginning with # is a preprocessor command, meaning it operates on the text of the program.  In order to actually define an identifier, you just, essentially describe it.
You are using pArray as function parameters, which means none of its occurrences are at the outer scope.  If the preprocessor behaved like any other part of C++, then, it would be harmless, but it just does textual substitution.  You might want to let the compiler tell you when you have failed to define something.
Another issue is the "too few arguments".  You declare alpha as taking two arguments, but only pass one when you call it early in tPrint.
I'm not going to go through the rest of the errors until you fix what you've got.  Once you've removed the #defines and read through the other errors yourself.
Comment: Thank you for your help. I do not expect anyone to sort through all of that as it is my issue. Hopefully this is enough to get me started and continue on.


Learning a Gaussian Process from function observations (not GP regression)

Question: Suppose we have a set of observations, where each observation represents a function. For example, our set is $\{f_1, f_2, ..., f_n\}$ where each $f_i = \{(x_1, y_1), (x_2, y_2), ..., (x_{p_i}, y_{p_i})\} $ representing evaluations of that function.
Now I want to learn a distribution over functions from these function observations, for example a Gaussian Process. What methods can you use for this?
Please note this is not GP regression, where you get a posterior distribution over functions representing your uncertainty over a single true function. I'm instead interested in maintaining a distribution over functions from which you sample genuinely different functions.
As a concrete example, each function observation $f_i$ could represent temperature over the course of a year, I have records from many years, and I'm interested in learning about what temperature profiles generally look like (i.e. warmer in summer, colder in winter), as well as what variations between years looks like.
Comment: So you have several *paths* of a $\text{GP}(\mu,\,k)$; you want to infer on $\mu$ and $k$ or predict/smooth within a specific path. This enters the previous framework with $u$ corresponding to a path. Indeed, a special covariance structure for this setting is $\text{Cov}([x,\,u],\,[x',\,u']) = k_{\text{cont}}(x,\,x')
k_{\text{cat}}(u,\,u')$ where $k_{\text{cont}}(x, \, x')$ is a
continuous kernel and $k_{\text{cat}}(u,\,u')$ is a categorical
kernel, which essentially is a covariance matrix
$[\Gamma_{u,u'}]_{u,u'}$. For i.i.d.  paths take an identity matrix.
Comment: As I understand you are interested in a GP with both a continuous input
$x$ and a categorical input, say $u$. Your observations $Y(x_i,\,u_i)$
are made at a finite set of design points. For instance $x$ can be an
time within the year (in practice a day number between $1$ and $365$)
while the year is categorical or ordinal. In this setting you can not
extrapolate at an unobserved level of $u$.
Comment: @Yves Thanks for the reply. I think my question is slightly different from what you suggest. A GP is distribution over functions, so we can take draws from this distribution, $f_i \sim GP(\mu, k)$, where $f_i$ is a finite-dimensional representation of the function (e.g. evaluations at ${(x_1, y_i), ..., (x_p, y_p)}$. For example, each draw could be an year, "i.i.d." from the GP. Essentially we should be able to learn about the GP's mean and covariance functions this way. The difference with your interpretation is that each year is just an identical draw - there is no additional variable $u$.
Comment: @Yves Yes, that's exactly my framework. As I'm making the i.i.d. assumption $k_{cat}(u, u')$ is the identity matrix as you say, so it does not need to be inferred. In this case do you know how I may go about inferring the mean function $\mu(x)$ and covariance function $k_{cont}(x, x')$?
Comment: You need use a software that can cope with a product kernel as
described and makes maximum-likelihood or Bayesian inference. The
computational task depends on the design, the kernel $k_{\text{cont}}$
and the dimension $d$ of the continuous input $x$. The simple case is
$d = 1$, a tensor design (same $x_i$ for all paths) and a semi-Markov
kernel such as Matérn with shape $1/2$, $3/2$, $5/2$, ...  But in
general, the computational cost is $O(N^3)$ where $N$ is the number of
sample points.
Answer: First off, we need to specify a parametric form for both the mean function $\mu$ (e.g. linear function $\alpha + \beta^Tx$) and the covariance $k$ (e.g. RBF or Matérn). These parameters $\alpha$, $\beta$, $\sigma^2$ etc. are often known as hyperparameters in GP regression.
In the general case when the function paths are not i.i.d., we can index each with a variable $u$. Then the solution is to simply perform GP regression with the mean and covariance functions taking the forms $\mu(x, u)$ and $k((x, u), (x', u'))$, and then optimize the hyperparameters using e.g. maximum marginal likelihood or Bayesian inference. However, the complexity for the regression is $O(N^3)$, where N is the total number of points $(x, u)$, i.e. $N = \sum_{i=1}^n p_i$.
However, in the i.i.d. case, we can simply run a GP regression on each of the $n$ datasets $f_i$ individually, optimizing or Bayesian updating the same hyperparameters for all of these. In this case the complexity is (assuming the number of datapoints per dataset $p_i = p$ is fixed) $O(np^3)$ instead of $O(n^3p^3)$.
The resulting hyperparameter values (if using maximum likelihood) or hyperparameter distribution (if using Bayesian inference) provide the learned "distribution over functions".
Thanks @Yves for the helpful comments.
Comment: Could this be framed in terms of a simple underdetermined resistor network framework? (have a few resistors in different configurations, but with more resistors than equations. Can pretend like there's some relationship between resistors or the "true model". Observed values are the effective resistances)


Clever equalities proven similarly to Euler's Identity

Question: From How to prove Euler's formula: $e^{i\varphi}=\cos(\varphi) +i\sin(\varphi)$?, a very elegant proof of Euler's Identity was given. Namely, observing $f(z)=g(z)h(z)=e^{-iz}(\cos(z)+i\sin(z))$, we can see that $f'(z)=g(z)h'(z)+h(z)g'(z)=0$, showing $f(z)$ is constant, and $f(0)=1$, showing $f(z)=1$ and thus $e^{iz}=\cos(z)+i\sin(z)$.
My question is whether there are other interesting results that can be garnered by finding $g(z)$ and $h(z)$ such that $g(z)h'(z)=-h(z)g'(z)$.
Are there other interesting equalities that are known?
Answer: As you have proved, $g(z)h'(z)=-h(z)g'(z)$ iff $g(z)h(z)$ is constant.
I doubt there is anything else to be said in general.


Create form by Ext.FormPanel

Question: form= new Ext.FormPanel({
    renderTo: Ext.query(".foo")[0],
    items:[]

});

In firebug HTML-code :

Where is the form tag? Or is there no form tag and is this form submit by Ajax?
Comment: What extjs version are you using (2.x, 3.x, 4.x)? And what is your goal?
Comment: I use version Extjs 4
Answer: You shouldn't care about html. ExtJS is a javascript framework that takes care of those things for you. (You shouldn't write tag dependent code? In future releases sencha could modify it and you will have to rewrite/update your code if you do.)
If you provide the form with an url parameter, you can just call .submit() on your form to submit the values.
Here you find an example in the documentation
The documentation's example:
Ext.create('Ext.form.Panel', {
    title: 'Simple Form',
    bodyPadding: 5,
    width: 350,

    // The form will submit an AJAX request to this URL when submitted
    url: 'save-form.php',

    // Fields will be arranged vertically, stretched to full width
    layout: 'anchor',
    defaults: {
        anchor: '100%'
    },

    // The fields
    defaultType: 'textfield',
    items: [{
        fieldLabel: 'First Name',
        name: 'first',
        allowBlank: false
    },{
        fieldLabel: 'Last Name',
        name: 'last',
        allowBlank: false
    }],

    // Reset and Submit buttons
    buttons: [{
        text: 'Reset',
        handler: function() {
            this.up('form').getForm().reset();
        }
    }, {
        text: 'Submit',
        formBind: true, //only enabled once the form is valid
        disabled: true,
        handler: function() {
            var form = this.up('form').getForm();
            if (form.isValid()) {
                form.submit({
                    success: function(form, action) {
                       Ext.Msg.alert('Success', action.result.msg);
                    },
                    failure: function(form, action) {
                        Ext.Msg.alert('Failed', action.result.msg);
                    }
                });
            }
        }
    }],
    renderTo: Ext.getBody()
});

Unrelated but helpful, before Ext 4.x we used the new keyword to create new components, now it's advised to use Ext.create. And instead of Ext.extend, we use Ext.define now and add an extend parameter.
Upgrade Guide
Comment: @VDP A minor correction: Ext.create has its useful side but using it blindly instead of `new` is not recommended because it adds noticeable overhead to object creation. It comes handy when you don't want to hardcode class names, but in most cases plain old `new` is more than sufficient.
Comment: @AlexTokarev I haven't thought about that. Good point! It has it's overhead. I've misinterpreted the documentation a little there. But weighing the overhead vs maintainability, most of the time I still prefer `Ext.create` / `Ext.widget`

Create form by Ext.FormPanel


$\sum \limits_{k=1}^{\infty} \frac{1}{k} \cos 2\pi k \theta$ does not converge as $\theta \rightarrow 0?$

Question: We know that the series $H(\theta) := \sum \limits_{k=1}^{\infty} \frac{1}{k} \cos 2\pi k \theta$ is convergent for every $\theta \in (0,1)$ and for $\theta = 0$ the series tends to $+ \infty$. Is it true that the limit $\lim \limits_{\theta \rightarrow 0} H(\theta)$ does not exsist? How to prove that?
Answer: Knowing this series is convergent, you can find its sum using the formula
$$ \sum_{k=1}^{\infty} \frac{z^k}{k} = -\log{(1-z)}. $$
Then the sum is
$$ -\frac{1}{2}\left( \log{(1-e^{2\pi i \theta})}+\log{(1-e^{-2\pi i \theta})} \right), $$
and the limit of this as $\theta \to 0$ does not exist, since $\log{z}$ diverges as $z \to 0$.


How to select count of a table using ServiceStack OrmLite

Question: How can I select the count from a table and include a where clause to return a long?  Ideally I would use db.Count instead of db.Select.  I'm just not sure how to use db.Count and cannot find documentation on it.
long totalCount = 0;
using (IDbConnection db = dbFactory.OpenDbConnection())
{
    totalCount = db.Count<Content>( ?? );
}
Console.WriteLine(totalCount);

Comment: A lambda appears to have worked in this case.  It didn't seem to want to add first.
Answer: You answered for you question in your comment ;) You should use Count extension method with expression parameter. Example below:
long amout  = db.Count<Post>(x => x.Subject == "test");

OrmLite generates following sql:
SELECT Count(*) FROM POST WHERE (SUBJECT = 'test')

Comment: Exactly what I found.  Thank Adam.


How to update relation of a model in Phoenix?

Question: When I try to edit a book in my MyDb app I'm getting the following error message:
you are attempting to change relation :people of MyDb.Book, but there is missing data.
Here are the relevant snippets:
/web/models/book.ex
defmodule MyDb.Book do
use MyDb.Web, :model
  schema "books" do
    field :title, :string
    field :note, :string
    many_to_many :people, MyDb.Person, join_through: MyDb.BookPerson
    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:title, :note])
    |> put_assoc(:people, parse_people_ids(params))
  end

  defp parse_people_ids(params) do
    (params["people_ids"] || [])
    |> Enum.map(&get_people/1)
  end

  defp get_people(id) do
      MyDb.Repo.get_by(MyDb.Person, id: id)
  end
end

I am able to save relation with this changeset.
/web/controllers/book_controller.ex
  def edit(conn, %{"id" => id}) do
    book = Repo.get!(Book, id)|> Repo.preload(:people)
    people = Repo.all(Person) |> Enum.map(&{&1.surname, &1.id})
    changeset = Book.changeset(book)
    render(conn, "edit.html", book: book, changeset: changeset, conn: conn, people: people)
  end

  def update(conn, %{"id" => id, "book" => book_params}) do
    book = Repo.get!(Book, id)
    changeset = Book.changeset(book, book_params)

    case Repo.update(changeset) do
      {:ok, book} ->
        conn
        |> put_flash(:info, "Book updated successfully.")
        |> redirect(to: book_path(conn, :show, book))
      {:error, changeset} ->
        render(conn, "edit.html", book: book, changeset: changeset)
    end
  end

/web/templates/book/form.html.eex

    <%= label f, "Authors", class: "control-label" %>
    <%= multiple_select f, :people_ids, @people, class: "form-control" %>
    <%= error_tag f, :person_id %>

The comment under error message says I should  include the entry primary key (ID) alongside the data if I want to update an existing entry but I can't figure out how.
Answer: It is necessary to use the option on_replace: :delete in books schema
 schema "books" do
    field :title, :string
    field :note, :string
    many_to_many :people, MyDb.Person, join_through: MyDb.BookPerson, on_replace: :delete
    timestamps()
  end


Ajax success callback is not invoked

Question: When I pass function() { location.reload(); } as a callback - it doesn't get invoked.
$('#swapLanguageLink').click(function() {
    $.post('@Url.Action("SwapLanguage", "Language")', function() { location.reload(); });
    //location.reload();
});

If I un-comment //location.reload(); (instead of passing callback) - it works nice, but I am not sure if it is async or not.
It can happen that my document will be reloaded before async operation is finished, right? So why my callback doesn't work?

Edit:
$.post('@Url.Action("SwapLanguage", "Language")', null, function () {
    location.reload();
}).done(function () {
    location.reload();
}).error(function () {
    alert('error');
});

I've tried the code above. error get invoked. But "SwapLanguage" invokes. Something really strange to me!
Comment: Can you try `$.ajax` to have full control over ajax request?
Comment: @BikashSinghMaharjan does it mean that the only thing I need to change is to put `$.ajax('#swap...')`?
Comment: `$.post('@Url.Action("SwapLanguage", "Language")', null, function () { location.reload(); })
                .done(function () { location.reload(); })
                .error(function () { alert('error'); });` heh.. I've tried the code above... error get invoked. But "SwapLanguage" invokes... Something really strange to me!
Comment: If the `error` callback is invoked it means the Ajax call returned with an error status. Look at the error.
Comment: @Tomalak I am totally new to the ajax... the debug breakpoint in VS does nothing. How can I see the error details?
Comment: Use the browser's developer tools. Look at the network tab. Instead of `alert('error');` use `console.log(arguments);` and look at the console. Set breakpoints in your JS code and inspect variables. Javascript debugging 101, that's not really Ajax-specific.
Answer: Something like this:
jQuery.ajax({
    type: "POST",
    async: true,
    url: '@Url.Action("SwapLanguage", "Language")',
    success: function (data) {
       location.reload();
    },
    error: function (err)
    {
      alert("error");
    }
});

OR
$.post('@Url.Action("SwapLanguage", "Language")', null)
  .done(function(data) {
     location.reload();
  });

Comment: What error comes in your browser? Open `debugger` in your browser and check for errors in `console`
Comment: .erorr invokes.. but at the same time targeted controller method (SwapLanguage()) - runs too. so I get waht I need making .always(...). But  it seems to be strange...

Ajax success callback is not invoked


Reporting Services 2012 - ReportViewer

Question: I have just installed the new SQL Server 2012 with Reporting Services. When I go to my report server page at http://localhost/Reports and select a report, the filter/input bar connected to the report has got a new blueish look. However, when im using the ReportViewer server control version 188.8.131.52, I still get the old beige look as previous versions. It is also missing the new button "Export to Data feed".
Does anyone know if the new ReportViewer server control should look like this or am I missing something?
Answer: The ReportViewer 2012 standalone package is now released. You may want to review my tip: http://blogs.msdn.com/b/arvindsh/archive/2012/12/11/microsoft-report-viewer-2012-update-a-gotcha-to-be-aware-of.aspx
Answer: The ReportViewer control is actually an ASP.NET control provided with Visual Studio, not part of your SQL Server installation. ReportViewer on MSDN
My suggestion would be to try installing the Visual Studio 11 beta and see if there's an updated version of the control in there.
Comment: The control was actually included (version 126.96.36.199) in the VS2011 Beta. Thanks!
Comment: I also use v126.96.36.199 in VS2012 but I get they beige/gray stuff too, and no Feed Export. Do you have any idea? :/
Answer: It is, or at least most of it is. I can't seem to find the Microsoft.ReportViewer.Common dll in my install of VS2012, but that might just be my install. If you don't trying an out of date version from the VS2012 preview, you can download it here: http://www.microsoft.com/en-us/download/details.aspx?id=27230

Reporting Services 2012 - ReportViewer


Adicionar uma coluna nova em uma tabela e já preencher a coluna com os dados de uma coluna já existente na tabela

Question: Olá, estou precisando adicionar uma nova coluna em uma tabela, mas no momento de adicionar a coluna quero preencher os registros já existentes com os dados de um campo que já existe na tabela, segue exemplo:
tabela1
campo id
nessa tabela existe 10 registros com o campo id preenchido com 1,2,3,4,5,6,7,8,9,10(cada qual no seu registros)
Quero adicionar o campo novo_id e no momento da criação do novo campo preencher novo_id com os dados do campo id, ficando assim após a criação do campo.

id       novo_id
1        1
2        2
3        3
4        4
5        5
6        6
7        7
8        8
9        9
10     10

ai depois disso vou fazer um alto incremente diferente na coluna novo_id, então se inserir um novo registro ficaria por exemplo:

id       novo_id
1        1
2        2
3        3
4        4
5        5
6        6
7        7
8        8
9        9
10     10
11     20
Answer: Para fazer isso você terá que primeiro adicionar a coluna e depois realizar um update com valor do campo ID.
ALTER TABLE para adicionar a coluna:
ALTER TABLE Tabela1
ADD COLUMN novo_id integer NOT NULL;

(opcional) ou já adicionar a coluna com auto incremento:
ALTER TABLE Tabela1
ADD COLUMN novo_id SERIAL;

Depois disso você realiza o UPDATE atualizando o novo_id com o Id atual:
UPDATE Tabela1
    SET novo_id = id

Se você adicionou o novo campo como auto incremento, você pode setar o valor do novo_id para o último registro adicionado:
SELECT setval('Tabela1_novo_id_seq', Select MAX(id) from Tabela1);

Todas as referências estão nos links.


Development of standard deviation

Question: I have a cloud of (x,y) variables which show two tendencies.

They appear linear.
As x increases, the y values become more spread out.

Using linear regression, I can plot a nice line through them but how can I get an indication of how the standard deviation of the points develops?
Comment: Does the spread seem to increase linearly or in some other way? Does it seem as if it would it be smallest at x=0 or somewhere else?
Answer: This could simply be a case of heteroskedastic errors. Heteroskedastic errors simply means that the variance of your error term is non-constant.
Using a linear regression to fit your points you would get a specification of the sort:
$$y_i=\beta x_i + \upsilon_i$$
where $$  V(\upsilon_i | x_i) = \sigma^2 h^2_i $$
Then, depending on your variables, you can place some assumptions on your function $h$.

Development of standard deviation


Canceling the emission sequence with Observables RxJS

Question: I'm creating a thread to control mouse directions (pixel by pixel) using javascript. Sometimes I need to stop the mouse movement and give it a new direction (a set of pixels). I would like to use Observables.
I would like to output the pixel sequences, for example:
[(x0, x0), ..., (xN, yN), (x1, y1)]
If a new set of pixels is issued, the previous one will be cleaned.
I would like to know the best way to do this, which operators, etc.
Answer: Assuming you are emitting a "sequence" as an array of "points", something like this should work:
type Point = [number, number];

const DELAY = 200;
const pixelSequence$ = new Subject<Point[]>();

const mousePoint$ = pixelSequence$.pipe(
  switchMap(sequence => timer(0, DELAY).pipe(
    map(i => sequence[i]),
    take(sequence.length),
  ))
);

mousePoint$.subscribe(
  ([x, y]) => setMousePosition(x, y)
);

Here we start with a Subject that will emit a "pixel sequence" (Point[]).  We can define a new Observable that will emit individual points, then subscribe to that observable to set the cursor position:
mousePoint$.subscribe(
  ([x, y]) => setMousePosition(x, y)
);

The core of the functionality happens in the definition of mousePoint$.  We define a new Observable that begins when pixelSequence$ emits a value.  We then use switchMap and create an "inner observable" that emits the sequence items one at a time at with the specified DELAY inbetween.
  switchMap(sequence => timer(0, DELAY).pipe(
    map(i => sequence[i]),
    take(sequence.length),
  ))

If you aren't familiar with switchMap, it basically receives a emission as input, then subscribes to an "inner observable" for you, emitting its emissions.  When switchMap receives a new emission, it will "switch" its inner source to a new observable, unsubscribing from its previous "inner observable".
So, to begin your mouse moving, simply call pixelSequence$.next() with an array of coorinates.  If you need to use a different sequence (whether or not the current sequence has been fully processed), simply call pixelSequence$.next() again with the new sequence.
Here is a example on StackBlitz.
Operators used:

switchMap - subscribe to inner observable and emit its emissions
timer - emit sequential integers at the specified interval
map - transform each emission with the provided function
take - complete the observable when the specified number of emissions have been received
Comment: Working like a charm! Ez for @BizzyBob :)
Comment: Is the code appropriate for sequences that will happen continuously? I mean, the mouse never stops.


Is it possible to access audio playing from the browser in javascript?

Question: Ok, since youtube doesn't allow you the use of the <audio> tag, is it possibile to capture the audio that is playing in the browser? (the stream transmitted to hardware).
And a question still relevant, is it possibile to capture the audio of an <object> tag? How could i make an <object> of a youtube video?
Comment: You can use PHP Media File Info library
Comment: @DmitriyButeiko …that isn't Javascript.
Answer: No and no, respectively.
There is no way to capture audio within a web page, especially across origins (e.g, capturing the audio of a YouTube frame, which has the origin https://youtube.com).
YouTube used to support an <object> embedding method based on Flash. This still exists, but it hasn't been recommended for quite some time, so I won't go into detail. Nor does it help you, as there is no way to capture the audio output from a browser plugin either.
Comment: Oh, thanks for the clarification, but, just to be sure, can an  audio be captured? It's from flash, i'm not really sure.
Comment: Ok, so then, using webRTC is there a way to capture the "computer audio", cause you could enable "stereo mix" but not everyone has it enabled.
Comment: No. There is currently no way to capture audio output anywhere in the browser -- the only reason I'm separating out the two is because you asked about them separately.
Comment: Thanks, for your answers, i could implement this by just letting the user download a file and then open it and stream it. I've been succesfull trying this, and it doesn't even ask you, you just "click save" and it does, how about reading a file, is it the same?


Displaying a product price on Ad Push content?

Question: Hi just started using Drupal a couple of days ago.
I'm using Commerce Kickstart 2. I'm having troubles displaying the product price on the Ad Push content. I just want to know if there is a way to display the product price on the Ad Push?

Thank you very much.
Answer: You would need to add a new Product Reference field to the Ad Push content type. This allows content editors to pick a product to reference. You can then display the price through the "manage display" tab of the Ad Push form. You'll want the "Product: Price" field.


Creating specialized maps with jQuery and/or Google Maps API

Question: I need to create a range-graded circle proportional map, i.e., a map that has circles overlaying a map the size of which circles indicates the proportional density of what I'm trying to measure.  This is best understood by example, and can be seen here: http://www.d.umn.edu/geog/cartfolder/HTML%20Pages/Map-Types.htm.  I've tried poking around with Google Maps API, and can't find anything that will let me create proportional circles on top of a map display; and, furthermore, I would like to be able to narrow it down by major cities in the U.S. (SF, LA, NYC, Chicago, Dallas, etc.).
Is this even possible?
Answer: Yes it is possible.
See this examples (in Russian, sorry)
http://mabp.kiev.ua/2010/08/16/custom-maptype-projection-in-google-map-api-v3/
http://mabp.kiev.ua/2010/08/22/google-maps-v3-and-raphael
here is simple sample
<code>for (var i=0,j=11;i&ly;j;i++){
        new google.maps.Circle({
            strokeWeight: 2,
            strokeColor : "#ffffff",
            map : map,
            center : new google.maps.LatLng(0, 0),
            radius : i*1000000
        });
    }
</code>
http://appdelegateinc.com/samples/Google-Maps-Circle-Overlay/
Comment: Thanks -- this is very helpful.  I'm actually proficient in Russian, so I can make my way through the attached pages (it'll take longer than if they were in English, of course!).


Permutations of Prime Order

Question: Here is the problem

Let $p$ be a prime. Show that an element has order $p$ in $S_n$ if and only if its cycle decomposition is a product of commuting $p$-cycles. Show by an explicit example that this need not be the case of p is not prime.

I was able to show the "only if" part easily enough. But I am having difficulty with the "if" direction. I suppose that $\sigma \in S_n$ has order $p$ yet $\sigma$ is not just the product of commuting $p$-cycles, which would mean that an $n$-cycle, with $n \neq p$, would appear in the product. But this  is where I was unsure of how to proceed, so I consulted this. However, the author claims that "the cycle decomposition of $\sigma$ contains an $n$-cycle $\tau$ for some $n \neq p$, and we can write $\sigma = \tau \omega$." Why does the $n$-cycle $\tau$ appear at the right-end of $\sigma$? Why couldn't it be at the left-end, or even in the interior?
Answer: The cycles in a cycle decomposition of $\sigma$ (not just any product of cycles) are disjoint, hence they commute. So it doesn't matter if it's in the interior; you can always move it to wherever you need it to be.
For example: (123)(45)(678) = (123)(678)(45).
Answer: The order of a permutation is the least common multiple of the lengths of cycles in the decomposition, so every of these lengths divides the order. In particular, if the order is a prime number $p$, then every cycle has length $1$ or $p$.
As to the opposite direction, if $n$ is composite, then you can write $n=pq$ with $(p,q)=1$ and $p,q\neq1$. We see that the product of $(1\ldots p)$ and $(p+1\ldots p+q)$ has order $pq=n$.
Comment: I think you mean least common multiple. Even so, we cannot use this idea you cite; in fact, that showing that idea true is the next problem.
Comment: Thanks, corrected. As to the result, it is rather trivial - just note that the disjoint cycles commute, so if some power of the permutation is the identity, then every such cycle must be the identity raised to this power.
Comment: For the other direction, you say that $n$ is composite. But what if $n$ is another prime number different from $p$? Does that pose any problems with your proof?
Comment: Hmm. If $n$ is another prime number different from $p$, then the same argument shows that the lengths of cycles are equal to $n$, another prime number different from $p$.

Permutations of Prime Order


how to strip a txt file of multiple things?

Question: I am creating a function which reads data of a txt file, the text file is set up as one sentence per line. I have 6 requirements to strip the file of to make it usable later on in my program:
 1. Make everything lowercase
 2. Split the line into words
 3. Remove all punctuation, such as ",", ".", "!", etc.
 4. Remove apostrophes and hyphens, e.g. transform "can't" into "cant" and
 "first-born" into "firstborn"
 5. Remove the words that are not all alphabetic characters (do not remove
 "can't" because you have transformed it to "cant", similarly for
 "firstborn").
 6. Remove the words with less than 2 characters, like "a".

Here's what I have so far...
def read_data(fp):
    file_dict={}
    fp=fp.lower
    fp=fp.strip(string.punctuation)
    lines=fp.readlines()

I am a little stuck, so how do I strip this file of these 6 items?
Comment: As a side note: fp usually stands for file pointers, which is the thing you get after open(), and that fp does not have a .lower(). Perhaps a litter more carful with naming?
Comment: `strip` only looks at the beginning and end of the line (It's really meant to remove extra whitespace).  Also, you're going to have to actually call `lower()`
Comment: Look into using [`re.sub`](https://docs.python.org/3/library/re.html#re.sub) to remove all those characters
Comment: yes it is file pointers, used from another function to open the file
Answer: This can be accomplished via a series of regex checks and then a loop to remove all items with less than 2 characters:
Code
import re

with open("text.txt", "r") as fi:
    lowerFile = re.sub("[^\w ]", "", fi.read().lower())
    lowerFile = re.sub("(^| )[^ ]*[^a-z ][^ ]*(?=$| )", "", lowerFile)
    words = [word for word in lowerFile.split() if len(word) >= 2]
    print(words)

Input
I li6ke to swim, dance, and Run r8un88.

Output
['to', 'swim', 'dance', 'and', 'run']


Reverse printing from txt file using recursion in C

Question: I need to write out .txt file backwards in terminal using recursion, but it seems I'm stuck.
This is my code so far, but it creates an infinite loop. Also, the procedure write() should have only 1 parameter - pointer to file.
#include <stdio.h>

void write(FILE **f)
{
    char cur;

    fseek(*f,-1,SEEK_CUR);
    cur = fgetc(*f);

    printf("%c",cur);
    write(f);
}

int main(void)
{
    FILE *f;
    f = fopen("text.txt","r");
    fseek(f, 0, SEEK_END);
    write(&f);

    fclose(f);
    return 0;
}

I wanted to use fseek and ftell functions, they seem to be best way to do this.
My expected output would be:
FILE
Hello world
OUTPUT
dlrow olleH
Comment: Considering they have a infinite call stack, they won't even be able to see the print outputs.
Comment: @Cassie can you please provide the outputs in the file, if any?
Comment: Your recursive function has no termination criteria. It always makes the recursive call, so it goes on forever until stack overflow. You need logic in a recursive function that decides whether to make the recursive call or not.
Comment: @RohanAsokan Right now my output is *dddddddddddddd* until I stop the program.
Answer: This task is actually not very suitable for the recursion but ..
EDIT I actually misunderstood your question but it is same trivial.
#include <stdio.h>
#include <string.h>

void writeRecursive(FILE *file)
{
    int ch;
    if(fread(&ch, 1, 1, file) == 1)
    {
        writeRecursive(file);
        fwrite(&ch, 1, 1, file);
    }
    else
    {
        rewind(file);
    }

}

int main(void)
{
    FILE *fi = fopen("a.txt", "w+");
    char c;

    fprintf(fi, "123456789");
    rewind(fi);

    writeRecursive(fi);
    rewind(fi);
    while(fread(&c, 1, 1, fi) == 1)
    {
        printf("%c", c);
    }
    printf("\n");
}

https://godbolt.org/z/edGfKa
or
void writeRecursive(FILE *file)
{
    int ch;
    if((ch = fgetc(file)) != EOF)
    {
        writeRecursive(file);
        fputc(ch, file);
    }
    else
    {
        rewind(file);
    }

}

Old answer
void printRecursive(FILE *fi, FILE *fo)
{
    char ch;
    if(fread(&ch, 1, 1, fi) == 1)
    {
        printRecursive(fi,fo);
        fwrite(&ch, 1, 1, fo);
    }

}

int main(void)
{
    FILE *fi = stdin, *fo = stdout;

    printRecursive(fi, fo);
}

https://godbolt.org/z/YjfvcP
Comment: @RohanAsokan The question is literally "I need to print .txt file backwards using recursion".  Nowhere is "write it to the same file" even implied.
Comment: The question is clearly to reverse the file and write it to the same file. And hence the recursion.
Comment: @RohanAsokan I just need to wrtite it out in terminal, not in file
Comment: @Cassie Cool. I have made some progress, it now prints the content. Just figuring wth is the end clause, hehe.
Comment: @Cassie here you have a recursive function which reverses the file
Comment: From certain size of the input file the code won't work any more, because the program would have run out of stack space.
Answer: From what you have given, the way to do the problem recursively using fseek and ftell can be written as follows,
#include <stdio.h>

void write(FILE **f)
{
    char cur;
    cur = fgetc(*f);
    printf("%c", cur);
    if (ftell(*f) == 1) return;
    fseek(*f,-2,SEEK_CUR);
    write(f);
}

int main(void)
{
    FILE *f;
    f = fopen("text.txt","r");
    fseek(f, -1, SEEK_END);
    write(&f);

    fclose(f);
    return 0;
}

Considering the file is read in reverse, the stop condition requires a bit of thinking. The position of a pointer is returned by ftell and using this we can detect if the current position of the pointer is at the start of the file or not (as in if it is equal to 1).
There were tiny mistakes in your code - the recursion never stopped (as pointed out in the comments), make sure you always have a stop inside your recursive functions.
The order of your fseek needs changing so that you read the first character in properly.
And you need to use a -2 inside your fseek to move to the previous character. This is because of the fact that fgetc will advance the pointer by 1 and you will have to go back by 1 character to reach the character that was read just now and you then you want to move it backwards by one more, so that you get to the character before the one that was just read. Thanks to p-j-supports-women-in-poland for pointing this out.
Otherwise the above code will make it clear for you, I hope. if you still got doubts ping me in the comments. Happy to help :)
Comment: @RohanAsokan Thank you! Code works for me and does exactly what I need.
Comment: what is the `fseek` for? It shows lack of understanding how the recursion works.
Comment: Sorry what? Can you be more clear? Thanks
Comment: It is not needed at all.  Type for cur is wrong. Vary bad code. No double `*` pointers needed.
Comment: Umm..it is as the fgetc increments the pointer by 1 and you want to move it two positions back to read the previous character - if that makes sense to you. And yes I agree with the wrong type for cur. I am sorry. But you do not have to be so rude.
Comment: Glad that it worked. Please mark it as the answer. Would help others moving through SO.


If a set has finite outer measure, and its inner measure is equal to its outer measure, then it is measurable

Question: I'm trying to prove this statement in $\mathbb{R} ^n$ with the Lebesgue measure:
$$|E|_e < +\infty \land |E|_i = |E|_e \Rightarrow E \text{ is measurable}$$
My guess is that the easy way of going about it is by trying to find an $F_{\sigma}$ set $K$ such that $E =K \cup N$ with |N| = 0
Constructing $K$ is easy: for each $n$ in $\mathbb N $ we have a closed set $F_n \subset E$ such that $|F| > |E|_i - \frac 1 n = |E|_e - \frac 1 n$. Then set $K := \bigcup_{n \in \mathbb N} F_n$
It's easy to check that $|K| = |E|_e$.
Now let $N = E - K$. I'm stuck trying to prove that $|N| = 0$. The only result I have is that $$|E-K|_e = |E - \bigcup_{n \in \mathbb N} K_n|_e = |\bigcap_{n \in \mathbb N} (E - K_n)|_e \le \lim_{n \to \infty} |E - K_n|_e$$
Where $K_n = \bigcup_{k=1}^n F_n$ is an increasing sequence of closed sets where $K = \bigcup_{n \in \mathbb N} K_n$ and so $E - K_n$ is a decreasing sequence of sets so the inequality above holds
I'm struggling to find a bound for $|E - K_n|_e$
Comment: See [here](https://math.stackexchange.com/q/1104419/977780)
Comment: @SouravGhosh what kind of finite premeasure do I use here? I don't see why they should be additive
Answer: Let $\varepsilon > 0$. Then there exists an open set $G \supseteq E$ such that $|G| < |E|_e + \varepsilon$. Now,
$$|E - K_n|_e \le |G - K_n| = |G| - |K_n| < |E|_e + \varepsilon- |K_n|$$
First inequality by monotonocity of outer measure, and then the equality in the middle because both $G$ and $K_n$ are measurable and $K_n \subseteq E \subseteq G$
Then taking limits on each side, since $\lim_{n\to \infty}|K_n|=|E|_e$, we get $\lim_{n \to \infty} |E-K_n|_e < \varepsilon$
But $\varepsilon$ was arbitrary so it must be 0