Add selection to range in jquery

Question: I have a problem. For example I have a
Helloworld
. And now I want to select (for example) 5th to 9th word. So, I want to have Helloworld ("worl" is hightlighted). Any ideas, how to do this?
Comment: https://stackoverflow.com/questions/12459734/highlight-words-inside-the-string
Comment: Is it dynamic? If not, why not just wrap those letters in a span: `Helloworld`
Comment: Yes, it is dynamic. I need exactly word selection.
Answer: Collect the innerHTML using .html() or .text().
HTML

Helloworld

CSS
.highlight {
  background-color: yellow;
}

JavaScript
$(function(){
  var myText = $("#id").html();
  var newText = myText.slice(0,5) + "" + myText.slice(5,9) + "" + myText.slice(9);
  $("#id").html(newText);
});

Example: https://jsfiddle.net/Twisty/t0yu8pce/
Update
Example: https://jsfiddle.net/Twisty/t0yu8pce/2/
JavaScript
$(function() {
  var myText = $("#id").html();
  var newText = myText.slice(0, 5) + "<input value='" + myText.slice(5, 9) + "' />" + myText.slice(9);
  $("#id").html(newText);
  $("#highlight").click(function(e) {
    $("#id input:text").select();
  })
});

The text to select has to be in a <input> or <textbox> element.
Update 2
Using click: https://jsfiddle.net/Twisty/t0yu8pce/3/
Comment: Thanks, but I wanted to highlight that text, as you can do with your cursor.
Comment: @VojtěchRemiš you didn't mention that. What would trigger this?
Comment: I thought select() works only in an input. It is triggered by div click.
Comment: @VojtěchRemiš provided updates to answer. Yes, it has to be a input or textbox.
Comment: And if it would be a textbox, can I select just (for example) 5th to 7th letters?
Answer: Not sure If this is what you want but you can use  or use  with appropriate style property.
As in your case:

Helloworld

Or do it this way

Helloworld

Comment: I want highlight that letters, like text selection, which you can select with your cursor.
Comment: @VojtěchRemiš You didn't mention that early. Check my other answer that I have posted.
Comment: I am not sure exactly, which answer do you think?
Comment: @VojtěchRemiš . The below posted answer. https://stackoverflow.com/a/44397592/7201256

Add selection to range in jquery


Balls are placed into 3 urns. Expected time until some urn has 100 balls.

Question: We have $3$ urns. At each round a ball is placed is placed into one of them, at random, with uniform probability. The game stops when some urn has $100$ balls.
What is expected duration of the game (number of rounds)?
Results from a simulation:
Comment: @sudix Those are the probabilities for the state (100,i,j). However, that does not mean that this 100 was reached in the *last* placement of the ball. You can reach the state (100,i,j) via (99,i,j) but also via (100,i-1,j) or (100,i,j-1). See in my answer where I compute the case that a an urn has 100 in it *in the last ball placement* by computing the probability that the urn has 99 in it (and no then you have 1/3 probability to reach 100 in the next step).
Comment: @callculus yes.
Comment: @quester I don´t know what the mean at the graph is. But it does not clearly matches my result where I used your formula. Do you think your formula is wrong?
Comment: @Sudix problem with formula is that there should be $\sum p = 1$, but unfortunately it is $\sum p < 1$ it should be summed up and then multiplied by inverse $\sum p = c => p_{new} = \frac{p}{c}$ then $EX = \sum x p_{new}$
Comment: each round we pick one enemy and we hit him once
Comment: yes at random||
Comment: In coding:  you can design a program that randomly increments one of three ints until one of them is $100$.  Record the number of increments, and rerun.  You should see a convergence towards a particular number given a large enough number of simulations.
Comment: What is the probability that  enemy $i$ is hit if enemy $i$ has been chosen?
Comment: @callculus we do not consider enemy attacks
Comment: @AndrewChin sure I wrote this simulation but it is not helping me at all, sure that you can have number through simulations but I would like to get formula (if it's possible)
Comment: So a chosen enemy is a hit enemy?
Comment: Does not look trivial, but probably has been studied here. Thinking. Numerically (not simulation) I get 274.918644
Comment: @quester Thanks for clarification.
Comment: @quester I´ve calculated the sum by using wolfram alpha, [here](https://www.wolframalpha.com/input/?i=sum_%28i%3D0%29%5E%2899%29+sum_%28j%3D0%29%5E%2899%29+%28100%2Bi%2Bj%29*%5Cfrac%7B%28100%2Bi%2Bj%29%21%7D%7B100%21j%21i%21%7D+%281%2F3%29%5Ei+%281%2F3%29%5Ej+%281%2F3%29%5E100). The result is  $\large{252.5}$
Comment: @quester You wrote that you don´t need numbers. But you should start to analyze the problem. For instance, my result does not match the graph you´ve posted. My first question is why?
Comment: @callculus what do you mean? avg of this data is **274.9...** which matches result of leonbloy
Comment: formula is for calculating expected number of steps... although when I come to think of it I took it from multinomial distribtion and I ignored some vectors so... probably sumation of probabilities will give value $<1$ so there should be magic component $1/prob_{sum}$
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/99057/discussion-between-quester-and-callculus).
Comment: @callculus I wonder where the mistake in your formula is (I would calculate it the exactly like that)
Comment: @quester The idea was to fix that the first bowl always gets 100 pulls, and then sum all tuples (0,0) to (99,99) for the other two bowls up: $$\sum _{j=0}^{99} \left(\sum _{i=0}^{99}(100+i+j) \frac{\binom{i+j+100}{100}
   \binom{i+j}{i}}{3^{i+j+100}}\right)$$ So, if anything, I expected that without the $(100+i+j)$, the sum would sum up to $1/3$, but instead it sums up to $\approx 0.89$. Also, even if I norm the  probabilities of the events so their sum goes to1, I get as expected value $275.5308620$, which is too far off from the other result. Somewhere there is still a hole in my reasoning
Comment: let's say that I thought about this problem for a long time and I know it's not trivial, althougt very fun!
Answer:
Computation of the distribution
Let $n$ be the number of balls to draw. Let $m$ be the number of urns. Let $k$ be the target number of balls when the game stops.
You could express the probability to reach a stop in $n$ balls in terms of the probability that the number of balls in each urn is $k-1$ or less (the cumulative distribution).

The number of ways to put $n$ balls into $m$ urns is $m^n$ (with or without reaching the stop condition).

The number of ways to put $n$ balls into $m$ urns but not having reached the stop condition (that is having at most $k-1$ in each of them) can be found by enumerating over the set $S$ of vectors $\vec{k}$ (the numbers $(k_i)$ depicting the the number of balls in each $i$-th urn) that satisfy the condition $$\sum_i k_i = n \quad \text{and} \quad  \forall i:0 \leq k_i < k$$ And
for each of the vector $\vec{k}$ (a set of numbers $k_1,k_2,k_3$) that satisfies these
conditions we compute the the number of ways to distribute the balls
into the urns with those numbers which is $$\text{number of ways to
   put $k_i$ balls in urn $i$} = \frac{n!}{\prod_i{k_i!}}$$ Then we take the sum over all of this $$P(N \leq n) = \frac{1}{m^n}\sum_{\vec{k} \in S} \frac{n!}{\prod_{k_i\in \vec{k}}{k_i!}} $$
where the sum over $\vec{k} \in S$ means the summation over all vectors with numbers $k_i$ that satisfy the conditions and the product over $k_i \in \vec{k}$ means the product with all $k_i$ in the $\vec{k}$.

See below for an implementation in R code:

<code># computation
n <- 99
sum <- rep(0,3*n+1)
for (k1 in 0:n) {
  for (k2 in 0:n) {
    for (k3 in 0:n) {
      t = (k1+k2+k3)
      sum[t+1] = sum[t+1]+exp(lfactorial(t)-lfactorial(k1)-lfactorial(k2)-lfactorial(k3))
    }
  }
}
x <- c(0:(3*n))
Xcum <- c(sum/3^x,0)

# simulation
set.seed(1)

draw <- function() {
  s <- sample(c(1:3),size = 300, replace=TRUE)
  min(which((cumsum(s==1)==100) | (cumsum(s==2)==100) | (cumsum(s==3)==100)))
}
q <- replicate(10^5,draw())

# computation using beta function

drn <- function(n,k) {
  a <- max(0,n-2*k+1)
  b <- min(k-1,n-k)
  choose(n-1,k-1) * 2^(n-k) / 3^(n-1) *
      ( zipfR::Ibeta(0.5,n-k-b+1,b+1)/beta(n-k-b+1,b+1) -
        zipfR::Ibeta(0.5,n-(k-1)-(a-1),(a-1)+1)/beta(n-(k-1)-(a-1),(a-1)+1) )
  #choose(n-1,k-1) * 2^(n-k) / 3^(n-1) * (pbinom(b,n-k,0.5)-pbinom(a-1,n-k,0.5))
}
drn <- Vectorize(drn)

#plotting both together

h <- hist(q, breaks=c(0:298)+0.5, xlim=c(200,300),
          xlab = "N", ylab = "probability", freq = FALSE, main="")
lines(1:298,-diff(Xcum),col=2)
lines(c(100:298),drn(c(100:298),100),col=3)
</code>

multinomial distribution
You can view this as related to the multinomial distribution which has the pdf
$$\frac {n!}{k_1! k_2! ... k_m!} p_1^{k_1} p_2^{k_2} ... p_m^{k_m} $$
which becomes for equal $p_i = 1/m $ the following
$$\frac {1}{m^n}\frac {n!}{k_1! k_2! ... k_m!} $$
which shows similarity with the expresssion before. Then the probability that for $n$ draws you did not reach 100 yet is equal to the probability that in 100 draws each $k_i<100$. And you can see the computation of you probability density as the computation of the CDF for the multinomial distribution.

Expression in terms of regularized incomplete beta function
For the case of three urns we may write an explicit expression for the probability in terms of the regularized incomplete beta function.
The probability that there are in the $n$-th draw $k$ balls in the first urn and less than $k$ in the others is, is equal to the 1/3 of the probability that there are in the $n-1$ draw $l= k-1$ balls in the first urn and equal or less than $l$ in the others is :
$$\begin{array}{rcrl}
P_{k_1=l=k-1,k_2 \leq l,k_3 \leq l \vert n-1} &=& &\sum_{a \leq k_2 \leq b} \frac {1}{3^{n-1}}\frac {(n-1)!}{l! k_2! (n-1-l-k_2)!} \\
& = & \frac{(n-1)!}{l! 3^{n-1}} &\sum_{a \leq k_2 \leq b} \frac {1}{k_2! (n-1-l-k_2)!} \\
& = & {{n-1}\choose{l}} \frac{2^{n-1-l}}{3^{n-1}}&  \sum_{a \leq k_2 \leq b} \underbrace{{n-1-l\choose{k_2}} \frac{1}{2^{n-1-l}}}_{\text{this is a binomial distribution}} \\
& = & {{n-1}\choose{k-1}} \frac{2^{n-k}}{3^{n-1}} & \left( I_{1/2}(n-k-b+1,b+1) - I_{1/2}(n-k-a+2,a) \right)
\end{array}$$
with $a = max(0,n-2k+1)$ and $b = min(k-1,n-k)$

Computation of the expectation value
In the first part we computed $P(n>k) = 1-P(n\leq k)$. To obtain the mean you can sum over all of these. $\mu = \sum 1-P(n\leq k)$. This will give:
$$\sum_{k_1=0}^{99}\sum_{k_2=0}^{99}\sum_{k_3=0}^{99} \frac{1}{3^{k_1+k_2+k_3}} \frac{(k_1+k_2+k_3)!}{k_1!k_2!k_3!} = 274.9186 $$
Comment: nice solution, specially in the first part. But $(k_1,k_2,k_3)$ is not a set, it is a triple (vector)
Answer: The expected time can be expressed in terms of the incomplete gamma function as follows (inspired by this paper and comments here):
In general: We want the expected value of the time to wait $T$ until one of the $3$ urns contains $n$ ($=100$) balls. Then
$$E_{n}[T] = \sum_{t=1}^\infty P(T\ge t) = \sum_{t=0}^\infty p_{n}(t) \tag1$$
where $p_{n}(t) $ is the probability that after $t$ rounds ($t$ balls) all $3$ urns have less than $n$ balls. But this is equivalent to
$$ \sum_{x=0}^{n-1}\sum_{y=0}^{n-1}\sum_{z=0}^{n-1} \frac{1}{3^{x+y+z}} \frac{(x+y+z)!}{x! \, y! \, z!} \tag2$$
Further, we use a property of the (upper) incomplete gamma function:
$$\begin{align}
\left( \frac{\Gamma(n,a)}{\Gamma(n)} \right)^3 &= \left( e^{-a} \sum_{r=0}^{n-1}\frac{a^r}{r!} \right)^3 \\&=
e^{-3a} \sum_{x=0}^{n-1}\sum_{y=0}^{n-1}\sum_{z=0}^{n-1}\frac{a^{x+y+z}}{x! \, y! \, z!} \tag3
 \end{align}$$
Integrating and using $\int_0^\infty \exp(-3a) a^p da = p!/3^{p+1}$ we get
$$ \int_0^\infty  \left( \frac{\Gamma(n,a)}{\Gamma(n)} \right)^3 da=
\sum_{x=0}^{n-1}\sum_{y=0}^{n-1}\sum_{z=0}^{n-1} \frac{1}{3^{x+y+z+1}}
 \frac{(x+y+z)!}{x! \, y! \, z!} \tag4$$
and finally
$$E_{n}[T]  = 3 \int_0^\infty  \left( \frac{\Gamma(n,a)}{\Gamma(n)} \right)^3 da \tag5$$
More in general, if we have $d$ urns:
$$E_{n,d}[T]  = d \int_0^\infty  \left( \frac{\Gamma(n,a)}{\Gamma(n)} \right)^d da \tag6$$
This can be evaluated numerically, I don't know about asymptotics (asked here).
Empirically , it seems that  $E = 3 n - \beta \sqrt{n} +O(1)$ where $\beta \approx 2.5$

And here's a numerical recursive computation (in Java):
<code>public class MSE3368225 {

    static Double[] cache = new Double[(1<<21)];

    static double ex(int x, int y, int z) {
        if (x == 0 || y == 0 || z == 0)
            return 0;
        if (x > 127 || y > 127 || z > 127)
            throw new RuntimeException("Out of range");
        int k = (x << 14) | (y << 7) | z; // packs three variables in one integer
        Double d = cache[k];
        if (d == null) {
            d = 1 + (ex(x - 1, y, z) + ex(x, y - 1, z) + ex(x, y, z - 1)) / 3.0;
            cache[k] = d;
        }
        return d;
    }

    public static void main(String[] args) {
        System.out.println(ex(100, 100, 100));
    }
}
</code>
This solves the recursion
$$g(x,y,z)=\begin{cases} 0 & \text {if $x=0$ or $y=0$ or $z=0$}\\
1+ \frac13\left(g(x-1,y,z)+g(x,y-1,z)+g(x,y,z-1)\right) & \text{elsewhere}
\end{cases}
$$
where $g(x,y,z)$ is the expected remaining time, when there remains $(x,y,z)$ balls for each urn.
The result is $E_{100}[T]=274.9186440$

Some values
<code>  n     E
  2  2.888889
  3  5.049383
  4  7.348270
  5  9.734204
 10  22.34468
 20  48.99126
 50  132.3676
100  274.9186
</code>
Comment: noticed that if it would be optimized like (x,y,z) always would be sorted then number of steps would be greatly reduced
Comment: and how did you computed this integral $E(L, N)$?
Comment: You mean how I evaluated it or how I got it? If the former: numerically - and I checked that it agreed with the code above.
Comment: I mean how did you figured out this formula with integral and fraction with gamma functions, I wish I worked more with gamma functions and I would like to develop intuition behind gamma functions in probability theory
Comment: @quester I added an explanation
Comment: Very nice solution, thanks a lot! Just a comment that I linked here from [Expected number of rolls until a number appears $k$ times](https://stats.stackexchange.com/q/475821/1352), which is of course the exact same problem (with $d$ the number of sides of the die, and $k=100$ here).


Exibir 2 dataTextField em um SelectList

Question: Ola! Estou com um probleminha para fazer um selectlist exibir 2 valores no textfield.
Tenho o seguinte SelectList que está armazenado em uma viewbag:
ViewBag.Account = new SelectList(new AccountBusiness().GetList<Account>(Util.AuxiliaryMethods.BMPerRequestInstance).ToList(), "AccountId", "AccountNumber");

No DOM ele exibe o AccountNumber no texto do Option e o AccountId no seu value. Na tela ele exibe da seguinte forma:

Eu preciso que ele exiba em vez de apenas o AccountNumber, exiba também mais um campo, que é o Description, então ficaria o AccountNumber + Description, mais ou menos assim "15252 - Standart", e no value continuaria retornando o Id. Como posso fazer o SelectList receber dois parametros ?
Comment: Poderia concatenar a propriedade `Description` com um separador e depois ao obter o valor fazia um _split_ pelo caracter separador (pode ser "-" ou ";").
Comment: Penso que seria no `SelectList` diretamente.
Comment: O valor que seria o Id eu ja to obtendo pelo Value do option, então o texto que eu colocar no option não vai fazer diferença. Então acho que não teria necessidade de dar um split pra pegar ele depois, é que to pegando  o id pelo javascript. Mas sobre concatenar, faço antes de mandar pro selectlist ou depois ?
Comment: Mas como faria isso ? Tentei fazer ele passar tipo 2 campos, utilizando + "-" + mas ele entende como se fosse o nome do campo. Se eu jogar la "AccountNumber" + "-" + "Description" ele procura exatamente esse campo. Não manjo muito de concatenação como pode ver huahua se puder me ajudar com exemplo de codigo
Answer: Basta você popular o seu SelectList() com uma List<SelectListItem> ou compor outro objeto com estrutura fornecendo os valores que serão utilizados para as propriedades Value e Text.
var selectAccounts = new AccountBusiness()
                            .GetList<Account>(Util.AuxiliaryMethods.BMPerRequestInstance)
                            .Select(x => new { Value = x.AccountId, Text = string.Format("{0} - {1}", x.AccountNumber, x.Description})
                            .ToList();
ViewBag.Account = new SelectList(selectAccounts, "Value", "Text"));

Comment: Ha, ia responder mesmo isso, por pouco :)
Comment: Agradeço brother ! Ele no caso retornou isso na dropdownlist "{ Value = 1, Text = 15252 - Standart }" , mas funciona, pega o Description e o Accountnumber, só vou ver um jeito de jogar o value no value do option. Valeu mano!
Comment: Veja minha edição, acho que agora está mais claro.
Comment: Eu tinha esquecido de declarar os atributos, uma vez que utilizei um objeto simples e não do tipo `SelectListItem`

Exibir 2 dataTextField em um SelectList


Oracle - WHERE COM SYSDATE

Question: No primeiro select o SALDO está vindo zerado, no segundo que substituo o sysdate por qual seria a data ele traz o valor correto
qual deve ser o problema no sysdate+4 no where?
SELECT SYSDATE+4 DATA, (SELECT NVL(SUM(E1_SALDO),0) A
FROM PROTHEUS.SE1010
INNER JOIN PROTHEUS.SED010 ON ED_CODIGO=E1_NATUREZ
WHERE SE1010.D_E_L_E_T_<>'*' AND SED010.D_E_L_E_T_<>'*' AND E1_SALDO<>'0' AND (TO_DATE(E1_VENCREA, 'YYYYMMDD')) = (SYSDATE+4))A
FROM DUAL

SELECT SYSDATE+4 DATA, (SELECT NVL(SUM(E1_SALDO),0) A
FROM PROTHEUS.SE1010
INNER JOIN PROTHEUS.SED010 ON ED_CODIGO=E1_NATUREZ
WHERE SE1010.D_E_L_E_T_<>'*' AND SED010.D_E_L_E_T_<>'*' AND E1_SALDO<>'0' AND E1_VENCREA = ('20190924'))A
FROM DUAL

Answer: O retorno do SYSDATE depende de como está configurado o NLS_DATE_FORMAT, o formato deve estar diferente e a comparação está falhando.
Veja um exemplo abaixo:
SELECT
SYSDATE DATA1, --o retorno aqui depende do NLS_DATE_FORMAT que provavelmente retorna diferente do que está esperando 'YYYYMMDD'
TO_CHAR(SYSDATE, 'YYYYMMDD') DATA2 --Aqui estou convertendo essa data no formato que deseja, mas como char
FROM DUAL;

Abaixo fiz mais um exemplo comparando algumas datas:
SELECT
     CASE TO_CHAR(DATA1, 'YYYYMMDD') WHEN DATA2 THEN 'V'
     ELSE 'F' END COMPARA_1_2,
     CASE TO_CHAR(DATA3, 'YYYYMMDD') WHEN DATA4 THEN 'V'
     ELSE 'F' END COMPARA_3_4
 FROM
  (SELECT
  SYSDATE DATA1,
  TO_CHAR(SYSDATE, 'YYYYMMDD') DATA2,
  SYSDATE DATA3,
  TO_CHAR(SYSDATE+4, 'YYYYMMDD') DATA4
  FROM DUAL) QRY;

Na sua query ficaria assim:
SELECT SYSDATE+4 DATA, (SELECT NVL(SUM(E1_SALDO),0) A
FROM PROTHEUS.SE1010
INNER JOIN PROTHEUS.SED010 ON ED_CODIGO=E1_NATUREZ
WHERE SE1010.D_E_L_E_T_<>'*' AND SED010.D_E_L_E_T_<>'*' AND E1_SALDO<>'0' AND (TO_CHAR(E1_VENCREA, 'YYYYMMDD')) = (TO_CHAR(SYSDATE+4, 'YYYYMMDD')))A
FROM DUAL

Comment: Ou TO_DATE(E1_VENCREA, 'YYYYMMDD') = Trunc(SYSDATE+4)
Comment: Acho que mataria o cara da Totvs que decidiu usar string no lugar de date .... :)
Comment: George, assim deu erro ORA-01481..
 Segui sua lógica e consegui assim:

 AND (TO_DATE(E1_VENCREA,'YYYYMMDD')) = (TO_DATE(TO_CHAR(SYSDATE+4, 'YYYYMMDD'),'YYYYMMDD')))A

Como Motta sugeriu funcionou também

Muito obrigado senhores!!

Oracle - WHERE COM SYSDATE


$\phi(t)=\sqrt{1-t^2} \ $ if $|t|<1$ and $\phi(t)=0$ if $|t| \geq 1.$ Prove that $\phi(t)$ is not a characteristic function

Question:
$\phi(t)=\sqrt{1-t^2} \ $ if $|t|<1$ and $\phi(t)=0$ if $|t| \geq 1.$
Prove that $\phi(t)$ is not a characteristic function.

$\phi(t)$ checks obvious signs of a characteristic function ($\phi(0)=1, \ |\phi(t)| \leq 1$).
$\phi(t)$ is an even real-valued function, so if it is a characteristic function, then its corresponding random variable $X$ has a distribution that is symmetric about zero.
Assuming $E|X|^k$ exists, we should have
$\phi^k(0) = i^k E X^k.$
$\phi'(0) = \frac{-2t}{2\sqrt{1-t^2}} |_{t=0}=0$ (since $X$ is assumed to be symmetric, odd moments of $X$ would be $0$, so it's correct).
$\phi''(0) = \frac{-\phi(t) + \phi ' (t)(t)}{\phi^2(t)} |_{t=0} =  \frac{-1+0}{1} = i^2 EX^2 = -EX^2 \Longrightarrow EX^2 = 1$.
$\phi'''(0)$ is also $0$, and I can't calculate further. Wolfram says $\phi''''(0)=3$; I see no use for it.
Finding pdf from the "characteristic function" (Wolfram calculated the integral):
$p(x)=\frac{1}{2\pi} \int_{t=-1}^{t=1} \cos(tx) \sqrt{1-t^2} dt = \frac{\pi J_1(x)}{x},$ where $J_1(x)$ is "Bessel function of the first kind" (we haven't studied it).
Could someone please help me see how $\phi(t)$ is not a characteristic function?
Comment: @AnuragA Polya's Theorem works only one way. None of the suggestions in that link seem to help in the present case except for Bochners' Theoem. Perhaps, we have to just play around  a bit and show that the function is not positive definite.
Comment: your function $\phi$ has a finite second derivative at $0$, but $\phi\notin\mathcal{C}^2(\mathbb{R})$. If it were a characteristic function, the fact that $\phi''(0)$ exists, implies that in fact $\phi\in\mathcal{C}^2(\mathbb{R})$.
Answer: No, $\phi(t)=\sqrt{(1-t^2)_+}$ is not a characteristic function since the function $\phi$ has a finite derivative of second order at $0$, but $\phi\notin\mathcal{C}^2(\mathbb{R})$.

The argument is encapsulated in two known facts about the Fourier transform of measures (for probability measures, see  Wikipedia here).
For a complex measure $\mu$ on $(\mathbb{R},\mathcal{B}(\mathbb{R}))$ define
$$\widehat{\mu}(t)=\int_\mathbb{R} e^{itx}\,\mu(dx)$$

Theorem 1: If $\mu$ is a complex measure on $(\mathbb{R},\mathcal{B}(\mathbb{R}))$ ((real finite is included in this case) and
$$\int_{\mathbb{R}}|x|^m|\mu|(dx)<\infty$$
for some $m\in\mathbb{N}$ ($|\mu|$ is the variation measure of $\mu$), then $\widehat{\mu}$ is $m$-th differentiable,  $\widehat{\mu}^{(m)}$  is uniformly continuous,  and
$$\widehat{\mu}^{(m)}(t)=i^m \int_\mathbb{R} x^m e^{ixt}\,\mu(du)$$

Theorem 2: If $\mu$ is a finite positive measure on $(\mathbb{R},\mathcal{B}(\mathbb{R}))$, and $\widehat{\mu}^{(n)}(0)$ exists and is finite for some $n\in 2\mathbb{N}$, then $\widehat{\mu}\in \mathcal{C}^{n}(\mathbb{R})$, $\int_{\mathbb{R}}|x|^n\mu(dx)<\infty$, and
$$\widehat{\mu}^{(n)}(t)=i^n \int_\mathbb{R} x^n e^{ixt}\,\mu(du)$$

Theorem 1  follows by dominated convergence an induction on the order of derivatives.
Theorem 2 follows by dominated convergence, the identity
$$-\frac{e^{ihx}-2+e^{-ixh}}{h^2}=\frac{2(1-\cos(hx))}{h^2}$$
and some induction arguments on half the order of the derivative, and by Theorem 1.

These results appear either as theorems or as exercises in many textbooks (see for example, Kallenberg, O. Foundations of modern Probability , Springer-Verlag, Berlin, 2nd Edition, 2002,  pp. 101, or Klenke, A., Probability Theory: A comprehensive course, Universitext, Springer-Verlag, London 2008, pp. 312-315)


What settings are there for sending an email to the users who create accounts?

Question: How can I send an email to users after registration, confirming they have been registered?
From user/register, when users enter the required data (name, username, email) as administrator I receive the account information, but the users don't get any message.
Answer: In configuration > people > account settings or going to config/people/accounts you can set who gets what and even modify the text
Register without admin approval
Check this setting
Who can register accounts? : visitors

and the user that registers will receive Welcome (no approval required) email which will include a one time link to complete registration.  Upon clicking on the link and following the instructions he is a registered user.
Register with admin approval
check the following setting
Who can register accounts? : Visitors, but administrator approval is required

The user will get Admin (user awaiting approval) email upon registering and if enabled on Account activation the setting Notify user when account is activated is enabled the user will get a 2nd email upon admin approval.
Comment: Thank you and I am sorry for the late reply, I just got back. I have set up "Visitors, but administrator approval is required". Is there a way to send out the email with admin approval on?
Comment: modified the answer please check
Comment: A million thanks. I'll do as you say and let you know.
Comment: Hello, I checked and all these settings are enabled. Still the user gets no email. Any guesses what might be wrong? Thank you again.
Comment: Are you sure your system can actually send emails ? does password reminder send email ?
Comment: Hello again, it finally works now but emails end up in the spam folder. Do you think this is related to https? I bought an ssl certificate but it works only  if you type the site name with https not with http. I haven't been able to redirect all traffic to https from the htacess file. Can that be the problem? Thank you again for your help. I am from Thessaloniki.
Comment: @kyriakib nice to see you here. What you are asking is not related to https and its a whole different subject and not specific to drupal.  I think you should start with searching some articles on "prevent emails from going to spam" and there is probably some drupal modules to help with that but its a coordination between setting things in drupal and on your DNS settings.
Comment: I am sorry for the late reply. Something unexpected came up. Thank you  for letting me know. I asked the hosting provider and they changed some settings. It will be all right soon. Thanks again.


$|z_2|z_1 +|z_1|\bar z_2$

Question: If for any two non zero complex numbers z1 and z2 , if $z_1 (1+|z_2|)=iz_2 (1+|z_1|)$ , then we have to find the value of  $|z_2|z_1 +|z_1|\bar z_2$
My try
$z_1 (1+|z_2|)=iz_2 (1+|z_1|)$ in this I multiplies both sided by $\bar z_1$
from.that I got $\bar z_1 z_2$ is purely imaginary .
after that I got stuck
Comment: How about $z_1=x_1+iy_1$  or $$z_1=r_1e^{it_1}$$
Answer: Consider $z_1 = i$ and $z_2 = 1$.
Then, $z_1 (1+|z_2|) = i(1+1) = 2i$ and $iz_2(1+|z_1|) = i(1+1) = 2i$.
However, $|z_2|z_1 +|z_1|\overline{z_2} = |i|(i) + |i|\overline1 = i+1 \ne 0$.
Answer: I found exactly the same counterexample as DHMO. However, I want to share how I found it, so maybe you can come up with many more counterexamples.
I started setting $z_1=re^{i\theta},z_2=\rho e^{i\phi}$. The hypothesis then becomes:
$$re^{i\theta}(1+\rho)=i\rho e^{i\phi}(1+r).$$
Taking moduli, this yields:
$$r(1+\rho)=\rho(1+r)\iff r=\rho.$$
So $|z_1|=|z_2|$. Then I took arguments:
$$\theta=\phi+\frac{\pi}{2}+2k\pi\iff\theta-\phi=\frac{\pi}{2}+2k\pi.$$
Since this approach didn't seem to be leading me to a proof, I tried a disproof. Since the moduli are equal, I thought, why not set them to 1, simplifying the equations? The hypothesis, with moduli equal to 1, becomes:
$$2z_1=2iz_2\iff z_1=iz_2\iff z_1=e^{i\theta},z_2=e^{i(\theta-\frac{\pi}{2})}.$$
Plug into thesis:
$$0=z_1+\overline{z_2}=e^{i\theta}+e^{i(\frac{\pi}{2}-\theta)}=e^{i\theta}+ie^{-i\theta}=z_1+i\overline{z_1}.$$
Let's switch to algebraic form: $z_1=a+ib$. This gives, plugging into thesis:
$$0=a+ib+i(a-ib)=a+b+i(a+b)\iff a=-b.$$
So $z_1$ should be a real multiple of $1-i$, which with modulus 1 implies:
$$z_1=\frac{1}{\sqrt2}(1-i).$$
So just take any other $z_1$ with modulus one, and you will find a counterexample. For example, $z_1=i$. Plug into hypothesis to find $z_2$, always under the assumption that $|z_2|=|z_1|=1$:
$$0=z_1(1+|z_2|)-iz_2(1+|z_1|)=2i-2iz_2\iff z_2=1.$$
Plug into thesis, it doesn't work. Many more counterexamples can be found.
Note that, since the moduli are equal, you can just assume $|z_1|=r$ for any $r$, and the thesis and hypothesis merely get multiplied by $r^2$, so you still get $z_1$ is a multiple of $1-i$, which is very restrictive.
Answer: From $z_1 (1+|z_2|)=iz_2 (1+|z_1|)$ you have that $ (1+|z_2|)\Im (z_1)  = (1+|z_1|) \Re (z_2)$ and $ (1+|z_2|)\Re (z_1)  = - (1+|z_1|) \Im (z_2)$ .
Plugging in our two findings from above gives
$$
|z_2|z_1 +|z_1|\bar z_2=\\
|z_2|(- \frac{1+|z_1|}{1+|z_2|} \Im (z_2) + i \frac{1+|z_1|}{1+|z_2|} \Re (z_2)) +|z_1|(\Re (z_2) - i \Im (z_2))=\\
(- |z_2| \frac{1+|z_1|}{1+|z_2|} \Im (z_2) + |z_1|(\Re (z_2) ) - i (- |z_2|\frac{1+|z_1|}{1+|z_2|} \Re (z_2)) + |z_1| \Im (z_2))
$$
Further, from $z_1 (1+|z_2|)=iz_2 (1+|z_1|)$ you have that  $|z_1| (1+|z_2|)=|z_2| (1+|z_1|)$ from which you even have $|z_1| =|z_2|$. So our expression reduces to
$$
|z_2|z_1 +|z_1|\bar z_2=\\
|z_1|\Big[ ( \Re (z_2) - \Im (z_2) ) + i ( \Re (z_2) - \Im (z_2)) \Big] =\\
|z_2|\Big[\bar z_2 + i z_2 \Big]
$$
Answer: Hint: taking the square of magnitudes on both sides of $\,z_1 (1+|z_2|)=iz_2 (1+|z_1|)\,$:
$$\require{cancel}
|z_1|^2(1+|z_2|)^2=|z_2|^2(1+|z_1|)^2 \\
|z_1|^2(1 + 2 |z_2| + \bcancel{|z_2|^2})=|z_2|^2(1+2|z_1|+\bcancel{|z_1|^2}) \\
(|z_1|-|z_2|)(|z_1|+|z_2|+2 |z_1||z_2|)=0
$$
The latter gives $|z_1|=|z_2|\,$, so the given relation simplifies to $z_1=i z_2\,$.
Then $|z_2|z_1 +|z_1|\bar z_2 = |z_2|(i z_2 + \bar z_2)=|z_2|\cdot \left(\operatorname{Re}(z_2)-\operatorname{Im}(z_2)\right)\cdot(1+i)\,$.

$|z_2|z_1 +|z_1|\bar z_2$


Calculating Cosine Distance in MXNet

Question: I want to be able to calculate the cosine distance between row vectors using MXNet. Additionally I am working with batches of samples, and would like to calculate the cosine distance for each pair of samples (i.e. cosine distance of 1st row vector of batch #1 with 1st row vector of batch #2).
Cosine distance between two vectors is defined as in scipy.spatial.distance.cosine:
Answer: You can use mx.nd.batch_dot to perform this batch-wise cosine distance:
import mxnet as mx

def batch_cosine_dist(a, b):
    a1 = mx.nd.expand_dims(a, axis=1)
    b1 = mx.nd.expand_dims(b, axis=2)
    d = mx.nd.batch_dot(a1, b1)[:,0,0]
    a_norm = mx.nd.sqrt(mx.nd.sum((a*a), axis=1))
    b_norm = mx.nd.sqrt(mx.nd.sum((b*b), axis=1))
    dist = 1.0 - d / (a_norm * b_norm)
    return dist

And it will return an array with batch_size number of distances.
batch_size = 3
dim = 2
a = mx.random.uniform(shape=(batch_size, dim))
b = mx.random.uniform(shape=(batch_size, dim))
dist = batch_cosine_dist(a, b)
print(dist.asnumpy())

# [ 0.04385382  0.25792354  0.10448891]

Comment: This code is wrong. Indeed, you need to check for division by zero or you will get NaN values... Else, you can approximate the cosine by adding a small epsilon to the norm.

Calculating Cosine Distance in MXNet


Continuity of eigenvalues and spectral radius for a general matrix

Question: Given a general matrix $A(t), t>0$, with real entries, I would like to know if the eigenvalues of $A(t)$ are continuous functions of $t$. These eigenvalues may be real or complex.
What about the spectral radius?
A classical result from complex analysis states that the roots of a polynomial vary continuously with the coefficients. Can we use the theorem directly to prove the above? or there are other cases where the eigenvalues are actually discontinuous?
What I'm actually doing is trying to prove that there exists a $t$ for which the spectral radius of $A(t)$ is in $(0,1)$, and I'm doing that by proving that the spectral radius is 1 if $t\rightarrow 0$ and 0 if $t\rightarrow \infty$ (which I already know). Then I would invoke the continuity of the spectral radius to say that there must exist a value of $t$ for which the spectral radius is in $(0,1)$
Thank you.
Comment: Presumably, this is assuming that the map $t \mapsto A(t)$ is itself continuous, even though the question doesn't directly say so.
Comment: Keep in mind that because a matrix has more than one eigenvalue, one must be careful in defining eigenvalue functions $\lambda_1(t), \ldots, \lambda_n(t)$. If one defines these such that $\lambda_1 \le \ldots \le \lambda_n$, then one must be careful when $\lambda_i(t) = \lambda_{i+1}(t)$ for some $t$.
Comment: If you know that the maximal root (in absolute value) of a polynomial varies continuously and the characteristic polynomial depends clearly continuously on the matrix, doesn't it answer your spectral radius question?
Comment: @Alqatrkapa You're right.. but the transition should be continuous. right? At the least, the spectral radius should be continuous if the eigenvalues are.
Comment: @PeterFranek Yeah I guess. From Wikipedia:
"The n roots of a polynomial of degree n depend continuously on the coefficients.
This result implies that the eigenvalues of a matrix depend continuously on the matrix. A proof can be found in a book of Tyrtyshnikov."
It looks like this is true for any matrix...
Comment: The main problem is: how the function that sends  to the eigenvalues of () is defined? In general, one might expect that such a function must be continuous but trying to describe it as an actual function might get things to their worse. I would suggest defining the function as a multifunction first $-$ before going to the technicalities of the definition of such a function as an actual function to, then, verify if this is continuous. These topics have been extensively studied, but, in general, they may be unnecessarily technical for our purposes.
Answer: All of these are continuous, since they are the compositions of continuous functions.
The function from the matrix to any coefficient of the polynomial is itself a polynomial on the entries of the matrix, which is continuous. Thus, the function from a matrix to the vector listing the coefficients of the polynomial is continuous.  So, the function from a matrix to its characteristic polynomial is continuous.
The function from a characteristic polynomial to its roots is continuous.  So, by the continuity of composition, the function from a matrix to its eigenvalues is continuous.
The function $x \mapsto |x|$ is continuous, as is $(x_1,\dots,x_n) \mapsto \max\{x_1,\dots,x_n\}$.  So, the function that yields the largest absolute value of an entry of a vector is continuous.  So, by composition, the spectral radius function is continuous.
Comment: If you talk about continuity, you have to specify the topologies. You said: "The function from a characteristic polynomial to its roots is continuous." I guess what you mean here is that the map from the coefficient vector $(a_0,\ldots,a_{n-1})$ to the set of roots of $\sum a_kz^k$ is continous, where on the left you have just the topology of $\mathbb C^n$ and on the right you use the Hausdroff metric. Is that correct?
Comment: The function which sends the set with $n$ elements to its subset with the largest $k<n$ elements is also continuous. This means that all the ordered eigenvalue functions $\lambda_1 \leq \lambda_2 \leq \cdots \leq \lambda_n$ are continuous.
Answer: Before talking about the continuity of eigenvalues as functions, one must be clear about the term "eigenvalue function". What does it really mean? How is it defined?
If A(t) is an nxn matrix in which each entry is a continuous function of the parameter t, then for each t, A(t) has n eigenvalues (constituting the spectrum of A(t)). The spectrum of A(t) is a multiset and it is uniquely determined for each t (via A(t)). However, how to number (or parameterize) the eigenvalues in the set is tricky and difficult.
It is known that if the domain of t is a disc in the complex plane that contains the origin, then it may be impossible to parameterize the eigenvalues as continuity functions. If t belongs to a real interval or if all the eigenvalues are real, then there exists a selection of n continuous functions that are eigenvalues of A(t) for each t. (See Kato's book Perturbation Theory of Linear Operators.)
Note that eigenvalues are always continuous in the topological sense (i.e.
the map from matrices to their spectra is continuous). The roots continuity of polynomials is usually in this sense. The topological continuity and functional continuity of eigenvalues (roots) are related, but not the same.


Find order of element

Question: Hi i have a very basic problem with group theory.
1)I have x element, and i know that $|x^2|=5$ and i need to find order of x.
I see it like that : $(x^2,x^4,x^6,x^8,x^{10})$ so order of x is 10 because : $(x,x^2,x^3,x^4,x^5,x^6,x^7,x^8,x^9,x^{10})$ but in task i got it can be also 5, i don't see it so if you could show me specific group i would be more than glad
2) I have $Z_{17}^{*}$ and i know it's order is 16. How can i tell how elements that have 16 order are in it? (Other than manually counting for each)
Answer: A really simple example is inside the group $\mathbb Z/5\mathbb Z$.
$2$ has order $5$ since it generates: $2, 4, 1, 3, 0$.
but $2^2 = 4$ and it also has order $5$ since it generates: $4, 3, 2, 1, 0$.
Comment: Thanks a little clearer :)To clarify so if i have $|x^2|=n$ then row of x can be $n$ and $2n$? What about 2? How knowing order of group and of element tells me number of elements with same order?
Answer: For the first part, consider the additive group $\mathbb{Z}/5\mathbb{Z}$ and pick appropriate elements (try 1 and 2).
For the second, I'm not sure there's an elementary way to do it other than manually counting, but for a prime $p$, I believe the number of primitive roots (elements that generate the cyclic group) is $\phi(\phi(p))$, where $\phi$ denotes Euler's totient function, but I'm not sure of a basic proof of this off the top of my head.
Answer: The key result for both questions is

If $ord(x)=n$, then
  $
ord(x^k) = \dfrac{n}{(n,k)}
$

$ord(x^2)=5$ implies $n=5(n,2)$ and so $n=5$ or $n=10$. Both cases are possible.
If you know that $\mathbb Z_{17}^{\times}$ is cyclic of order $16$, then there are as many generators as $k$ such that $0\le k \le 15$, $(16,k)=1$ and so there are $\phi(16)=8$ generators.

Find order of element


htaccess multisite config crashed after sites move to other host

Question: I am on my long way to move my D6 site to other hosting company. It was hard but finally seems it's almost done but I am stacked on multisites configuration.
Situation is like this:
Drupal folder (from ftp/apache access point of view)

/webs/drupal/site  (main )
/webs/drupal/site/sites (multisites)

domains:

www.a.com
www.b.a.com

point to:

/webs/drupal/

/webs/drupal/.htaccess file
<code>#redirect to */site
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?b.a.com$
RewriteRule ^(/)?$ site [L]
RewriteCond %{HTTP_HOST} ^(www.)?a.com$
RewriteRule ^(/)?$ site [L]
</code>
/webs/drupal/site/.htaccess

it's standard D6 .htaccess with "always add 'www' prefix" rule on

The problem is that I can:

access default site using all combinations like www.a.com, a.com, a.com/site
access subsite like www.b.a.com/site

but all calls like:

www.b.a.com
b.a.com

redirects to the main site www.a.com/site ...
Any ideas?
Comment: I'm voting to close this question as off-topic because it's really more about writing htaccess files than about Drupal itself.
Comment: I opt, as htaccess is clean tested and working, the question here is why drupal do not call/see subsite but redirects to the main.
Comment: True enough. See [here](http://stackoverflow.com/a/5799393/2389310) and test what URL your site is actually "seeing". Put it in index.php (back up real index.php of course).
Comment: `REQUEST_URI: /site/

REDIRECT_URL: empty` in all cases, no deference for b.a.com or a.com. Have no idea what does it mean
Answer: It was a matter of the firefox cached data. After cleaning the cache it works.


Drush > ignore files and folders (ie : IDE conf) when pm-update

Question: Do you know if is there a way (by command argument, or in config) to ask drush not to remove IDE's configuration files and folder?
To be clear, Phpstorm create a .idea folder with project configuration in the root folder; when I run drush pm-update drupal, this folder is removed. Is there a way to ask drush to not delete this folder?
Comment: FWIW, I always have the base of my project one level up from Drupal root.  This way, my .idea, .git, Gruntfile, etc, don't have to live in DOCROOT and I never accidentally deploy them.
Comment: Yep, it could be a solution but how do you manage the cvs integration with phpstorm. The root of you repos is the drupal instance ? or the level up ?
Comment: All of my PHPStorm projects are in ~/Drupal, eg ~/Drupal/foo.com.  That is where the .idea and .git (or .svn) directory is.  ~/Drupal/foo.com/docroot has the actual site.
Answer: Nope.  Drush always does a full directory replacement when upgrading a module with pm-update.  This insures that any files removed from the release do not remain on the disk after the update.  Contributions to improve drush in this area would be appreciated.
As a workaround, if you have your .idea folder checked into git, then you could always use git checkout -- .idea after pm-update to get it back.
Comment: Ok, thanks, in order to collect advices and ideas about that, I've created a github issue : https://github.com/drush-ops/drush/issues/614
Answer: The same thing happened to me, then I remembered that drush restores the directory sites, so you could locate all your permanent files inside that folder. Another option is to recover them from the backup drush does when updating...
I hope this helps


Elemento visível mas ainda não clicavel

Question: Nos meus testes automatizados com selenium, possuo um método que espera o elemento por um determinado tempo, até que o elemento fique visível na tela (VisibilityOfAllElementsLocatedBy).
Porém, quando o elemento fica visível ele ainda não está clicável, estourando o erro no click. Acontece normalmente quando carrega o elemento, mas a página ainda está carregando.
Comment: Quando falo "ainda não está clicável" me refiro a habilitado para Clique. No meu caso fica a label de Carregando na frente da tela
Answer: Além de verificar se o elemento está visível através do método que você citou você pode verificar se o elemento já pode ser clicado através do método elementToBeClickable antes de chamar o método click. Use o wait para esperar o elemento ficar pronto. Veja um exemplo:
<code>private static WebDriver driver;
private static WebDriverWait wait;

driver = new chromeDriver();
wait = new WebDriverWait(driver, 10); //espera por dez sengundos

static By button = By.id("btnEnviar");

public static void clickButton{
    wait.until(ExpectedConditions.visibilityOfElementLocated(button));
    wait.until(ExpectedConditions.elementToBeClickable(button));
    driver.findElement(button).click();
}
</code>

Elemento visível mas ainda não clicavel


how can I add contextual links to each of the items in my view?

Question: I am creating a view in drupal and I need that each of the items of this view (are publications) have a contextual link to access more easily to edit this publication. I have tried adding {{title_suffix.contextual_links }} in the twig, however the contextual links appear one on top of the other and it doesn't allow to edit well.
I need help please
Answer: Rendering the links is only one half of the equation.
Contextual links are positioned absolutely. The easiest solution is to make sure that each item has the contextual-region class on it's wrapper.
I bet that your view has this wrapper, but none of your items do. The result is that all of the contextual links get positioned at the top right of your view rather than the top right of each item.
Comment: oh thank you very much, it worked great


Listar vários registros do MYSQL no email PHP para enviar tudo de uma vez

Question: Tenho um sistema imobiliário que lista vários registros do MYSQL. Estou com este código abaixo para que estes vários registros sejam enviados em um único email, porém ele só envia um registro.
Vejam o código:
<?php require_once('conexao.php'); ?>
<?php
$sqlxml = "select conta.dominio,conta.id,conta.modelo,imoveis.id,imoveis.cod,imoveis.titulo,imoveis.vvenda,imoveis.vtemporada,imoveis.vanual,imoveis.tipo,fotos.cod,fotos.foto,imoveis.descricao,imoveis.cidade, imoveis.data, imoveis.endereco, conta.nome, imoveis.dormitorio, imoveis.banheiro, imoveis.atotal, imoveis.areatotalmedida, imoveis.bairro from conta inner join imoveis on conta.id = imoveis.cod inner join fotos on fotos.cod=imoveis.id where imoveis.status='2' AND imoveis.vvenda < '500000' GROUP BY imoveis.id";
$rsqlxml = mysql_query($sqlxml)
or die ("Banco XML não abre!");

$quebra_linha = "\n";
$emailsender = "firstname.lastname@example.com";
$emailorigem = "firstname.lastname@example.com";
$assunto = "Roteiro do Imóvel - Sugestão de imóveis";

while($rowxml = mysql_fetch_array($rsqlxml))
{
    $mensagemHTML = "
    Id: ".$rowxml[3]. "

    Título: ".$rowxml[5]. "

    Categoria: ".$imvtipo. "

    Imóvel para: ".$tipodoimovel. "

    Valor: ".number_format($rowxml[6], 2, ',', ' '). "

    Cidade: ".$imvcidade. "

    Bairro: ".$mostrarbairroemail. "

    Descrição: ".$rowxml[12]. "

    Visualizar: ".$rowxml['0']."/".$rowxml['2']."/detalhes.php?idimovel=".$rowxml['3']."

    ";
 }

$headers = "MIME-Version: 1.1".$quebra_linha;
$headers .= "Content-type: text/html; charset=utf-8".$quebra_linha;
$headers .= "From: ".$emailorigem.$quebra_linha;
$headers .= "Return-Path: " . $emailorigem . $quebra_linha;
$headers .= "Reply-To: ".$emailsender.$quebra_linha;
$mailsend=mail($emailsender, $assunto, $mensagemHTML, $headers, "-r". $emailsender);
?>

O que foi feito de errado?
Answer: Só é enviado o último registro porque a cada volta no while $mensagemHTML tem seu valor rescrito.
Para resolver isso define a variável antes do while e faça a concatenação da string com .=
mude:
$mensagemHTML = "longo html";

Para:
$mensagemHTML = "";
while(...){
    $mensagemHTML .= "longo html";


How to convert SOAP request curl to RCurl

Question: How should I convert this one liner:
curl -d @request.xml -o response.xml http://www.sample.com/soap

It is accessing request xml which looks like this:
<?xml version="1.0" encoding="utf-8"?>
     <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://sample.com/">
    <soap:Body>
      <req:getEvents>
        <start>2014-12-12T00:00:00+0100</start>
        <end>2014-12-13T00:00:00+0100</end>
        <type>TYPE</type>
      </req:getEvents>
     </soap:Body>
    </soap:Envelope>

The response is written into response.xml
I would like to read the response directly into r
Comment: Have you looked into the `SSOAP` package?
Comment: possible duplicate of [SOAP request in R](http://stackoverflow.com/questions/26717706/soap-request-in-r)
Comment: Yes, I tried with SSOAP but it is throwing an "recursive error" at interface function which I do not understand and can not trace. No hints in the net available as well. So, now I am asking for a help to assemble the post request by hand with RCurl
Answer: Here's how with httr:
library(httr)
r <- POST("http://www.sample.com/soap", body = upload_file("request.xml"))
stop_for_status(r)
content(r)

Comment: Wow!!!! That's awesome! How cool, just an one liner, actually. This is doing exactly what I want. Thank you!


Field extensions of degree a composite number and subextensions

Question: Assume that $L/K$ is an extension of fields and $[L:K]=n$, with $n$ composite. Assume that $p\mid n$, can we always produce a subextension of degree $p$ and if not under what conditions can it be done? I would guess this is very false, but I couldn't come up with any trivial counterexamples.
Comment: If $L/K$ is Galois with a Galois group which is non-abelian and simple, then $2|n$ but there is no extension $K'/K$ contained in $L$ of degree $2.$
Answer: You are very right when you write "I would guess this is very false": here is a precise statement.
Proposition 1
For any $n\gt 1$ there exists a field extension  $\mathbb Q\subset K$ of degree $[K:\mathbb Q]=n  \:$  with no intermediate extension $\mathbb Q      \subsetneq k\subsetneq K$.
Proof
Let $\mathbb Q \subset L$  be  a Galois extension with Galois group $S_n$, the permutation group of $n$ elements .
The Galois correspondence associates to the subgroup $S_{n-1}\subset S_n$ an  extension $\mathbb Q \subset K$. The intermediate fields $\mathbb Q      \subsetneq k\subsetneq K$ bijectively correspond (by Galois theory again)
to intermediate subgroups $S_{n-1}\subsetneq  G\subsetneq S_n$. However an easy exercise in group theory shows that no such group exists and thus no intermediate field $k$ exists either.
An analogous problem
It is well known that   constructible numbers $c\in \mathbb C$ (those that can be constructed by straightedge and compass)  have degree a power of two: $[\mathbb Q(c):\mathbb Q]=2^r$ . However the converse is false :
Proposition 2
For every $n=2^r\geq 4$ there exists a non-constructible number $c\in \mathbb C$ which is not constructible even though it has degree $n=2^r$.
Proof
Take an irreducible  polynomial $P(X)\in \mathbb Q[X]$ whose Galois group is $S_n$. I claim that one of its roots $c $ is the required  nonconstructible number of degree $n$.
Else all its roots $c_1, ...,c_n$ would be constructible and  all the numbers of its splitting field $K=\mathbb Q(c_1,...,c_n)$ would be constructible too (the constructible numbers form a field).
But this is contradictory  because a primitive element $c_0$ of $K$  (i.e. $K=\mathbb Q(c_0$)) should then also have degree some power of $2$, whereas its degree is actually $n!$,  a number  divisible by $3$ since $n\geq 4$.
Bibliography
The existence of polynomials over  $\mathbb Q$ with Galois group $S_n$ is proved for example in Dummit-Foote's Abstract algebra, Chapter 14, Proposition 42.
Comment: Dear Georges: +1. A detail: Our friend pki (who asked the question) didn't require that the ground field be $\mathbb Q$. This makes it much easier to build a Galois extension with Galois group $S_n$. --- By the way, I noticed that Theorem 2.2 p. 4 in [these notes](http://www.math.uconn.edu/~kconrad/math316s08/galoisappn.pdf) of our friend Keith Conrad is very similar to your answer; but I like your wording very much!
Comment: Dear @Pierre-Yves, yes it is true, pki didn't require anything of the ground field .  I have added an illustration showing the interest of having polynomials over $\mathbb Q$ with Galois group $S_n$. Anyway, thanks a lot for your interest in this answer and the reference to Keith's handout.
Answer: We know that equations of degree 2 and 3 have solutions in radicals, but most equations of degree 6 (or any degree 5 or greater) don't. So let $f$ be a polynomial over $K$ of degree 6 not solvable in radicals, let $\alpha$ be a root of $f$ in some extension, let $L=K(\alpha)$. If there were an intermediate field $E$ of degree 2 or 3, then you could express $\alpha$ in radicals over $E$, and those radicals in radicals over $K$, contradicting the assumption that you couldn't solve $f$ in radicals over $K$.
Answer: Suppose $L/K$ is Galois with group $G$. Then subextensions of degree $m$ over $K$ correspond to normal subgroups of $G$ of index $m$. Given an abelian group you can always find subgroups of order $p$, where $p$ is a prime divisor of $\vert G \vert =n$. So to find a counterexample, you should (with $L/K$ Galois) start with non-abelian Galois groups.  I'm pretty sure there exists a group of order $n$ which doesn't have a normal subgroup of index $m$ for all $m\vert n$. (Note that if $m$ is prime, such a (not necesarily normal) subgroup exists).
Comment: Just subgroups. They don't have to be normal.


Amazon API signed requests isn't working properly

Question: Here's the code:
<code>import urllib2
import base64,hashlib,hmac,time
from urllib import urlencode
from xml.dom import minidom

AWS_ACCESS_KEY_ID = "secret"
AWS_SECRET_ACCESS_KEY = "secret"

base_url = "http://ecs.amazonaws.com/onca/xml"
url_params = {"Version": "2010-09-01",
              "Operation": "ItemSearch",
              "ResponseGroup": "Images",
              "SearchIndex": "Books",
              "Keywords": "Python",
              "AWSAccessKeyId": AWS_ACCESS_KEY_ID,
              "Service": "AWSCommerceService"
             }

# Add a ISO 8601 compliant timestamp (in GMT)
url_params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())

# Sort the URL parameters by key
keys = url_params.keys()
keys.sort()
# Get the values in the same order of the sorted keys
values = map(url_params.get, keys)

# Reconstruct the URL paramters and encode them
url_string = urlencode(zip(keys,values))
url_string = url_string.replace('+',"%20")
url_string = url_string.replace(':',"%3A")

#Construct the string to sign
string_to_sign = """GET
ecs.amazonaws.com
/onca/xml
%s""" % url_string

# Sign the request
signature = hmac.new(
            key=AWS_SECRET_ACCESS_KEY,
            msg=string_to_sign,
            digestmod=hashlib.sha256).digest()

# Base64 encode the signature
signature = base64.encodestring(signature)

# Make the signature URL safe
signature = signature.replace('+','%20')
signature = signature.replace('=','%3D')
signature = signature.replace(':','%3A')
url_string += "&Signature=%s" % signature

print "%s?%s" % (base_url,url_string)
</code>
When used with Django, i constantly get a 403 Forbidden error. When used without Django it sometimes works and sometimes doesn't. I have no idea what the cause of this might be.
Comment: Does it support the Product Advertising API?
Answer: Adam Cox has posted a nice example for signing request URLs: Page not found
Of course, you can just be lazy and use python-amazon-product-api.
If you need to use it on Google App Engine, look at this thread:
Using python-amazon-product-api on Google Appengine without lxml


PHP MVC: Too many dependencies in controller?

Question: I'm working on a personal HMVC project:

No service locators, no global state (like static or global), no singletons.
The model handling is encapsulated in services (service = domain objects + repositories + data mappers).
All controllers extend an abstract controller.
All project dependencies are injected through Auryn dependency injection container.

All needed dependencies are injected in the constructor of the abstract controller. If I want to override this constructor, then I have to pass all these dependencies in the child controller's constructor too.
class UsersController extends AbstractController {

    private $authentication;

    public function __construct(
        Config $config
        , Request $request
        , Session $session
        , View $view
        , Response $response
        , Logger $logger
        , Authentication $authentication // Domain model service
    ) {
        parent::__construct(/* All dependencies except authentication service */);
        $this->authentication = $authentication;
    }

    // Id passed by routing.
    public function authenticateUser($id) {
        // Use the authentication service...
    }

}

The dependencies list would further grow. This needs to change. So I was thinking about:

Totally separate controllers from views.
They would then share the service layer. The views wouldn't belong to controllers anymore and the Response would be a dependency of the views.
Use setter injection in controllersLike for Request, Session, Logger, etc;
Inject dependencies in the controller actionsOnly when needed.Like for Request, Session, Logger, etc;
Use decorator pattern.Like for logging after an action call.
Implement some factories.
To constructor inject only the needed dependencies only on child controllers.So not in AbstractController anymore.

I'm trying to find an elegant way to deal with this task and I'll appreciate any suggestions. Thank you.
Answer: I'll answer to my own question. When I wrote it I already had a good overview of what many experienced developers recommend regarding dependency injection in MVC and MVC structure.

The constructor injection is the proper option. But it seemed to
me that, following this line, I'll end up with too many
dependencies/arguments in constructors. Therefore giving controllers
too many responsibilities (reading the requested values, changing the
state of the domain objects, logging operations, requesting the view
to load the templates and to render the data, etc).
Setter injection was also a solution to take in consideration. But, in the course of the developing time on my project, I realised
that this solution really didn't fit (at least) into the picture of
my controller-view relationships.
The injection of the dependencies directly into the controller
actions caused me hard-time (but great time) too, having in mind
that I already had the url values injected as action arguments and
that I didn't used any routing dispatchers.
Implementing factories was also a great idea, in order to be able
to have objects at my disposal within each controller action.
Factories are a great tool to use, but only going from the premise of
needed run-time objects, not of just reducing the number of
dependencies in constructors.
Decorator pattern is also a good alternative. But if, for example, you want to log something within a controller action, then
this is not a solution: you still have to pass a logger as dependency
(in constructor, setter or action).
I had a thought about injecting the needed dependencies only on
child controllers. But then the problem of multiple
responsibilities of the corresponding controllers remains the same.

So, none of this solutions seemed to entirely fit into the structure of my HMVC project, whatever I did. So, i dug further, until I realised what the missing link was. For this I give my whole appreciation to Tom Butler, the creator of the following great articles:

Model-View-Confusion part 1: The View gets its own data from the
Model
Model-View-Confusion part 2: MVC models are not domain
models

His works are based on an in-depth, well argumented analyse of the MVC concepts. They are not only very easy to follow, but also sustained by self-explanatory examples. In a word: a wonderful contribution to the MVC and developer community.
What I'll write further is meant to be just a presentation of his principles with my own words, having in mind to somehow complete them, to provide a compacter perspective of them and to show the steps followed by me when I implemented them in my project. All credit on the subject, ideas and principles and workflows depicted here goes to Tom Butler.
So, what was the missing link in my HMVC project? It's named SEPARATION OF CONCERNS.
For simplicity I'll try to explain this by referring myself to only one controller, one controller action, one view, one model (domain object) and one template (file), introducing them into a User context.
The MVC concept most described on web - and also implemented by some popular frameworks that I studied - is centered around the principle of giving the controller the control over the view and the model. In order to display something on screen you'll have to tell that to the controller - he further notifies the view to load and render the template. If this display process implies the use of some model data too, then the controller manipulates the model too.
In a classical way, the controller creation and action calling process involve two steps:

Create the controller - passing it all dependencies, view inclusive;
Call the controller action.

The code:
$controller = new UserController(/* Controller dependencies */);

$controller->{action}(/* Action dependencies */);

This implies, that the controller is responsible for, well, everything. So, no wonder why a controller must be injected with so many dependencies.
But should the controller be involved in, or responsible for effectively displaying any kind of information on the screen? No. This should be the responsibility of the view. In order to achieve this let's begin separating the view from the controller - going from the premise of not needing any model yet. The involved steps would be:

Define an output method for displaying information on screen in the
view.
Create the controller - passing it all dependencies, excepting the
view and its related dependencies (response, template object, etc).
Create the view - passing it the corresponding dependencies
(response, template object, etc).
Call the controller action.
Call the output method of the view:

And the code:
class UserView {
    //....
    // Display information on screen.
    public function output () {
        return $this
                    ->load('<template-name>')
                    ->render(array(<data-to-display>))
        ;
    }
    //....
}

$controller = new UserController(/* (less) controller dependencies */);
$view = new UserView(/* View dependencies */);

$controller->{action}(/* Action dependencies */);
echo $view->output();

By accomplishing the five upper steps we managed to completely decouple the controller from the view.
But, there is an aspect, that we hypothesised earlier: we did not made use of any model. So what's the role of the controller in this constellation then? The answer is: none. The controller should exist only as a middlemann between some storage place (database, file system, etc) and the view. Otherwise, e.g. only to output some information in a certain format on screen, is the output method of the view fully sufficient.
Things change if a model is beeing brought on the scene. But where should it be injected? In the controller or in the view? In both. They share the same model instance. In this moment the controller gains the role of the middleman - between storage and view - in his own right. A theoretical form would be:
$model = new UserModel;
$controller = new UserController($model, /* Other controller dependencies */);
$view = new UserView($model, /* Other view dependencies */);

$controller->{action}(/* Action dependencies */);
echo $view->output();

Doing so, the controller can change the state of the model and ensure that it's saved in the storage system. The same model instance, respective its state, is read by the view and displayed. The controller passes display logic informations to the view through the model. The problem is, that these informations don't belong to the business logic, which a model is supposed to exclusively have. They are only display logic participants.
In order to avoid giving display logic responsibilities to the model, we have to introduce a new component in the picture: the view-model. Instead of sharing a model object, the controller and the view will share a view-model instance. Only this one will receive the model as dependency. An implementation:
$model = new UserModel;
$viewModel = new UserViewModel($model, /* Other view-model dependencies */);
$controller = new UserController($viewModel /* Other controller dependencies */);
$view = new UserView($viewModel, /* Other view dependencies */);

$controller->{action}(/* Action dependencies */);
echo $view->output();

And the workflow can be described like this:

The request values are sent by the browser ("the user") to the
controller.
The controller stores them in the view-model instance as properties
(data members), therefore changing the display logic state of the
view-model.
Within its output method, the view reads the values from the
view-model and requests the model to query the storage on their
basis.
The model runs the corresponding query and passes the results back to
the view.
The view reads and passes them to the corresponding template.
After template rendering, the results are displayed on the screen.

The view-model does not belong to the domain model, where all domain objects reside and the real business logic takes place. It does also not belong to the service layer, which manipulates the domain objects, repositories and data mappers. It belongs to the application model, e.g to the place where the application logic takes place. The view-model obtains the sole responsibility of gaining display logic state from the controller and conducting it to the controller.
As can be seen, only the view-model "touches" the model. Both, the controller and the view were not only completely decoupled from each other, but also from the model. The most important aspect of this approach is, that each of all the components involved gains only the responsibilities, that it is supposed to gain.
By making use of this kind of component separation and of a dependency injection container, the problem of too many dependencies in controllers vanishes. And one can apply a combination of all options presented in my question in a really flexible manner. Without having in mind that one of the components (model, view or controller) gains too many responsibilities.


Unknown provider returned from registerWithProvider

Question: I am trying to create a custom auth provider called "cgpsauth" and I am getting "Unknown provider" when I call:
  var ru = Realm.Sync.User.registerWithProvider(
        "http://localhost:9080",
        "cgpsauth",
        accessToken,
        (error, user) => {...

Here is my provider which I know is being loaded because if I make a syntax error in this file I get an error when I launch the ROS:
module.exports = function(deps) {
  return class CgpsAuthProvider extends deps.BaseAuthProvider {

    static get name() {
      return 'custom/cgpsauth';
    }

    constructor(name, options, requestPromise) {
      super(name, options, requestPromise);
    }

    verifyIdentifier(req) {
      const token = req.body.data;
      return 30;
    }
  }
};

configuration.yml
 providers:
     custom/cgpsauth:
      implementation: cgpsauth.js

Answer: You have to prefix the provider name when authenticating from the client SDK with custom/:
var ru = Realm.Sync.User.registerWithProvider(
    "http://localhost:9080",
    "custom/cgpsauth",
    accessToken,
    (error, user) => {...


What is the relationship between momentum method for gradient descent defined in machine learning and the momentum defined in physics

Question: The momentum method for gradient descent in machine learning is defined as
$$
\begin{array}{l}
\mathbf{v}_{t} \leftarrow \beta \mathbf{v}_{t-1}+\mathbf{g}_{t-1} \\
\mathbf{x}_{t} \leftarrow \mathbf{x}_{t-1}-\eta_{t} \mathbf{v}_{t}
\end{array}
$$
where $\mathbf{g}$ is the gradient.
While the momentum in physics is defined as:
$$
p=mv
$$
where $m$ is the mass and $v$ is the velocity.
I don't see how the above two equations are mathematically connected. Does the term momentum have a totally different meaning in machine learning from it does in physics?
Answer: The physics concept which optimization "momentum" maps best to is drag. For example, if $\beta = 1$, then there is no damping, and you get something very close to the classic laws of motion ($x_t = x_{t-1} + v\cdot dt, v_t = v_{t-1} + \frac{F}{m} \cdot dt$). On the other hand, if $\beta = 0$, it's as if there's a drag force $F'$ acting in the opposite direction of $v_t$, just strong enough to "cancel out" the previous velocity, so that $v_t = (v_{t-1} - \frac{F'}{m} dt)
 + \frac{F}{m} dt = \frac{F}{m} dt $. Since $F' \propto v_{t-1}$, it seems appropriate to call this drag, since drag does scale linearly with velocity in many cases.


CSS/JS Overlay Zoom Problems

Question: I've got problems regarding my image gallery site that uses PhotoZoom Javascript (Zooms image during mouseover). Hope you guys can help me out.
Problem:
The photozoom javascript works perfectly during mouseover event. However the zoomed image is under the other images. I've tried manipulating the Z-INDEX in the CSS but nothing worked. What could be the possible solution to see the zoomed image above everything else?
Thanks for helping!
Answer: I've added some css which helped me,

Try adding this code in your documents  section.
and here is output of same:

Hope it helps! cheers :).
Comment: Should be `z-index:100 !important;` :)
Comment: Thanks @misterManSam, But it can even work without `!important`.
Comment: @emotheraphy, I'm glad that I could help you.
Comment: Thanks also to you @misterManSam more power to both of you. :)

CSS/JS Overlay Zoom Problems


SBS 2008 SP2 Backup - Volume Shadow Copy Operation Failed

Question: Server Setup
Exchange 2007 Version: 08.03.0192.001 (Rollup 4)
Windows Small Business Server 2008 SP2 (Rollup 5)
Exchange set up on D: drive (449 GB / 698 GB Free)
80 GB / 148 GB Free on OS drive.
Issue
Backup Failure (VSS related)
Backup Software
Windows Server Backup (ver 1.0)
Simplified Error
Creation of the shared protection point timed out.
Unknown error (0x81000101)
The flush and hold writes operation on volume C: timed out while waiting for a release writes command.
Volume Shadow Copy Warning: VSS spent 43 seconds trying to flush and hold the volume \?\Volume{b562a5dd-8246-11de-a75b-806e6f6e6963}.  This might cause problems when other volumes in the shadow-copy set timeout waiting for the release-writes phase, and it can cause  the shadow-copy creation to fail.  Trying again when disk activity is lower may solve this problem.
What I've tried

Server Reboot.
Updated Server and Exchange.
ReConfigured Sharepoint (Helped resolve last vss error I encountered).
registered VSS Dll's (Backups will sometimes work afterwards but VSS writers fail soon after).
Tried Implementing Hotfix:  http://support.microsoft.com/kb/956136
Tried Implementing Hotfix: http://support.microsoft.com/kb/972135
I left it for a few days and a few backups came through but then began to fail again.

Detailed Information
Log Name:      Application
Source:        VSS
Date:          16/11/2011 8:02:11 PM
Event ID:      12341
Task Category: None
Level:         Warning
Keywords:      Classic
User:          N/A
Computer:      SERVER.DOMAIN.local
Description:
Volume Shadow Copy Warning: VSS spent 43 seconds trying to flush and hold the volume \?\Volume{b562a5dd-8246-11de-a75b-806e6f6e6963}.  This might cause problems when other volumes in the shadow-copy set timeout waiting for the release-writes phase, and it can cause  the shadow-copy creation to fail.  Trying again when disk activity is lower may solve this problem.
Operation:
   Executing Asynchronous Operation
Context:
   Current State: flush-and-hold writes
   Volume Name: \?\Volume{b562a5dd-8246-11de-a75b-806e6f6e6963}\
Event Xml:

    12341
    3
    0
    0x80000000000000

    1651049
    Application
    SERVER.DOMAIN.local

    43
    \?\Volume{b562a5dd-8246-11de-a75b-806e6f6e6963}\

Operation:
   Executing Asynchronous Operation
Context:
   Current State: flush-and-hold writes
   Volume Name: \?\Volume{b562a5dd-8246-11de-a75b-806e6f6e6963}\
=================================================================================
Log Name:      System
Source:        volsnap
Date:          16/11/2011 8:02:11 PM
Event ID:      8
Task Category: None
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      SERVER.DOMAIN.local
Description:
The flush and hold writes operation on volume C: timed out while waiting for a release writes command.
Event Xml:

    8
    2
    0
    0x80000000000000

    987135
    System
    SERVER.DOMAIN.local
==================================================================================
Log Name:      Application
Source:        Microsoft-Windows-Backup
Date:          16/11/2011 8:11:18 PM
Event ID:      521
Task Category: None
Level:         Error
Keywords:
User:          SYSTEM
Computer:      SERVER.DOMAIN.local
Description:
Backup started at '16/11/2011 9:00:35 AM' failed as Volume Shadow copy operation failed for backup volumes with following error code '2155348001'. Please rerun backup once issue is resolved.
Event Xml:

    521
    0
    2
    0
    0
    0x8000000000000000

    1651065

    Application
    SERVER.DOMAIN.local

    2011-11-16T09:00:35.446Z
    2155348001
    %%2155348001

==================================================================================
Writer name: 'FRS Writer'
   Writer Id: {d76f5a28-3092-4589-ba48-2958fb88ce29}
   Writer Instance Id: {ba047fc6-9ce8-44ba-b59f-f2f8c07708aa}
State: [5] Waiting for completion
   Last error: No error
Writer name: 'ASR Writer'
   Writer Id: {be000cbe-11fe-4426-9c58-531aa6355fc4}
   Writer Instance Id: {0aace3e2-c840-4572-bf49-7fcc3fbcf56d}
   State: [1] Stable
   Last error: No error
Writer name: 'Shadow Copy Optimization Writer'
   Writer Id: {4dc3bdd4-ab48-4d07-adb0-3bee2926fd7f}
   Writer Instance Id: {054593e2-2086-4480-92e5-30386509ed1b}
   State: [1] Stable
   Last error: No error
Writer name: 'Registry Writer'
   Writer Id: {afbab4a2-367d-4d15-a586-71dbb18f8485}
   Writer Instance Id: {840e6f5f-f35a-4b65-bb20-060cf2ee892a}
   State: [1] Stable
   Last error: No error
Writer name: 'COM+ REGDB Writer'
   Writer Id: {542da469-d3e1-473c-9f4f-7847f01fc64f}
   Writer Instance Id: {9486bedc-f6e8-424b-b563-8b849d51b1e1}
   State: [1] Stable
   Last error: No error
Writer name: 'BITS Writer'
   Writer Id: {4969d978-be47-48b0-b100-f328f07ac1e0}
   Writer Instance Id: {29368bb3-e04b-4404-8fc9-e62dae18da91}
   State: [1] Stable
   Last error: No error
Writer name: 'Dhcp Jet Writer'
   Writer Id: {be9ac81e-3619-421f-920f-4c6fea9e93ad}
   Writer Instance Id: {cfb58c78-9609-4133-8fc8-f66b0d25e12d}
State: [5] Waiting for completion
   Last error: No error
==================================================================================
Answer: I ran the following in an elevated Command Prompt and this resolved it (if needed script it to run before each backup)
<code>Takeown /f %windir%\winsxs\temp\PendingRenames /a
icacls %windir%\winsxs\temp\PendingRenames /grant "NT AUTHORITY\SYSTEM:(RX)"
icacls %windir%\winsxs\temp\PendingRenames /grant "NT Service\trustedinstaller:(F)"
icacls %windir%\winsxs\temp\PendingRenames /grant BUILTIN\Users:(RX)
Takeown /f %windir%\winsxs\filemaps\* /a
icacls %windir%\winsxs\filemaps\*.* /grant "NT AUTHORITY\SYSTEM:(RX)"
icacls %windir%\winsxs\filemaps\*.* /grant "NT Service\trustedinstaller:(F)"
icacls %windir%\winsxs\filemaps\*.* /grant BUILTIN\Users:(RX)

net stop cryptsvc
net start cryptsvc
</code>


How to change html of CAPTCHA module in another module?

Question: I add captcha field to form in this way
$form['captcha'] = array(
    '#type' => 'captcha',
    '#title' => 'Simple title',
    '#captcha_type' => 'captcha/Math',
    '#description' => 'Please solve it'
);

This element will be rendered as
<fieldset class="captcha form-wrapper"><legend>CAPTCHA</legend>

Please solve it
<input type="hidden" name="captcha_sid" value="102">
<input type="hidden" name="captcha_token" value="bf6179f1c98e4291e1bb2e11c733d991">

  Math question *
 20 + 0 =  <input type="text" id="edit-captcha-response" name="captcha_response" value="" size="4" maxlength="2" class="form-text required" autocomplete="off">

Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.

</fieldset>

How to change this html template ?
Answer: I guess you could override theme_captcha. here is the code
function bartik_captcha($variables){
  $element = $variables['element'];
  $output='
'.$element['#title'].'
';
  $output.= drupal_render_children($element);
  return $output;
}


Subparser -- show help for both parser and subparser

Question: I've looked through dozens of similar SO questions but haven't find suitable solutions so please forgive me in case of a dublicate.
I have a problem similar to this one
I want to have a parser+subparser pair, with --help option causing help being shown for the both if subparser is "activated".
The only way I was able to get full (parser + subparser) help is:
common_parser = argparse.ArgumentParser(add_help=False)
common_parser.add_argument('-c', required = True)
parser = argparse.ArgumentParser(parents=[common_parser])
subparsers = parser.add_subparsers(dest="sub")
subparser = subparsers.add_parser("sub_option", parents=[common_parser])
subparser.add_argument('-o', required = False)
settings = parser.parse_args()

But then script requires the -c option to be entered twice (apparently for parser and subparser). If I don't use parents then I get normal behaviour but I don't the help I get for subparser contains only -o description (I want also -c to be shown)
P.S. Python 2.7
Answer: For a start let's distinguish between parsing behavior and help display.
I assume you have multiple subparsers (otherwise why use the subparser mechanism).  -o is an argument specific to sub_option, and presumably the other subparsers have their own arguments.
What is the purpose of -c?  Is it something that is common to all subparsers?  Since subparsers are required, it doesn't make sense to talk about an argument that only matters to the main parser.
One way to deal with a common argument is to define it for all subparsers.  The parents mechanism that you use saves you a bit of typing.  Just omit it from the main parser definition.  That gets rid of the problem with having to supply it twice.
If -c is defined for all the subparsers, then there isn't a need to show it in the main parser help, is there?
The whole subparser mechanism is cleanest when the subparser command is the 1st argument string, with all of its arguments, positionals and options following.  It's possible to define arguments for the main parser, but it often complicates both use and help.
The issue of display the help for both the main parser and (all) the subparsers has come up before, both on SO, and on the python bug/issues.  There isn't a simple solution.  Some tools that may help are:

generate help under program control with parser.print_help(), and subparse.print_help().
add_subparsers() command takes parameters like prog, title and description which can be used to control the help, including the usage of the subparser help.
add_subparser() takes the same sort of parameters as ArgumentParser (since it defines a parser), description and usage may be useful.

Looking a previous question
How to show help for all subparsers in argparse?
I realized that if -c is not required, it can be defined for both the main and subparser, and appear as expected in the helps.  But by making it 'required', both parsers have to see it - but only the value seen by the subparser appears in the namespace.
Also positionals defined in the main parser appear in the subparser usage.
Another subparsers help display question
argparse subparser monolithic help output

http://bugs.python.org/issue20333 argparse subparser usage message hides main parser usage  discusses the question of how much of main parser usage should show up in the subparse usage line.  Currently just positionals (defined before the subparsers) show up.  In the patch I suggest adding required optionals as well.  But you can always fudge this by defining your own prog for subparsers.


Solving the system $\sin\theta\,(A+\cos\phi)=\cos\theta\,(B+\sin\phi)$, $\sin\phi\,(C+\cos\theta)=\cos\phi\,(D+\sin\theta)$

Question: Is there an easy way to solve the following system of trigonometric equations (that is, to find $\theta$ and $\phi$)? A,B,C, and D are known constants.
$$\sin\theta\,(A+\cos\phi)=\cos\theta\,(B+\sin\phi)$$
$$\sin\phi\,(C+\cos\theta)=\cos\phi\,(D+\sin\theta)$$
All I can think of is to derive $\tan\theta$ in terms of $\phi$ from the first equation, and then plug it into the second equation, but then I'd come up with a complicated equation (although with only one variable). So I am wondering if there is a simpler method to do it. Thanks!
Comment: I'm also getting a complicated equation (a polynomial of degree six). Is there reason to believe there should be a "nice" answer? Is there some relation among $A$, $B$, $C$, $D$ that you haven't mentioned? ... It might help if you told how the system arose. Is it a textbook exercise? an online challenge? something of your own?
Comment: This is actually the simplified form of another system of equations that I encountered when trying to model a wireless network. A, B, C, and D are functions of (many of) the system parameters but there is no simple relation between them.
Comment: Is this $$\sin(\theta(A+cos(\phi))$$ etc?
Comment: No, it's sin$(\theta)$ .($A$+cos$(\phi))$
Answer: One partial answer (really a comment too long for the comment box) in the more general case where $A^2 + B^2 \neq C^2 + D^2$. The system can be recast as
\begin{align*}
\sin \theta \cos \phi - \cos \theta \sin \phi &= B \cos \theta - A \sin \theta \\
\sin \theta \cos \phi - \cos \theta \sin \phi &= C \sin \phi - D \cos \phi
\end{align*}
The LHS of both equations is $\sin (\theta - \phi)$, and each RHS can be rewritten with the help of phasor diagrams as
\begin{align*}
-A \sin \theta + B \cos \theta &= \sqrt{A^2 + B^2} \sin \left(\theta + \frac{\pi}{2} + \arctan \frac{A}{B}\right) \\
C \sin \phi - D \cos \phi &= \sqrt{C^2 + D^2} \sin\left(\phi - \arctan \frac{C}{D}\right)
\end{align*}
and equating these quantities may least may simplify the task of finding a solution numerically, but I doubt an analytic solution is possible.
Answer: I started with an assumption of $ A^2+B^2=C^2+D^2$. Here's what I came up with,
$\sin\theta(A+\cos\phi)= \cos\theta(B+\sin\phi) \Rightarrow A\sin\theta-B\cos\theta=-\sin(\theta-\phi) \ldots  (1)$
Similarly $C\sin\phi-D\cos\phi = \sin(\theta-\phi) \ldots (2)$.
$\therefore (1)$ & $(2)$ together give $A\sin\theta-B\cos\theta= D\cos\phi-C\sin\phi$ $ \Rightarrow \sin(\theta-\theta_1)=\sin(\phi_1-\phi) \ldots (3)$, where both $\theta_1$ and $\phi_1 $ are known because $A,B,C,D$ are known, namely $\tan\theta_1=\frac{B}{A}$ and $\tan\phi_1=\frac{D}{C}$.
Now the solution of equation $(3)$ gives $\theta-\theta_1=\phi_1-\phi$ (Discarding any general solution). It implies $\theta= \phi_1+\theta_1-\phi \ldots (4)$
Substituting the value of $\theta$ in $(2)$ gives  $\sin(\phi-\phi_1)=\sin(\phi_1+\theta_1-2\phi) \Rightarrow \phi=\frac{1}{3}(2\phi_1+\theta_1).$ Value of $\theta$ can be found from $(4)$. Here I did not consider any general solution because ranges of $\theta$ and $\phi$ are not specified.
Answer: I find it numerically easier to solve this equivalent pairs:
$$\sin(\theta-\phi) = -A \sin(\theta) + B \cos(\theta)$$
$$\sin(\theta-\phi) = C \sin(\phi) - D \sin(\phi) $$
If A,B are constants, convert (-A,B) to angle notation, $r_\theta ∠ γ_\theta $
If C,D are constants, do the same: (C,-D) → $r_\phi ∠ γ_\phi $
Let $x=\theta-\phi, \text{we have } \sin(x) =  r_\theta \sin(\theta + γ_\theta) = r_\phi \sin(\phi + γ_\phi)$
$$\theta = \sin^{-1}({ \sin(x) \over r_\theta}) - γ_\theta   $$
$$\phi = \sin^{-1}({ \sin(x) \over r_\phi}) - γ_\phi   $$
You can guess the gap of angles, x, solve for the 2 angles, and try the new gap.
Example, say A=1, B=4, C=7, D=8
x $= +0.0000, \text{ we get } \theta≈-1.8158, \phi≈0.8520$
x $ = -2.6678, \text{ we get } \theta≈-1.9267, \phi≈0.8090$
x $= -2.7357, \text{ we get } \theta≈-1.9117, \phi≈0.8148$
x $= -2.7265, \text{ we get } \theta≈-1.9137, \phi≈0.8140$
x $= -2.7277, \text{ we get } \theta≈-1.9135, \phi≈0.8141$
x $= -2.7276, \text{ we get } \theta≈-1.9135, \phi≈0.8141$

We can speed up convergence with Newton's method:
$$f(x)= \theta-\phi-x= \{\sin^{-1}({ \sin(x) \over r_\theta}) - γ_\theta\} - \{ \sin^{-1}({ \sin(x) \over r_\phi}) - γ_\phi \} - x $$
$$f'(x)=\large \cos(x) \left({1 \over \sqrt{r_\theta^2-\sin(x)^2}} - {1 \over \sqrt{r_\phi^2-\sin(x)^2}}\right) -1 $$
For the same example, iterate with $x = x - \large{f(x) \over f'(x)}$:
+0.0
-3.13285623900302
-2.72899493772358
-2.72760870383572
-2.72760865698240 $ → (\theta,\phi) = (-1.91349280095738, 0.81411585602502)$
Comment: is there a reason that these steps would converge to the solution? I mean, does it have any advantage over random guessing?
Comment: Can you show what you meant by random guessing ?
Comment: I mean just trying different values of $\theta$ and $\phi$ over and over again until the both equations hold. Does your method provide a faster way to solve the equations?
Comment: Fixed point iterations for the angles, convergence is not very fast.  For my example, about 1 decimal digits gain per iteration.  I tried Newton's method (added to my answer), convergence is much faster.
Comment: I don't know why but, using your numbers, I don't get the same numerical result.
Comment: For (A,B,C,D)=(1,4,7,8), there are multiple solutions.  Limiting angles inside ± pi, this is what I found so far: (θ,ϕ) = (-1.9135, 0.8141), (-1.6611, -2.3494), (1.2411, 0.8848).
Comment: @albertchan. You are very correct and I am ... stupid ! Cheers :-(
Comment: Can you provide an iterative numerical solution if the second main equation was replaced by $sin\phi (C+cos\theta)= -cos\phi (D+sin\theta)$?
Comment: Why not use @ClaudeLeibovici f(ϕ), but flip the sign before D?
Comment: (A,B,C,D)=(1,4,7,8), angles within ± pi, I think there are 4 solutions. (θ,ϕ) = (-1.9135, 0.8141), (-1.6611, -2.3494), (1.2411, 0.8848), (1.4534, -2.2403)
Comment: Does the iterative numerical method guarantee to find all the solutions (say, within ±pi)?
Comment: Since f(x) = θ - ϕ - x, and  (θ,ϕ) involve asin, to get full solutions, you had 2*2 = 4 f's to solve, thus 4 solutions. My answer only do the principle asin angle.  But, try θ = (pi - asin(sin(x)/r(θ))) - γ(θ), and solve f(x)=0, you would get @ClaudeLeibovici solution.
Answer: I think that you initial idea is worth to use.
From the first equation
$$\theta=\tan ^{-1}\left(\frac{B+\sin (\phi )}{A+\cos (\phi )}\right)$$ which means that we look for the zero of
$$f(\phi)=\left(C+\frac{1}{\sqrt{x^2(\phi)+1}}\right) \sin (\phi
   )-\left(D+\frac{x(\phi)}{\sqrt{x^2(\phi)+1}}\right) \cos (\phi )$$ where $x(\phi)=\frac{B+\sin (\phi )}{A+\cos (\phi )}$
Using $A=1$, $B=4$, $C=7$, $D=8$ as albert chan did and using Newton method, the iterates are
$$\left(
\begin{array}{cc}
 n & \phi_n \\
 0 & 0.00000000 \\
 1 & 1.20154495 \\
 2 & 0.87333496 \\
 3 & 0.88478716 \\
 4 & 0.88478758
\end{array}
\right)$$ from which $\theta=1.24111220$.
As I wrote in comments, I do not know why our solutions are different.
For sure, the analytical expression of $f'(\phi)$ would be quite messy but using central differences will not make any problem.


CRC error in several compressed files

Question: I have a server which backs up itself on another server with duplicity (actually duply). The full backup is about 330 1-GB files. The full backup finished without problems, but the next day the incremental terminated with "CRC check failed". On the backup server several files appear to have a problem:
# gzip *20170530* --test

gzip: duplicity-full-signatures.20170530T032515Z.sigtar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol139.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol139.difftar.gz: invalid compressed data--length error

gzip: duplicity-full.20170530T032515Z.vol146.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol169.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol171.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol171.difftar.gz: invalid compressed data--length error

gzip: duplicity-full.20170530T032515Z.vol193.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol223.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol224.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol233.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol301.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol310.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol310.difftar.gz: invalid compressed data--length error

gzip: duplicity-full.20170530T032515Z.vol53.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol53.difftar.gz: invalid compressed data--length error

gzip: duplicity-full.20170530T032515Z.vol63.difftar.gz: invalid compressed data--crc error

gzip: duplicity-full.20170530T032515Z.vol63.difftar.gz: invalid compressed data--length error

If only one file had an error I'd just retry hoping it would be a random error. But... 13 files with error? How should I debug this?
Both servers are Debian 8. Duplicity is 0.6.24, installed with apt; the same thing with all dependencies, with the exception of paramiko, for which 1.16.0 has been installed.
The main server's logs do show some SATA stuff, but would this result in silently corrupting files? Wouldn't the full backup have stopped with an I/O error or something? Here's an example of stuff written in the log:
May 31 06:49:11 acheloos kernel: [1887359.720042] ata3.00: exception Emask 0x50 SAct 0x40000 SErr 0x280900 action 0x6 frozen
May 31 06:49:11 acheloos kernel: [1887359.720472] ata3.00: irq_stat 0x08000000, interface fatal error
May 31 06:49:11 acheloos kernel: [1887359.720870] ata3: SError: { UnrecovData HostInt 10B8B BadCRC }
May 31 06:49:11 acheloos kernel: [1887359.721255] ata3.00: failed command: READ FPDMA QUEUED
May 31 06:49:11 acheloos kernel: [1887359.721639] ata3.00: cmd 60/40:90:ac:3b:d8/00:00:2e:00:00/40 tag 18 ncq 32768 in
May 31 06:49:11 acheloos kernel: [1887359.721639]          res 40/00:94:ac:3b:d8/00:00:2e:00:00/40 Emask 0x50 (ATA bus error)
May 31 06:49:11 acheloos kernel: [1887359.722430] ata3.00: status: { DRDY }
May 31 06:49:11 acheloos kernel: [1887359.722927] ata3: hard resetting link
May 31 06:49:11 acheloos kernel: [1887360.040025] ata3: SATA link up 3.0 Gbps (SStatus 123 SControl 300)
May 31 06:49:11 acheloos kernel: [1887360.041846] ata3.00: configured for UDMA/133
May 31 06:49:11 acheloos kernel: [1887360.041859] ata3: EH complete

Comment: Why the downvote?!
Answer: May 31 06:49:11 acheloos kernel: [1887359.720870] ata3: SError: { UnrecovData HostInt 10B8B BadCRC }

This sums it up, a unrecoverable error occurred and some data was lost.  How many drives do you have in the host? The usual cause is a bad drive, so the first step would be to replace that and then move on to RAM and then the controller itself (via the motherboard).
You could also query the SMART data from the drives with smartctl --health /dev/sda (change the drive name) and smartctl --all /dev/sda; https://www.faqforge.com/linux/get-the-disk-health-status-with-smart-monitor-tools-on-debian-and-ubuntu-linux/ describes that in more detail. You are looking for any incrementing error counters.
You can test if it is the drive by making a backup to an alternate drive and see if those files show corruption.  You might also run badblocks (https://linux.die.net/man/8/badblocks) to see if the existing drive has issues. If you can vacate the drive first then the destructive test is better, but is more work.
At this point if the backups you are making of the drive are being corrupted its quite possible the existing data is also corrupted. You'll want to consider your recovery scenario if the existing data is bad.
It is a little odd that this did not bubble up through your backup tool into an error, though it is possible it is ignoring them.
Comment: I have three disks that form a soft RAID5 array. `smartctl` doesn't show any error. If the drive had an error the RAID would fix it, and if it couldn't, I'd get an I/O error, not silent corruption (on 13 files!). Anyway I shutdown the machine and started it again. After it has come up the only fishy thing I see so far is a CPU usage of 5-15% by `ksoftirq` (but `/proc/interrupts` shows something like 100 interrupts per second, which I take is normal).

CRC error in several compressed files


Using forms API - sending submitted data as an XML attachment to an email address

Question: I need to have a request form on a D7 site which does a few different things with the form data:

Writes to database table (standard);
Emails a copy of the form data to a site administrator on a pre-defined email address;
Creates a XML file attachment in a prescribed format (not valid XML, so possibly best being a template with placeholder values being replaced by form data) which is also attached to the email to administrator.

The generation of the XML is currently working fine in a bespoke PHP system and I'm thinking for ease re-using the functionality would make good sense.
However, is there a simple way to hook this into the submit process for the Drupal form? I believe using the Forms API may be the best approach?
Answer: Just implement the hook_form_alter or hook_form_FORM_ID_alter and add your custom submit handler.
See this article for an intro into hooking into forms:
http://websmiths.co/blog/very-introduction-drupals-hookformalter


What actually changes in related scales?

Question: I'm a guitar newbie, and I've only been taking lessons for about 2 months now. My goal is to rock out on an electric guitar - for the time being, I have a cheap classical one.
Thus far I've been playing scales (pentatonic included) along the whole neck of the guitar. To be frank, this gets somewhat boring after a while. My teacher hasn't really touched on chords yet aside from some really basic theory.
As such, please forgive me if the question is just lame or if I'm using some terminology wrong.
If I'm looking at this right, the C major (which is the most basic scale, if I understand it correctly) and A minor scales use the same notes. I used this site to double-check - the root note is different, but otherwise the scales look exactly alike.
If I got a backing track in A-minor and want to improvise, do I need to play this any differently, assuming I'm not using chords at all yet? What actually changes in between these scales?
Comment: There is not a 'most basic chord' - but what you should do is look at the questions tagged [tag:modes] - and you will see what the changes are. Basically for these two it is simply where you start the scale from.
Comment: In the long run, Chords, Scales & Arpeggios are all one and the same, just organized differently, i.e. scales in 2nd's, Arpeggios in 3rd's (remove every other note of the scale, "2-4-6" and move them up an octave to be the 9-11-13 i.e. 1-3-5-7-9-11-13), of course we are limiting this example to 7-note "diatonic" scales (modes), there are other permutations that seem more complex when first starting out than they really are... until you see the larger internal logical consistency... in the end, everything we do just involves organization (re-organization) of the same 12 chromatic notes.
Comment: Be careful to not fall into the trap of practicing the same scale over and over again, just starting and stopping on a different scale tone thinking that you are practicing "modes", you aren't, you would just be playing the same scale, starting and stopping on different scale tones. To really get the concept and understand the usage of "modes" (like the major and minor scale, i.e. Ionian & Aeolian modes), you have to have some kind of harmonic context to play them against, this will make more sense as your teacher expands on chord theory... but in the end, it's almost all I & V (simplified).
Answer: C major and A minor scales contain the same notes, but those notes take on different roles.
The root note is the "home" of the melody - often the melody begins or ends on the root note, but even when it doesn't, you should be able to hear how the melody feels "resolved" when it's on the root note.
C is the root note of C major. A is the root note of A minor.
The fifth is an important relative of the root, because it reliably harmonises with it - indeed if you listen carefully (on most instruments) you can hear the pitch of the fifth when you play the root note - it is a harmonic. It's called the fifth because it's four notes up the scale from the root (or first) -- but it's 7 semitones up.
G is the fifth of C. E is the fifth of A minor.
The third is really important because it's the difference between a major and a minor scale. If you play all the notes from a scale except for the third, you can't tell whether it's major or minor.
It's two notes up the scale from the first. But in a major key it's 4 semitones up, while in a minor key it's 3 semitones up.
E is the third of C. C is the third of A minor.
All the other notes have "roles" too (this isn't a formal music term -- I'm using ordinary language to explain things). You can study books to learn more, or just learn to feel the music.
So:

in C, the 1-3-5 notes are C-E-G.
in A the 1-3-5 notes are A-C-E.

You'll play A notes in C major melodies, but they will not take as significant a role in the structure of the melody. Likewise you'll play G notes in A minor melodies, but again they'll not be as "important" as a G is in C major melodies.
When soloing:

As a rule of thumb, start and end on the root note (but rules are made to be broken!)
Use the third to give a major or minor feel (or omit it to make it indeterminate)

On a piano, you could say that C major / A minor are the "most basic" keys, because the player can ignore black keys. In principle, though, every key is pretty much equivalent. C# major is simply C major with every note moved up one semitone.
There are easier keys than C/Am on a guitar, because more of the significant notes are open strings. However, if your intention is to solo, it's good to learn shapes that have no open strings. You can use these shapes in any key, simply by moving your whole hand up or down the fretboard.
Comment: In "A" the notes are A-C#-E, in "Amin" (the "Aeolian" mode aka, relative minor of Cmaj. 1-3-5 are A-C-E, to really show the relationship better, the i (minor "one" chord) Amin7 is A-C-E-G (the 3-5-7 of Amin7 are none other than Cmaj triad, this is referred to as a diatonic substitution), this relationship goes both ways... playing an Amin sound like Amin pentatonic (A-C-D-E-G) over a Cmaj triad is cool, roots are boring but help you center yourself as a reference when beginning, (but eventually every teacher will begin suggesting you limit it, there's almost always someone else playing it)
Answer: Sometimes a scale can be called "related". For example, there is the major diatonic scale http://en.wikipedia.org/wiki/Diatonic_and_chromatic consisting of eight notes. On a piano, this is easy to remember. The C major scale is all the white keys. C to C is 7 notes plus the octave.
The related or 'relative minor' can be counted 3 steps backwards.
C - D - E - F - G - A - B - c
becomes
A - B - C - D - E - F - G - a
All the same notes, but as sound can be recognized as the major or minor.
There are actually three main minor scales (relative, melodic & harmonic). Each is slightly different.
One other thing about scales as mentioned above, is the modes. Here's a simple picture of all seven. http://waltribeiro.com/wp-content/uploads/2008/10/modes-together-rt.jpg
Try them all out! You will begin to see, and hear, C Ionian sounds different from C Dorian and also the (relative minor) A Aeolian for C Ionian (the major). Try C Aeolian. etc.