Clang apresenta erro character too large mas Visual Studio compila normal

Question: Estou com dificuldades de entender porque o clang apresenta a mensagem de erro

character too large for enclosing character literal type

ao tentar executar o código:
char c = 'ç';

enquanto o Visual Studio 2015 compila sem problemas. Eu sei que diferentes compiladores podem e tem suas implementações diferentes. E que ç está fora da tabela ASCII, que o valor numérico deve ser maior que 127 por isso do Clang informar que não é possível armazenar dentro da tipo char. Mas ainda gostaria de saber:
Por que o Clang não permite que eu utilize 'ç' como um char enquanto o Visual Studio permite? É alguma coisa pré-definida no Visual Studio? Alguma opção baseado na linguagem do meu sistema?
Porque o Visual Studio retorna o valor "correto" nas funções de string, como strlen mesmo passando strings com acentos?
Exemplo: strlen("opção"); Retorna 5 no Visual Studio, eu esperava o retorno ser 7 como o Clang retorna.
Comment: Arriscaria dizer que por este caracter não pertencer ao padrão ASCII ele ocupa mais que 1 byte (enquanto o tipo `char` só suporta este tamanho). Veja se há como setar alguma opção para considerar o código fonte como UTF-8 na hora de executar.
Comment: Sim, acredito seja isso no clang, lá o strlen volta o valor em bytes, ou seja mais de 1 byte para ç. Pelo que vi o gcc permite alterar o encoding, porém o clang não tem tal opção. Mas o que me intriga o fato do Visual Studio simplesmente funcionar sem nenhum tipo de aviso para caracteres fora da tabela ascii. Mesmo usando ascii estendido.
Answer: Primeiro: compilar ou funcionar é diferente de estar certo. Todo programador deve ter isso muito claramente. Fez bem em perguntar aqui para entender porque funciona ou não.

Eu não tenho uma informação oficial (achei algumas informações soltas que indicam isso), mas posso inferir que o compilador C da Microsoft, que por acaso é usado por padrão no Visual Studio, está usando uma codificação de caracteres de apenas um byte, possivelmente Windows 1252. Esta usa uma tabela estendida do ASCII (que só tem 127 caracteres) permitindo alguns caracteres acentuados. Não funcionará com caracteres que estejam fora desta pequena tabela de 255 caracteres.
Recentemente o novo compilador permitiu controlar melhor como tratar isso.
Está claro pra mim que o Clang usa UTF-8 por padrão (até li em alguns lugares não oficiais que é isso mesmo), que é uma codificação multi-byte. Quando usa caracteres além da tabela ASCII ele precisa ser representado por 2 ou mais bytes.
Isso explica porque o char não funciona, afinal a especificação do C diz claramente que este tipo deve ter 1 byte sempre.
A função strlen() retorna o valor correto, afinal ela se propõe retornar a quantidade de bytes e não de caracteres.
Ainda aconselho procurar na documentação para confirmar se são essas codificações padrões mesmo.
Use wchar_t para garantir um tipo multi-byte. Ou wstring em C++.
Leia sobre as funções de string multi-byte do C.
Comment: Ou Unicode literals em vez de wide chars: http://en.cppreference.com/w/cpp/language/string_literal
Comment: Fiz alguns testes e realmente parece ser o caso, existe uma falta de documentação sobre essa discrepância. Mas bem ao tentar utilizar um carácter de outra linguagem o VisualC me deu a mensagem:  ```warning C4566: character represented by universal-character-name '\u30C8' cannot be represented in the current code page (1252)```, outra coisa que percebi que se o arquivo estiver com a codificação 1252 o visual studio substitui os caracteres fora dessa code page para um ?(char code 63) em vez de causar erro.. o que faz o código compilar, mas não funciona de forma correta.
Comment: @pepper_chico em C++, sim, claro.


If $u_{n+1}=\frac{1}{u_{n} + a_{n} + 1} $ for $(a_n)$ positive and bounded, then $(u_n)$ converges iff $(a_n)$ converges

Question: Let $(a_n)$ denote a positive, bounded, real sequence, and  $(u_n)$ the sequence defined by $u_0 > 0$ and, for every $n\ge0$,
$$u_{n + 1} = \frac{1}{u_{n} + a_{n} + 1}$$
How to show that the sequence  $(u_{n})$ converges if, and only if , the sequence $(a_{n})$ converges?
Answer: Since $u_0>0$, it is clear from the recurrence that $u_{n}>0, \forall n\geq 0$. Hence $$\frac{1}{2+M}\leq u_{n}\leq1$$ where $M>0$ is such that  $a_n\leq M$. So if $u_n\to l\Rightarrow l>0$ and hence $$a_n=\frac{1}{u_{n+1}}-u_n-1\to \frac{1}{l}-l-1$$ Now suppose $a_n\to l.$ Set $b_n=\frac{1}{u_n+a_n+1}-\frac{1}{u_n+l+1}$ and note  that $b_n\to 0$. We've $$u_{n+1}=\frac{1}{u_n+l+1}+b_n$$ so that $$u_{n+k+1}-u_{n+1}=\frac{-u_{n+k}+u_{n}}{\left(u_{n+k}+l+1\right)\left(u_n+l+1\right)}+b_{n+k}-b_n$$ Hence $$\left|u_{n+k+1}-u_{n+1}\right|\leq c\left|u_{n+k}-u_n\right|+\left|b_{n+k}-b_n\right|$$ where $0\leq c<1$. Setting $A_{(n,k)}=|u_{n+k}-u_n|$ and $B_{(n,k)}= |b_{n+k}-b_n| $ , the relation becomes $$A_{(n+1,k)}\leq c\,A_{(n,k)}+B_{(n,k)}$$ from which one gets $$ A_{(n+1,k)}\leq c^{n+1}A_{(0,k)}+\sum_{r=0}^{n}c^{n-r}B_{(r,k)}  $$
Now since $b_n\to 0$, there exist $n_0\in \mathbb{N}$ such that $B_{(r,k)}\leq \epsilon, \forall r\geq n_0,k\in\mathbb{N}$, for a fixed $\epsilon>0$. So
$$A_{(n+1,k)}\leq c^{n+1}A_{(0,k)}+\sum_{r=0}^{n_0}c^{n-r}B_{(r,k)}+\epsilon\left(\sum_{r=0}^{n_0}c^r \right)\leq c^{n+1}A_{(0,k)}+C\left(\sum_{r=n-n_0}^{n}c^r \right)+\epsilon\left(\sum_{r=0}^{n_0}c^r \right) $$ where $B_{(r,k)}\leq C, \forall r\in\mathbb{N},k\in\mathbb{N}$. Now for large enough $m$, it is clear from the above equation that there is $M'\geq0$ such that $$A_{(n+1,k)}\leq M'\epsilon$$ $\forall n\geq m, k\in \mathbb{N}$. Since $\epsilon>0$ was arbitrary, this means that the sequence $u_{n}$ is cauchy and hence convergent.
Comment: Thanks a lot for you detailed answer.
Comment: Excuse me but I don't understand how we have $$u_{n+1}=\frac{1}{u_n+l+1}+b_n$$ so that $$u_{n+k+1}-u_{n+1}=\frac{u_{n+k}-u_{n}}{\left(u_{n+k}+l+1\right)\left(u_n+l+1\right)}+b_{n+k}-b_n\leq c\left(-u_{n+k}+u_n\right)+(b_{n+k}-b_n)$$. I get $$u_{n+k+1}-u_{n+1}=\frac{-
u_{n+k}+u_{n}}{\left(u_{n+k}+l+1\right)\left(u_n+l+1\right)}+b_{n+k}-b_n $$
Comment: Silly me!  Fortunately that does not matter much. Edited.
Comment: Yes ! Thanks a lot.


How do I find the source of an error?

Question: I'm seeing the following error when running cron (in terminal via drush and on screen via the status report page.

Error: Call to a member function getScriptTag() on a non-object in /home/loktah/public_html/includes/common.inc(1762) : eval()'d code, line 2

I'm not sure where to even start looking for the source. Any direction would be appreciated.
Answer: The line 1762 is inside drupal_eval(), in Drupal 6. You need to check  those nodes that use the PHP filter and call getScriptTag() on a variable that doesn't contain a PHP object.
It happens during cron tasks because one of the implementations of hook_cron() indirectly calls node_view() on some nodes.
Comment: Thank you. After some searching I discovered that my client pasted javascript into text fields on nodes.

How do I find the source of an error?


How to carry out multiple post-hoc chi-square tests on a 2 X 3 table?

Question: My data set is comprised of either total mortality or survival of an organism at three site types, inshore, midchannel and offshore. The numbers in the table below represent the number of sites.
<code>              100% Mortality            100% Survival
Inshore             30                       31
Midchannel          10                       20
Offshore             1                       10
</code>
I would like to know if the # of sites where 100% mortality occurred is significant based on site type.
If I run a 2 x 3 chi-square, I get a significant result. Is there a post-hoc pairwise comparison that I can run or should I actually be using a logistical ANOVA or regression with binomial distribution?
Thanks!
Answer: A contingency table should contain all the mutually exclusive categories on both axes. Inshore/Midchannel/Offshore look fine, however unless "less than 100% mortality" means "100% survival" in this biological setting you may need to construct tables that account for all the cases observed or explain why you restrict your analysis to the extreme ends of the sample.
As 100% survival means 0% mortality, you could have a table with columns 100%=mortality / 100%>mortality>0% / mortality=0%. In this case you wouldn't any more compare percentages, but compare ordinal mortality measures across three site type categories. (What about using the original percentage values instead of categories?) A version of Kruskal-Wallis test may be appropriate here that takes ties appropriately into consideration (maybe a permutation test).
There are established post hoc tests for the Kruskal-Wallis test: 1, 2, 3. (A resampling approach may help tackling with ties.)
Logistic regression and binomial regression may be even better as they not only give you p values, but also useful estimates and confidence intervals of the effect sizes. However to set up those models more details would be needed concerning the 100%>mortality>0% sites.
Answer: I am going to assume that "100% survival" means that your sites only contained a single organism.  so 30 means 30 organisms died, and 31 means 31 organisms didn't.
Based on this the chi-square should be fine, but it will only tell which hypothesis are not supported by the data - it won't tell you if two reasonable hypothesis are better or not.  I present a probability analysis which does extract this information - it agrees with the chi-square test, but it gives you more information than the chi-square test, and a better way to present the results.
The model is a bernouli model for the indicator of "death", $Y_{ij}\sim Bin(1,\theta_{ij})$ ($i$ denotes the cell of the $2\times 3$ table, and $j$ denotes the individual unit within the cell).
There are two global assumption underlying the chi-square test:

within a given cell of the table, the $\theta_{ij}$ are all equal, that is $\theta_{ij}=\theta_{ik}=\theta_{i}$
the $Y_{ij}$ are statistically independent, given $\theta_{i}$.  This means that the probability parameters tell you everything about $Y_{ij}$ - all other information is irrelevant if you know $\theta_{i}$

Denote $X_{i}$ as the sum of $Y_{ij}$, (so $X_{1}=30,X_{2}=10,X_{3}=1$) and let $N_{i}$ be the group size (so $N_{1}=61,N_{2}=30,N_{3}=11$).  Now we have a hypothesis to test:
$$H_{A}:\theta_{1}=\theta_{2},\theta_{1}=\theta_{3},\theta_{2}=\theta_{3}$$
But what are the alternatives?  I would say the other possible combinations of equal or not equal.
$$H_{B1}:\theta_{1}\neq\theta_{2},\theta_{1}\neq\theta_{3},\theta_{2}=\theta_{3}$$
$$H_{B2}:\theta_{1}\neq\theta_{2},\theta_{1}=\theta_{3},\theta_{2}\neq\theta_{3}$$
$$H_{B3}:\theta_{1}=\theta_{2},\theta_{1}\neq\theta_{3},\theta_{2}\neq\theta_{3}$$
$$H_{C}:\theta_{1}\neq\theta_{2},\theta_{1}\neq\theta_{3},\theta_{2}\neq\theta_{3}$$
One of these hypothesis has to be true, given the "global" assumptions above.  But note that none of these specify specific values for the rates - so they must be integrated out.  Now given that $H_{A}$ is true, we only have one parameter (because all are equal), and the uniform prior is a conservative choice, denote this and the global assumptions by $I_{0}$.  so we have:
$$P(X_{1},X_{2},X_{3}|N_{1},N_{2},N_{3},H_{A},I_{0})=\int_{0}^{1}P(X_{1},X_{2},X_{3},\theta|N_{1},N_{2},N_{3},H_{A},I_{0})d\theta$$
$$={N_{1} \choose X_{1}}{N_{2} \choose X_{2}}{N_{3} \choose X_{3}}\int_{0}^{1}\theta^{X_{1}+X_{2}+X_{3}}(1-\theta)^{N_{1}+N_{2}+N_{3}-X_{1}-X_{2}-X_{3}}d\theta$$
$$=\frac{{N_{1} \choose X_{1}}{N_{2} \choose X_{2}}{N_{3} \choose X_{3}}}{(N_{1}+N_{2}+N_{3}+1){N_{1}+N_{2}+N_{3} \choose X_{1}+X_{2}+X_{3}}}$$
Which is a hypergeometric distribution divided by a constant.  Similarly for $H_{B1}$ we will have:
$$P(X_{1},X_{2},X_{3}|N_{1},N_{2},N_{3},H_{B1},I_{0})=\int_{0}^{1}P(X_{1},X_{2},X_{3},\theta_{1}\theta_{2}|N_{1},N_{2},N_{3},H_{B1},I_{0})d\theta_{1}d\theta_{2}$$
$$=\frac{{N_{2} \choose X_{2}}{N_{3} \choose X_{3}}}{(N_{1}+1)(N_{2}+N_{3}+1){N_{2}+N_{3} \choose X_{2}+X_{3}}}$$
You can see the pattern for the others.  We can calculate the odds for say $H_{A}\;vs\;H_{B1}$ by simply dividing the above two expressions.  The answer is about $4$, which means the data support $H_{A}$ over $H_{B1}$ by about a factor of $4$ - fairly weak evidence in favour of equal rates.  The other probabilities are given below.
$$\begin{array}{c|c}
Hypothesis & probability \\ \hline
(H_{A}|D) & 0.018982265 \\
(H_{B1}|D) & 0.004790669 \\
(H_{B2}|D) & 0.051620022 \\
(H_{B3}|D) & 0.484155874 \\
(H_{C}|D) & 0.440451171 \\
 \end{array}
$$
This is showing strong evidence against equal rates, but not in strong evidence favour of a defintie alternative.  It seems like there is strong evidence that the "offshore" rate is different to the other two rates, but inconclusive evidence as to whether "inshore" and "mid-channel" rates differ.  This is what the chi-square test won't tell you - it only tells you that hypothesis $A$ is "crap" but not what alternative to put in its place
Answer: Here is the code to do the chi square tests as well as generate a variety of test statistics. However, statistical tests of association of the table margins are useless here; the answer is obvious. No one does a statistical test to see if summer is hotter than winter.
<code>Chompy<-matrix(c(30,10,1,31,20,10), 3, 2)
Chompy
chisq.test(Chompy)
chisq.test(Chompy, simulate.p.value = TRUE, B = 10000)
chompy2<-data.frame(matrix(c(30,10,1,31,20,10,1,2,1,2,1,2,1,2,3,1,2,3), 6,3))
chompy2
chompy2$X2<-factor(chompy2$X2)
chompy2$X3<-factor(chompy2$X3)
summary(fit1<-glm(X1~X2+X3, data=chompy2, family=poisson))
summary(fit2<-glm(X1~X2*X3, data=chompy2, family=poisson)) #oversaturated
summary(fit3<-glm(X1~1, data=chompy2, family=poisson)) #null
anova(fit3,fit1)
library(lmtest)
waldtest(fit1)
waldtest(fit2) #oversaturated
kruskal.test(X1~X2+X3, data=chompy2)
kruskal.test(X1~X2*X3, data=chompy2)
</code>
Comment: It would be interesting for the reader (and the OP) if you could provide details about the different R syntax (and the underlying tests) you gave, and especially how a Kruskal-Wallis test does compare to a log-linear model.
Comment: Sure. Responses come from themselves by running the code, of course.
Comment: You can see this by copying and pasting the code into the R console.
Answer: You can do proportion testing for 100%Mortality vs totals:
<code>                Inshore  Midchannel  Offshore  Inshore%  Midchannel%  Offshore%   Pvalue
 FullMortality       30          10         1    49.180       33.333      9.091    0.029
 FullSurvival        31          20        10
 Total               61          30        11
</code>
P=0.029 indicates that there is a significant difference between different sites for 100%Mortality.
Answer: I believe you could use the "simultaneous confidence intervals" for doing multiple comparisons. The reference is Agresti et al. 2008 Simultaneous confidence intervals for comparing binomial parameters. Biometrics 64 1270-1275.
You could find the corresponding R code in http://www.stat.ufl.edu/~aa/cda/software.html


Executar servlet antes de carregar index.jsp

Question: Estou tentando executar meu servlet antes de carregar a index.jsp, pois as informações contidas na index vem de uma consulta no banco de dados. Tentei usar
<jsp:forward page="/servlet"/>

mas não deu certo. Como posso fazer isso?
Comment: Você precisa de um Filter :)
Answer: Bom dia Guilherme.
São varias as formas de se atingir o objetivo que você pretende. Utilizar um Filter como o @DilneiCunha sugeriu é uma das formas.
Outra forma também interessante é editar a tag <welcome-file> no seu arquivo de configuração web.xml (Se seu projetor estiver usando um, claro).
O seu arquivo de configuração web.xml ficará mais ou menos assim:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
        <url-pattern>/servlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>servlet</welcome-file>
    </welcome-file-list>
</web-app>

Note que:

/servlet seria o mapeamento para a Servlet que você quer usar para preencher o index.jsp.
Se no seu web.xml já existir a tag <welcome-file> preenchida com index.jsp é necessário substituir para o mapeamento da sua Servlet. (Não se esqueça de retirar o /)

Por fim, na sua Servlet, basta dispachar a requisição para o index.jsp. Assim, dentro de index.jsp, você terá acesso ao request que pode conter os dados que você obteu por meio de sua lógica dentro da Servlet.
Sua Servlet ficará mais ou menos assim:
public class Servlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //Executar sua lógica para obter os dados
        //...

        // Dispacha a requisição para index.jsp
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

}

Pronto. Seu projeto irá funcionar com esse workaround.
Não se esqueça de sempre buscar soluções alternativas para os problemas.
Espero ter ajudado. Um abraço.
Comment: Obrigado Andrew Ribeiro.
Foi o mesmo caso:
Eu precisava iniciar a página home e-commerce, porém, antes, precisava ir no banco de dados para buscar os produtos para expor na tela inicial.


Operator topologies on $L^{\infty}(X,\mu )$

Question: Let $(X,\mu )$ be a measure space.  Then, $L^2(X):=L^2(X,\mu )$ is a Hilbert space in the usual way and we may view $L^{\infty}(X):=L^{\infty}(X,\mu )$ as a subalgebra of bounded operators on $L^2(X)$ via $L^{\infty}(X)\ni f\mapsto M_f$, where $M_f\colon L^2(X)\rightarrow L^2(X)$ is the multiplication operator defined by $[M_f(g)](x):=f(x)g(x)$.
Regarding $L^{\infty}(X)$ as an algebra of bounded operators in this way, the question can be stated as

How can we describe explicitly convergence in the various operator topologies on $L^{\infty}(X)$?

At least one is relatively easy.  For example, $\lambda \mapsto M_{f_{\lambda}}$ converges to $M_f$ in the operator norm topology iff $\lambda \mapsto f_{\lambda}$ converges to $f$ in the $L^{\infty}$ norm.  It seems that convergence in measure corresponds to ultra-weak convergence.  Furthermore, pointwise almost-everywhere convergence can't correspond to any topology.  These are perhaps the three most obvious notions of convergence in $L^{\infty}(X)$, but that leaves many operator topologies unaccounted for.  Perhaps most of them just don't have a very nice description?
Update #1:  It seems as if the weak operator topology corresponds to the weak-$^*$ topology:  $\lambda \mapsto f_{\lambda}\in L^{\infty}(X)$ converges to $f\in L^{\infty}(X)$ in the weak-$^*$ topology iff $\lambda \mapsto \int _Xgf_{\lambda}$ converges to $\int _Xgf$ for all $g\in L^1(X)$, and on the other hand, $\lambda \mapsto M_{f_{\lambda}}$ converges to $M_f$ in the weak operator topology iff $\lambda \mapsto \int _Xgf_{\lambda}h$ converges to $\int  _Xgfh$ for all $g,h\in L^2(X)$.  As $gh\in L^1(X)$ for $g,h\in L^2(X)$, we obtain the $(\Rightarrow )$ direction immediately.  For the $(\Leftarrow )$ write $g=u|g|$ for some Borel function $u$ with $|u|=1$, so that we have $\lambda \mapsto \int _Xgf_{\lambda}=\int _X(u|g|^{1/2})f_{\lambda}|g|^{1/2}$ converges to $\int _X(u|g|^{1/2})f|g|^{1/2}=\int _Xgf$.
Update #2:  I have decided to ask this on mathoverflow.
Answer: I think you can learn something related to von Neumann algebra.
$L^2(X,\mu)$ is a Hilbert space. You can verify that $L^\infty(X,\mu)$ is a maximal abelian von Neumann algebra on $L^2(X,\mu)$.
By von Neumann bicommutant theorem (https://en.wikipedia.org/wiki/Von_Neumann_bicommutant_theorem), $M$ is a von Neumann algebra on Hilbert space $H$ iff $M$ is closed in strong operator topology  iff $M$ is closed in weak operator topology.
Comment: This is only true if $(X,\mu)$ is $\sigma$-finite, right?


Can long-run variance of an ARMA process be lower than its error variance?

Question: Consider an ARMA process expressed in lag operator notation,
$$
\Phi(L)x_t=\theta(L)\varepsilon_t.
$$ Let $\text{Var}(\varepsilon_t)=\sigma^2_{\varepsilon}$.
Question: Can the long-run variance of $x_t$ be lower than the error variance? If so, could you provide an example?
A related thread with an answer that may help answer my question is "Long-run variance of ARMA(p,q)".
A related new question is "Can unconditional variance of an ARMA process be lower than its error variance?".
Comment: The second link is the same as the first one
Comment: @gunes, good catch! Now fixed.
Answer: Let's denote the long-run variance as $\operatorname{var}_L(y_t)$ to prevent confusion. From the formula provided in the linked post, a proper choice of coefficients can lead to smaller long-run variance. Let our process be defined as
$$y_t=e_t-0.6e_{t-1}$$ then, the long-run variance will be $$\operatorname{var}_L(y_t)=\sigma^2 \left(\frac{1-0.6}{1}\right)^2=0.16\sigma^2<\sigma^2$$
Note that the missing definiton of coefficients in that post is ($b_0=1$)
$$y_t=\sum_{i=1}^p a_py_{t-p}+\sum_{i=0}^q b_qe_{t-q}$$
Comment: @RichardHardy But, long-term variance is not $var(x_t)=\gamma(0)$, where $\gamma(t)$ is the auto covariance function. We also have $\gamma(1)=\gamma(-1)=-0.6\sigma^2$ and higher order covariances $0$, which yields $$\operatorname{var}_L(y_t)=\sum_{k=-\infty}^\infty \gamma(k) = 0.16\sigma^2$$
Comment: I believe the formula there is wrong. Your example yields $\text{Var}(x_t)=1.36\sigma^2_\varepsilon>\sigma^2_\varepsilon$. Here is a quick simulation to show that: `n=1e6; set.seed(1); e=rnorm(n); x=arima.sim(model=list(ma1=-0.6),n=n,innov=e); var(e); var(x)`.
Comment: Ahh, I forgot what the term *long-run variance* actually means. I meant to ask about the unconditional variance of $x$ instead, which I actually did by writing $\text{Var}(x_t)$. I will edit the question to clarify. Or better yet, I will post a new question so that your answer gets the credit it deserves. ... And I did: [here](https://stats.stackexchange.com/questions/507648) is my new question.


É possível alterar o valor de uma variável que foi decorada com Input()?

Question: Tenho a variável disciplinasTurma que foi está recebendo um valor do componente pai. Eu queria remover um dos valores dela, o método até remove, mas só dentro dele mesmo. Tem como fazer isso?
Comment: Mutação no geral é ruim, o certo seria copiar pra outra propriedade
Answer: Você pode utilizar um método set para esse fim.
Dessa forma você executa uma lógica antes de passar o valor para a sua variável de classe.
Por exemplo:
<code>@Input()
set disciplinasTurma(disciplinas: string[]): void {
    this.disciplinasTurma = disciplinas.splice(disciplinas.findIndex(d => d === valor), 1);
}
</code>


Nonlinear ODE's

Question: So I've in second-year, taking a course on differential equations. We've learned about integrating factors, different classifications, substitutions, etc. I think I have a hold on lots of this stuff so far but this one problem is stuck in my teeth and it's driving me crazy. It looks simple enough but Maple spits out a big ugly logarithmic equation with an arctan term, and I don't know where to begin:
$x^2\,dx + (xy + x^2)\,dy = 0$
Answer: $$
\frac{dy}{dx} = -\frac{x^{2}}{xy+x^{2}} = -\frac{1}{\frac{y}{x} + 1}.
$$
using the transform $z = y/x$ yields
$$
x\frac{dz}{dx} + z = - \frac{1}{z+1}.
$$
This is separable and therefore can be solved.
To complete the problem
$$
\int \frac{(z+1)}{z(z+1)+1}dz = -\int \frac{1}{x} = -\mathrm{ln}(x) + C
$$
now we shall concentrate on the lhs
$$
\frac{(z+1)}{z(z+1)+1} = \frac{4}{3}\frac{(z+1)}{\left(\frac{z+\frac{1}{2}}{\sqrt{3/4}}\right)^{2}+1}.
$$
Using a change of variable $u = \frac{z+\frac{1}{2}}{\sqrt{\frac{3}{4}}}$ leads to
$$
\frac{4}{3}\frac{\frac{\sqrt{3}}{2}u+\frac{1}{2}}{u^{2}+1}= \frac{2}{\sqrt{3}}\frac{u+\frac{1}{\sqrt{3}}}{u^{2}+1}
$$
after all that re-arranging we can sub back into the integral.
$$
\int \frac{2}{\sqrt{3}}\frac{u+\frac{1}{\sqrt{3}}}{u^{2}+1}\sqrt{\frac{3}{4}}du = -\mathrm{ln}(x) + C
$$
we can split the integral on the lhs as
$$
\int \frac{u}{u^{2}+1} du + \frac{1}{\sqrt{3}}\int \frac{1}{u^{2}+1}du
$$
The terms above evaluates to terms in the brackets below
$$
\left[\frac{1}{2}\mathrm{ln}\left(u^{2}+1\right)+\frac{1}{\sqrt{3}}\mathrm{arctan}(u) \right] = -\mathrm{ln}(x) + C
$$
$$
u = \frac{1}{x}\frac{2y+x}{\sqrt{3}}
$$
transforming back
$$
\left[\frac{1}{2}\mathrm{ln}\left(\left(\frac{1}{x}\frac{2y+x}{\sqrt{3}}\right)^{2}+1\right)+\frac{1}{\sqrt{3}}\mathrm{arctan}\left(\frac{1}{x}\frac{2y+x}{\sqrt{3}}\right) \right] = -\mathrm{ln}(x) + C
$$
which if we expand the log argument yields
$$
\left(\frac{1}{x}\frac{2y+x}{\sqrt{3}}\right)^{2}+1 = \frac{4y^{2} + 4xy + x^{2} + 3x^{2}}{3x^{2}} = \frac{4}{3}\frac{y^{2} + xy + y^{2}}{x^{2}}
$$
which if we take the logarithm of
$$
\mathrm{ln}\left(\frac{4}{3}\right) + \mathrm{ln}\left(\frac{y^{2} + xy + y^{2}}{x^{2}}\right)
$$
we can sub back into the solution equation and take the constant logarithm into the constant C, we finally reach
$$
\frac{1}{2}\mathrm{ln}\left(\frac{y^{2} + xy + y^{2}}{x^{2}}\right)+\frac{1}{\sqrt{3}}\mathrm{arctan}\left(\frac{1}{x}\frac{2y+x}{\sqrt{3}}\right)  = -\mathrm{ln}(x) + C
$$
was this close to what you got?
Comment: In your fourth equation, you go from having a $z^2$ term in the denominator to only having a $z$ term.
Comment: @Arkamis oops!! thank you.
Comment: You're the best =)
Comment: @user126291 no problem. I am glad to help

Nonlinear ODE's


Desktop Application to upload a txt file to Google Cloud Storage

Question: Well i been searching through the whole internet for something that solves my issue. I have read about the JSON API and Java Client for Cloud Storage but it seems this two apis required to be deployed on Compute engine and App Engine respectively. So i was wondering if there is a way to create a desktop application that sends a file to google Cloud storage bucket. Sorry im not an expert in this issue so any help would be really appreciated.
Answer: According to the Developer Guide, Google's "API Client Library for Java" is supported on vanilla Java (Java 5 and later).

Supported Java environments
The library supports the following Java environments:

Java 5 (or higher), standard (SE) and enterprise (EE)
Android 1.5 (or higher) (Note that this library's support for Android is @Beta.)
Google App Engine

You should be able to use that library as the starting point for your desktop application.
Comment: Thank you so much Stephen C, this helped me to point me to the right direction. After reading the Developers Guide and seeing some examples of storage, I was able to get solution. If anyone needs help with this i would be more than happy to help them.


Problems with Oledb and DATETIME

Question: I need some help.this is my code:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Request " + "WHERE _Date >= " + "@Dt", con);
cmd.Parameters.Add("@Dt", OleDbType.Date);
cmd.Parameters["@Dt"].Value = DateTime.Now;
using (IDataReader reader = cmd.ExecuteReader())
{ }

But it returns an exception:

"Syntax error in query expression '_Date >= @Dt'." OleDb Exception

and with this code:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Request " + "WHERE _Date > " + "'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +"'", con);
using (IDataReader reader = cmd.ExecuteReader())
{  }

it returns

"Syntax error in query expression '_Date > '2014-08-08 10:55:04''."

What's wrong here?
Comment: I would avoid Column names that have an underscore in front like that, and I would also try to give it a better name, like RequestDate.  Try putting the field in brackets: [_Date].
Comment: @LarsTech, Change column names and work. thank you
Answer: Despite the underscore, the name Date is a reserved word, so you should probably place the field name in brackets:
WHERE [_Date] > @Dt

It's best to avoid reserved words and use a better description for the field name, like RequestDate.  I would also avoid starting a column name with an underscore.
Answer: Try like this
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Request] WHERE [_Date] >= @Date", con);
cmd.Parameters.AddWithValue("@Date", DateTime.Now);

Comment: @user886550 please give the full error description.
Comment: @user886550 if this was right then click on right button for set it answer
Answer: Instead of exposing your SQL to injection by concatinating your sql together, use a placeholder for the parameter.
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Request WHERE _Date > ?", con);
cmd.Parameters.AddWithValue("@Date", DateTime.Now);

Problems with Oledb and DATETIME


What's Typescript's issue with document.getElementbyID?

Question: Please someone choose a better title, because I frankly don't know how to title this one.
What I'm trying to do, is to get Textarea's content as string (for use with NW.js file functions as I'm writing an app that does stuff on flat files) and I'm using following code to do that:
let file = document.getElementById("txt").value;

It works after being compiled to JS just fine. However, the TypeScript compiler complains about the value part:
Property 'value' does not exist on type 'HTMLElement'

What am I doing wrong?
Answer: TypeScript's raison d'être is to apply static typing to JavaScript-like code. document.getElementById returns HTMLElement, which doesn't have value (after all, it could be any kind of HTML element), so TypeScript warns you you're using a property that HTMLElement doesn't have. TypeScript can't know that the specific element you're getting is an HTMLInputElement (which has value) unless you tell it it is via casting (technically, a type assertion):
let file = (document.getElementById("txt") as HTMLInputElement).value;
// or
let file = (<HTMLInputElement>document.getElementById("txt")).value;

Comment: Thanks for clarification.


topological group operation vs homotopy group operation

Question: Let $X$ be a topological group. Let $\tau_1$ and $\tau_2$ representing elements of $\pi_n(X)$. Is it true that
$$ [\tau_1] [\tau_2] = [\tau_1 \tau_2] $$
in $\pi_n(X)$?,
where of course "$[\tau_1] [\tau_2]$" refers to the $\pi_n(X)$ group operation, and by $\tau_1 \tau_2$ I mean the map $S^n \ni x \mapsto \tau_1(x) \tau_2(x)$.
I know from greenberg harper algebraic topology a first course, page 30, that this is true for n=1.
It seems to me that the answer is a simple "yes", but I wonder why I can't find it on the internet.
Comment: does https://en.wikipedia.org/wiki/Eckmann-Hilton_argument#The_Eckmann.E2.80.93Hilton_result

provide an answer to the question?
Comment: I don't understand your objection: we do have two group operations on the same set $\pi_n(X)$: the first one is the standard one, the second one is the pointwise product.
Comment: I don't see how to use E-H here since you don't have two operations on one set but here each operation is on a different set. Anyway, interesting question and I'm curious about the answer in either direction. Can we say anything concrete e.g. about $SU(2)$?
Comment: Ah, I see, I misunderstood your construction. Sorry.
Answer: Yes, Eckmann-Hilton applies. Interestingly, this implies that all of the homotopy groups of a topological group are abelian. For higher homotopy groups, this is not so interesting, because they are always abelian, regardless of the space. For $n=1$, however, it is not content-less: it tells us that the fundamental group of a topological group is abelian. Fundamental groups are not always abelian!
Thus, for instance, it is impossible to put a topological group structure on the twice-punctured plane.


Erro no JavaScript

Question: Alguém poderia me dizer como fazer o JOIN para preencher os dados automaticamente a partir do campo descrição. Acusa este erro Notice: Trying to get property of non-object in C:\xampp\htdocs\PhpProject1\function.php on line 9
{"codigo_produto":"","barcode":"","porcao":""} no caso a linha 9 é esta if($resultado->num_rows){
index.php

                Descrição:
                <input type="text" required class="form-control" maxlength="13" name="descri">

                Código do Produto:
                <input type="text" required class="form-control" maxlength="13" name="codigo_produto">

                Código EAN:
                <input type="text" required class="form-control" maxlength="13" name="barcode">

                Tipo:
                <input type="text" class="form-control" name="codigo_tipo" value="">

                Porção:
                <input type="text" class="form-control" maxlength="20"  name="porcao">

function.php
   function retorna($descricao, $conn){

        $result = "SELECT a.descricao, a.codigo_produto, a.barcode, b.codigo_tipo, c.porcao FROM CADPRO A
            LEFT OUTER JOIN TIPOPROD B ON (A.CODIGO_PRODUTO = B.CODIGO_PRODUTO)
            LEFT OUTER JOIN INFOPROD C ON (B.CODIGO_PRODUTO = C.CODIGO_PRODUTO) WHERE descricao =";
        $resultado = mysqli_query($conn, $result);

        if(!is_null($resultado)){
            $row = mysqli_fetch_assoc($resultado);
                $valores['codigo_produto'] = $row['codigo_produto'];
                $valores['barcode'] = $row['barcode'];
                $codigo_produto = $row['codigo_produto'];
                $valores['codigo_tipo'] = $row['codigo_tipo'];
                $valores['porcao'] = $row['porcao'];
        } else {
                $valores['codigo_produto'] = '';
                $valores['barcode'] = '';
                $valors['tipo'] = '';
                $valores['porcao'] = '';
        }

        return json_encode($valores);
    }
    if(isset($_GET['descricao'])){
        echo retorna($_GET['descricao'], $conn);
    }
    ?>

Comment: Defiz a edição, senão a resposta dada perderia o sentido.
Answer: Tenta colocar desta forma:
$resultado = mysqli_num_rows($resultado);

if(!is_null($resultado)){
     ...

Assumindo que você não instanciou a classe mysqli. Veja o exemplo nesta página, interpretando seu código, aparentemente está fazendo de forma procedural.
Desta forma não poderia utilizar nenhum tipo de objeto.
Comment: Vou mostrar o código na function.php como esta agora meu erro é ------>Warning:  mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\PhpProject1\function.php on line 14
{"codigo_produto":null,"barcode":null,"codigo_tipo":null,"porcao":null}
Comment: A função mysqli_fetch_assoc retorna uma matriz associativa que corresponde a linha obtida, ou NULL se não houverem mais linhas. No caso, como não está utilizando o mysqli_num_rows, irá retornar NULL. (Em sua ultima atualização)
Answer: Isso não tem sentido:
if(!is_null($resultado)){

O mysqli_query nunca vai retornar NULL, ele sempre vai cair no mesmo if, mesmo que dê erro, no caso ele retornou false e como false não é null ele entra no primeiro if de qualquer jeito, mas o mysqli_fetch_assoc sempre espera um "objeto".
Pra evitar isso é só sempre usar a documentação pra ter certeza de como a função funciona e vai ver http://php.net/manual/en/mysqli.query.php#refsect1-mysqli.query-returnvalues.
Veja a documentação dize que ele retorna FALSE se falhar ou um objeto mysqli_result se tiver sucesso.
Mude o código para:
if($resultado){
    $row = mysqli_fetch_assoc($resultado);
        $valores['codigo_produto'] = $row['codigo_produto'];
        $valores['barcode'] = $row['barcode'];
        $codigo_produto = $row['codigo_produto'];
        $valores['codigo_tipo'] = $row['codigo_tipo'];
        $valores['porcao'] = $row['porcao'];
} else {

Outra sugestão é criar um JSON de erro, assim:
if($resultado){
    $row = mysqli_fetch_assoc($resultado);
        $valores['codigo_produto'] = $row['codigo_produto'];
        $valores['barcode'] = $row['barcode'];
        $codigo_produto = $row['codigo_produto'];
        $valores['codigo_tipo'] = $row['codigo_tipo'];
        $valores['porcao'] = $row['porcao'];
} else {
       return json_encode(array( 'error' => mysqli_error($conn) ));
}

Outro de importante, você não declarou a variavel $valores, mas declarou a variavel $codigo_produto = $row['codigo_produto'];, mas você não esta usando ela, talvez o código deva ficar assim:
function retorna($descricao, $conn){

    $result = "SELECT a.descricao, a.codigo_produto, a.barcode, b.codigo_tipo, c.porcao FROM CADPRO A
        LEFT OUTER JOIN TIPOPROD B ON (A.CODIGO_PRODUTO = B.CODIGO_PRODUTO)
        LEFT OUTER JOIN INFOPROD C ON (B.CODIGO_PRODUTO = C.CODIGO_PRODUTO) WHERE descricao =";
    $resultado = mysqli_query($conn, $result);

    // DECLARA A VARIAVEL
    $valores = array();

    if(!is_null($resultado)){
        $row = mysqli_fetch_assoc($resultado);
        $valores['codigo_produto'] = $row['codigo_produto'];
        $valores['barcode'] = $row['barcode'];
        $codigo_produto = $row['codigo_produto'];
        $valores['codigo_tipo'] = $row['codigo_tipo'];
        $valores['porcao'] = $row['porcao'];
    } else {
        return json_encode(array( 'error' => mysqli_error($conn) ));
    }

    return json_encode($valores);
}

Comment: @VictorT. uma coisa não tem nada haver com a outra, join é no comando do mysql, teus erros eram no PHP, veja a edição da resposta ........ Se quer entender o básico do JOIN leia isto: https://pt.stackoverflow.com/a/6448/3635
Comment: @VictorT. não é isso, PHP é PHP, mysql é mysql... eles não trabalham paralelamente, o problema é como vc esta fazendo o JOIN que vai gerar uma saida diferente, como eu te mandei no linkp pra vc entender, cada join tem um efeito, entendendo o efeito vc já entende parte do resultado, se jogar em um programa como HeidSQL ou phpmyadmin vai notar que provavelmente ele gerou linhas repetidas, ou seja é você que não esta entendendo bem o efeito do JOIN e esta fazendo confusão, a culpa não é do PHP.....
Comment: No caso o seu código apresenta este erro ao debugar ---> Notice:  Undefined variable: valores in C:\xampp\htdocs\PhpProject1\function.php on line 22
Comment: @VictorT. isso ae já é outro erro, é só vc observar, vc não declarou a variavel $valores dentro do escopo da função. E se vc notar bem vc declarou a variavel `$codigo_produto`, mas não esta usando ela.
Comment: @VictorT. Editei a resposta, veja o codigo de exemplo do final se dá pra vc entender.
Comment: então no caso, eu acho estranho o fato de eu testar o mesmo código sem join utilizando ele pra trazer dados de uma única tabela e funciona, estranho isso, vou editar a pergunta o arquivo funcition.php para verificar, está identico
Comment: o problema não é o JOIN mesmo, mas muito estranho o PHP não reconhecer, já que eu jogo esse JOIN no MYSQL e funciona
Comment: ....  Provavelmente você vai querer somar valores ou agrupar algo, ae não tenho como te responder porque não sei como é tua tabela nem os dados que contem nela. @VictorT.
Comment: eu quero que a partir da descrição que o usuário digite, a medida que ele de tab os dados restantes sejam preenchidos automaticamente
Comment: @VictorT. ae vc já está mudando o sentido da pergunta totalmente, eu resolvi o problema aqui, certo? A parte que era o erro `Trying to get property of non-object`. Agora se tem outra duvida ainda mais sendo complexa assim crie uma nova pergunta e explique detalhadamente o que ocorre.
Comment: não meu problema continua, mas vou marcar sua resposta como a melhor mesmo assim pelo esforço, BASTA VOCÊ LER A PERGUNTA --->Alguém poderia me dizer como fazer o JOIN para preencher os dados automaticamente a partir do campo descrição.
Comment: @VictorT. continua a mesma mensagem de erro `Trying to get property of non-object` ou `Undefined variable: valores`?
Comment: o erro agora é ---->Warning:  mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\PhpProject1\function.php on line 15
{"codigo_produto":null,"barcode":null,"codigo_tipo":null,"porcao":null} MAS EDITEI MINHA FUNCTION E ESTA IDENTICO A SUA, SE EU TIRO O !is_null ME RETORNA APENAS [] no NETWORK
Comment: @VictorT. você tem certeza que ajustou o código como eu te disse? Eu acho que vc fez outra confusão.
Comment: editei novamente  a function
Comment: @VictorT. então é sem is_null, já deixei bem claro na minha resposta, se vc adicionou novamente é porque você não esta entendendo o que esta fazendo, vc esta fazendo coisas aleatorias e sem sentido, simplesmente. Eu já disse que aquilo nunca vai retornar null, logo não tem sentido usar is_null. E se sem is_null está retornando um array vazio `[]` é porque tem algo de errado na sua query, mas como eu já te disse pra esse caso vc deve abrir uma nova pergunta, pois esse é outro problema, como detalhes da tabela e dados, pois sem isso eu não tenho como te ajudar sem informações desse tipo.
Comment: ok obrigado, tentarei abrir outra pergunta, mas fiz umas edicoes na query e   agora diz que --> "Column 'descricao' in where clause is ambiguous"} é péssimo ser iniciante rs
Comment: @VictorT. isso é problema na sua query mesmo, quando fizer a pergunta me manda o link
Comment: @VictorT. antes de criar a pergunta, tenta mudar pra isto `$result = "SELECT a.descricao, a.codigo_produto, a.barcode, b.codigo_tipo, c.porcao FROM CADPRO A
            LEFT OUTER JOIN TIPOPROD B ON (A.CODIGO_PRODUTO = B.CODIGO_PRODUTO)
            LEFT OUTER JOIN INFOPROD C ON (B.CODIGO_PRODUTO = C.CODIGO_PRODUTO) WHERE a.descricao =''";` e veja se funciona.
Comment: Fiz desta forma com o a.descricao e o resultado quando vou em inspecionar e na aba Network  é este =>{"codigo_produto":"MARMEL","barcode":"3719826450","codigo_tipo":"PEDACO","porcao":"50 g"}
$result = "SELECT a.descricao, a.codigo_produto, a.barcode, b.codigo_tipo, c.porcao FROM CADPRO A
LEFT OUTER JOIN TIPOPROD B ON (A.CODIGO_PRODUTO = B.CODIGO_PRODUTO)
LEFT OUTER JOIN INFOPROD C ON (B.CODIGO_PRODUTO = C.CODIGO_PRODUTO) WHERE a.descricao =''"; mas no caso a linha que esta dentro de {...}  é justamente o que deveria retornar dentro dos inputs e seria solucionado o problema
Comment: @VictorT. ae complica, melhor abrir outra pergunta, porque da forma que está eu nem consigo saber aonde é o problema, visando que esse assunto já é totalmente outro.

Erro no JavaScript


Mathematics Engineering: How do you prove the power rule?

Question: Consider the real-valued function  $f(x)=x^r$ where $r$ is a real number.
(1) For what values of $x$ and $r$, is this function differentiable?
(2) How do you prove the power rule, when $f(x)$ is differentiable?
It would be nice if the proof is accessible to a 12th grade student.
EDIT: Perhaps, I have not been very clear about my question.  I am not satisfied with the "textbook proofs" I have seen.  Please established the existence (of the derivative) first before proving the power rule.  That is, please consider first question first.  This is the reason why I call the question a mathematical engineering question.  (If we can we bring high level math down to Grade 12 level, without loosing precision, then I call it good mathematical engineering.)
Comment: It is differentiable for: positive $x$ and all $r$; negative $x$ and $r$ rational with an odd denominator; zero $x$ with $r$  positive rational with an odd denominator; and if you define $0^0=1$ also zero $x$ with zero $r$.
Comment: How does your hypothetical Grade 12 student *define* derivative? Unless he has a *precise* definition, you're not going to be able to get any kind of "proof" across to him, because the very notion of derivative is not clear. The Inverse Function Theorem is easy enough to get across, but products and compositions are not.
Comment: Have you checked the Wikipedia proof at http://en.wikipedia.org/wiki/Power_rule?
Comment: "negative $x$ and $r$ rational with an odd denominator" - depends on the branch of the logarithm taken...
Comment: @RossMillikan: I just looked at it.  The generalization part is vague.
Answer: For positive integer $r$, we can define $x\mapsto x^r$ for all $r$, and the formula follows from the definition of derivative and the Binomial Theorem:
$$\begin{align*}
\frac{d}{dx} x^r &= \lim_{h\to 0}\frac{(x+h)^r - x^r}{h} = \lim_{h\to 0}\frac{x^r + rx^{r-1}h + h^2(\text{some factors}) - x^r}{h}\\
&= \lim_{h\to 0}\frac{rx^{r-1}h + h^2(\text{some factors})}{h} = \lim_{h\to 0}\left(rx^{r-1} + h(\text{some factors})\right)\\
&= rx^{r-1} + 0 = rx^{r-1}
\end{align*}$$
It is continuous for all $x$, since it is differentiable for all $x$.
For negative integers $r= -n$ with $n$ a positive integer, continuity at all $x\neq 0$ follows because $x^n$ is continuous at all $x$. For differentiability, we know it is differentiable at all places where it is defined, because it is the quotient of two differentiable functions (the constant function $1$, and the function $x\mapsto x^n$, which we just proved is differentiable). To find the formula, we use the Product Rule:
$$\begin{align*}
0 &= \frac{d}{dx} 1 = \frac{d}{dx}x^{-n}x^n = (x^{-n})'x^n + (x^{-n})(x^n)'\\
&= (x^{-n})'x^n + x^{-n}(nx^{n-1}) = (x^{-n})' + nx^{-1}.
\end{align*}$$
Solving for $(x^{-n})'$ we obtain
$$\frac{d}{dx} x^{-n} = -\frac{nx^{-1}}{x^n} = -nx^{-n-1} = rx^{r-1},$$
yielding the power rule. (We could also use the Quotient Rule to get differentiability of $\frac{1}{x^n}$).
For rational $r=\frac{p}{q}$ with $p$ and $q$ in reduced terms, the definition is that $x^r = (x^p)^{1/q}$. For $q$ odd, this is defined for all $x$ and is continuous (it's the composition of $x^p$ and the inverse of $x^q$, which is continuous on all $x$), but differentiable only at $x\neq 0$; differentiability of $x\mapsto x^{1/q}$ follows by the Inverse Function Theorem, and differentiability of $x^{p/q}$ now follows because it is a composition of differentiable functions, so the proof of the Chain Rule shows that it is differentiable; for $q$ even, this is defined for all $x\geq 0$ and is continuous there, but only differentiable at $x\gt 0$ (the tangent at $x=0$ is vertical). Differentiability elsewhere again follows by the Inverse Function Theorem and the Chain Rule (which in fact proves that the composition is differentiable).
For $x^{1/q}$ with $q$ and integer, we use the Chain Rule:
$$1 = \frac{d}{dx}x = \frac{d}{dx}(x^{1/q})^q = q(x^{1/q})^{q-1}(x^{1/q})',$$
so solving for $(x^{1/q})'$ we get
$$\frac{d}{dx}x^{1/q} = \frac{1}{q}x^{(1-q)/q} = \frac{1}{q}x^{(1/q) - 1}.$$
Then for $x^{p/q}$ we have, again by the Chain Rule,
$$\frac{d}{dx}x^{p/q} = \frac{d}{dx}(x^p)^{1/q} = \frac{1}{q}(x^p)^{(1/q)-1}(x^p)' = \frac{p}{q}(x^{p})^{(1/q)-1}x^{p-1} = \frac{p}{q}x^{(p/q)-p+p-1} = \frac{p}{q}x^{(p/q)-1}.$$
For irrational exponent $r$ we only define $x^r$ for $x\gt 0$, and we define it $x^r = \exp(r\ln x)$. For $x\gt 0$ the function $x\mapsto \ln x$ is differentiable; hence $x\mapsto r\ln x$ is differentiable. The exponential is differentiable everywhere, so the commposition $x\mapsto \exp(r\ln x)$ is differentiable everywhere that it is defined, again by the Chain Rule. To get the formula, we can just use the Chain Rule again:
$$\frac{d}{dx} x^r = \frac{d}{dx}\exp(r\ln x) = \exp(r\ln x)(r(\ln x)') = \frac{r}{x}\exp(r\ln x) = \frac{r}{x}(x^r) = rx^{r-1}.$$
Comment: @Sony: You cannot **prove** things without assumptions and basic definitions. There is a vast difference between "getting idea across" and "proving". One can get the idea of the Chain Rule across pretty easily, and one can even provide an argument using limits which is *almost* right but not really a proof, but actually proving it is more complicated. Likewise for the inverse function (which can be gotten across reasonably well using geometric arguments). But if you want **proofs**, then you need a lot more, and you are vacillating wildly between "proving" and "getting across". (cont)
Comment: @Sony: In my opinion, you are being quite muddled and unclear about just what it is you want or what it is you want to assume or not assume, and as such your "suspicion" is likely little more than a reinforcement of that muddleness, born out of itself.
Comment: @Sony: That the logarithm function is differentiable follows because it's the inverse of the exponential: inverse of a differentiable function is differentiable, provided the original function does not have derivative equal to $0$ (think about the graph of the inverse: it is obtained as a reflection of the original graph about the line $x=y$. Draw a graph and draw the tangent: if the tangent has slope $m$, the reflection has slope $\frac{1}{m}$; unless the original tangent was horizontal, in which case the inverse will have a vertical tangent, and not be differentiable).
Comment: @ArthroMagidin: I like your proof.  Let us assume that the hypothetical Grade 12 student has a very good understanding what limit of a function (at a point) is.
Comment: I followed your proof up to rational powers.  In the real case, you use "exp function is differentiable" and "ln function is differentiable" How do you establish one or the other at Grade 12 level?
Comment: @Sony: So it really comes down to the fact that the exponential function $y=e^x$ is differentiable and the derivative is not equal to $0$. Getting it "across at the Grade 12 level" will, **again**, depend on just what this imaginary (and in my personal opinion, utterly and ridiculously unrealistic) student knows about the exponential function. How is $e^x$ defined for arbitrary $x$? As a power series? Then differentiate term-by-term to see that $(e^x)' = e^x$. In some other way? Then it depends on your definition.
Comment: Thank you very much.  You confirmed my suspicion.  You cannot prove power rule in Grade 12 if you want to be coherent.  Hung-Hsi Wu in his book "Understanding Numbers in Elementary School Mathematics" introduces the term FASM (Fundamental Assumption of School Mathematics).  That is, "All information about the arithmetic operations on fractions can be extrapolated to all real numbers".  We may have to use something similar to FASM to get the general power rule in Grade 12.  Better yet, stop (the proof) at rational powers and do not do any problem involving irrational powers.
Comment: *For rational $r=\frac{p}{q}$ ... differentiable only at $x\neq 0$* But aren't $x\mapsto x^{2/1}$ and $x\mapsto x^{5/3}$ differentiable at $0$? I posted this related Q: https://math.stackexchange.com/questions/4841408/
Answer: Let's prove the power rule for an arbitrary real number. So $r$ can be an integer, rational, irrational. We make use of the fact that $e^{r\ln x}=x^r$.
$$
\begin{align*}
\frac{\text{d}}{\text{dx}} (x^r) & = \frac{\text{d}}{\text{dx}} \left(e^{r\ln x}\right)\\
&= e^{r\ln x}  \frac{\text{d}}{\text{dx}}\left(r\ln x \right)\\
& = e^{r\ln x}  \left(\frac{r}{x}\right)\\
& =rx^{r-1}.
\end{align*}
$$
where we have used the fact that $\frac{\text{d}}{\text{d}x}\ln x =\frac{1}{x}$. Of course this works if $x>0$.
Comment: You use $\ln x$ in $e^{r\ln X}$.  How do you know $x>0$?  By definition, (Grade 12 level) a real-valued function is differentiable at $x_0$ if the derivative exists at $x_0$.  Therefore, existence of the derivative must be established first.  Hence, the question 1.
Comment: @Sony: The Chain Rule is not just a formula: the proof of the Chain Rule actually shows that if $g$ is differentiable at $x$, and $f$ is differentiable at $g(x)$, then $f\circ g$ is differentiable at $x$ **and** $(f(g(x))' = f'(g(x))g'(x)$. So to know that $e^{r\ln x}$ is differentiable wherever it is defined, you just need to know that the exponential function is differentiable everywhere, and that the logarithm is differentiable for all $x\gt 0$ (because it is the inverse of a function that is differentiable everywhere and whose derivative is never $0$).
Answer: That it is true of nonnegative integer values of $r$ can be proved by any of several methods.

One of those uses mathematical induction and the power rule:
$$
\frac{d}{dx} x^{r+1} = \frac{d}{dx} (x^r\cdot x) = x\frac{d}{dx} x^r + x^r \frac{d}{dx} x = x(rx^{r-1}) + x^r\cdot 1 = (r+1)x^r.
$$
Another uses the definition of derivative directly:
$$
\frac{d}{dx} x^r = \lim_{w\to x} \frac{w^r-x^r}{w-x} = \lim_{w\to x}\frac{(w-x)(w^{r-1}+w^{r-2}x + w^{r-3}x^2 + \cdots + x^{r-1})}{w-x}
$$
$$
= \lim_{w\to x} (w^{r-1}+w^{r-2}x + w^{r-3}x^2 + \cdots + x^{r-1})
$$
$$
= \underbrace{x^{r-1}+\cdots+x^{r-1}}_{r\text{ terms}}.
$$
Another uses the binomial theorem and the definition of the derivative.  There's a bit of overkill in that one, since the binomial expansion gives you all $r+1$ coefficients where you need only the first two.

For positive $x$ and real $r$ (non-integer and not necessarily positive), you can use logarithmic differentation, provided you know the chain rule and how to differentiate the natural exponential and logarithmic functions:
$$
\frac{d}{dx} x^r = \frac{d}{dx} e^{r\log_e x} = e^{r\log_e x} \frac{r}{x} = x^r\cdot \frac{r}{x}.
$$
For negative integer values of $r$, you can use the reciprocal rule:
$$
\frac{d}{dx}x^r = \frac{d}{dx} \frac{1}{x^{-r}} = \frac{-\frac{d}{dx}x^{-r}}{x^{-2r}} = \frac{rx^{-r-1}}{x^{-2r}} = rx^{r-1}.
$$
It's also true of arbitrary real values of $r$ even when $x$ is not positive.  I'll think about the quickest way to prove that.  Except that it is not true when $x=0$ and $r<0$, since that involves dividing by $0$.
Answer: Prove power rule from first principle via binomial theorem and taking leading order term, now for negative exponents, we can use a trick. Consider:
$$ x^k \cdot x^{-k} = 1$$
The above identity holds for all $ x \in R -{0}$, differentiate it:
$$ kx^{k-1} x^{-k} + x^k \frac{d}{dx} x^{-k} =0$$
$$  \frac{d}{dx} x^{-k} =  -\frac{k}{x^{k+1}}$$
So, without any generalized binomial theorem, a student who knows binomial theorem + product rule would be able to do this :^)
It is definitely differentiable for all $r \in \mathbb{R}$ and all x in R except for case when $r$ is negative ; then x can't be zero
Answer: Edited to include absolute values.
Write $y=x^r$. Then $\log|y|=r\log|x|$. Then implicit differentiation gives $\displaystyle\frac{y'}{y}=r\frac{1}{x}$, or $\displaystyle y'=r\frac{y}{x} = r\frac{x^r}{x} = rx^{r-1}$. This works for all real numbers $r$, and so $f(x)=x^r$ is differentiable for all $r$ and for all $x$ for which $x^r$ is defined, unless $r-1<0$ in which case $f$ is not differentiable at $0$.
Of course, this assumes you already know that $\displaystyle\frac{\mathrm{d}}{\mathrm{d}x} \log(x) = \frac{1}{x}$.
Comment: @Sony: Arbitrary exponentials are only defined for positive bases; so $x\mapsto x^r$ for arbitrary $r$ is only defined if $x\gt 0$. For rational exponents which, in reduced form have an odd denominator, you can establish the Power Rule by considering $(x^{p/q})^q$, using the Chain Rule, and the Power Rule for positive integral exponents.
Comment: @Sony: Don't assume base 10.  "$\log x$" in this kind of context normally means $\ln x$ i.e. $\log_e x$.
Comment: @Sony: To echo Michael Hardy, $\log$ usually denotes whichever logarithm is more commonly used in the particular field. In mathematics (outside Calculus classes, at any rate) it almost invariably means the natural logarithm. In other areas it may mean something else (e.g., in Computer Science, particularly in analysis of algorithms, it often means logarithm base 2).
Comment: To apply log (I presume log base 10) $y$ has to be positive.  How do you know that $y$ is positive?
Comment: @Sony: I mean log base e. You are right to be concerned about $y$ being positive. Maybe you can adapt my method to take this into account.
Comment: It also appears to assume $x$ is positive (not just $y$).


PouchDb + Cordova não funcionando

Question: Estou desenvolvendo uma aplicação utilizando o PouchDb e criando aplicativos utilizando o Cordova.
Já testei a aplicação no chrome, firefox, android browser, safari, blackBerry browser, app for ios, apk no blackBerry e em todos eles funcionou corretamente.
O problema é somente no android, onde o app abre normalmente e quando o PouchDb começa a fazer o sync o aplicativo fecha sozinho sem mensagem de erro ou log algum. Já realizei vários testes em dois tablets diferentes (Android 4.1.2) e nos dois ocorre o mesmo problema.
Alguém já passou por este problema?
Preciso resolver isso urgente.
Muito obrigado.
Comment: Você está utilizando o CORS? No adb não existe nenhum log ou informações com a TAG do Cordova? Pelo que vi no github deles existe um problema no WebKit do Android 4.1 e 4.2.2 e infelizmente não existe solução para isso. Mais info no link: https://github.com/pouchdb/pouchdb/issues/504
Comment: Sim utilizando CORS. Consegui resolver aqui, é um problema com o *SqLite* + *Android*, acho que o Android não consegue gerenciar e mata a aplicação. Testei com o *WebSql* e funcionou corretamente, obrigado.
Answer: Realizei testes em versões diferentes do Android e constatei que o problema está no Android e não na aplicação. Esta versão do Android por algum motivo quando a aplicação começa a escrever e ler muitos dados no disco, apresenta alguma falha relacionada a despejo de memória ou algo parecido fazendo com que a aplicação feche inesperadamente.
Atualizado o Android para o 4.4.2 e passou a funcionar perfeitamente.

PouchDb + Cordova não funcionando


left outer join em uma cláusula or

Question: Estou com um problema com uma consulta, que preciso fazer um left outer join de uma tabela com outra, ou considerando os valores como 0, se for o caso, basicamente o que estava fazendo era o seguinte.
select B.coluna
from A, B
where A.coluna = B.coluna(+) or B.coluna = 0;

Mas está retornando o seguinte, dizendo que não é possível fazer um left join num operador or.
outer join operator (+) not allowed in operand of OR or IN.
Poderiam me ajudar a dizer como eu posso resolver isso?
Answer: tenta:
select
    B.coluna
from A
left outer join B on b.coluna = a.coluna or b.coluna = 0

tentando utilizar a mesma sintaxe que você utilizou, acho que ficaria assim:
select B.coluna
from A, B
where (A.coluna = B.coluna or B.coluna = 0)(+);

left outer join em uma cláusula or


Proving that a theorem is invalid ($\left(A\cap B\right)\triangle C\subset \left(A\triangle C\right)\cap \left(B\triangle C\right)$)

Question: Is this a valid way to show that the theorem is incorrect?
Theorem: $\left(A\cap B\right)\triangle C\subset \left(A\triangle C\right)\cap \left(B\triangle C\right)$
Suppose $a\in \left(A\cap B\right)\triangle C$. Then either $a\in C\setminus \left(A\cap B\right)$ or $a\in \left(A\cap B\right)\setminus C$. Consider the case where $a\in C\setminus \left(A\cap B\right)$, this means $a\in C$ and either $a\notin A$ or $a\notin B$. Consider the case where $a\notin A$ and $a\in B$. Then $a\in B$ and $a\in C$, but this contradicts $a\in(B\triangle C)$.
Thus, the theorem is invalid.
Comment: If a statement is false or invalid then it's not a theorem. Instead of talking of an "invalid theorem" you should talk about a false statement.
Comment: To prove that such a statement is false you must provide a counterexample...
Answer: Take
$$A=\{1,2,3\}\,,\,\,B=\{1,2\}\,,\,\,C=\{3\}$$
then
$$(A\cap B)\Delta C=\{1,2\}\Delta \{3\}=\{1,2,3\}$$
yet
$$\left(A\Delta C\right)\cap\left(B\Delta C\right)=\{1,2\}\cap\{1,2,3\}=\{1,2\}$$
Answer: What you have done is a draft.
You have shown that
an element $a$ such that $a\in C$ and $a\not\in A$ and $a\in B$
satisfies $a\in (A\cap B)\triangle C$ and $a\not\in (A\triangle C)\cap (B\triangle C)$.
However, this does not immediately show that $(A\cap B)\triangle C\subset (A\triangle C)\cap (B\triangle C)$ is false,
because such an element $a$ may not exist.
You need to also show that an element with this property exists for some sets $A$, $B$, $C$.
The simplest way to do it is to find an explicit example like what @DonAntonio did.
In fact, after you have found a counterexample,
the draft is not necessarily needed to show that the statement is false (although it might be more explanatory to include them,
provided you state clearly what you are trying to show).

By the way, the word theorem is used to refer to a statement that is true.
Use the word proposition or statement for a sentence that can be true or false, but not necessarily known to be true or false.
Answer: If you want to carry out a proof building a counterexample, then you must investigate the general case and not just for one admitted part $a\in C\setminus \left(A\cap B\right)$, but also for $a\in \left(A\cap B\right)\setminus C$ , because "or" can be true depending on each of them. So, I suggest to consider following:
$$x\in \left(A\cap B\right)\triangle C\Leftrightarrow \\
\Leftrightarrow \Big[x \in A \land x\in B\land x\notin C \Big] \lor \Big[x \in C \land \neg(x \in A \land x\in B ) \Big] \Leftrightarrow \\
\Leftrightarrow \Big[x \in A \land x\in B\land x\notin C \Big] \lor \Big[x \in C \land (x \notin A \lor  x \notin B ) \Big]  \Leftrightarrow \\
 \Big[x \in A \land x\in B\land x\notin C \Big] \lor \Big[x \in C \land x \notin A \Big] \lor \Big[x \in C  \land x \notin B \Big]\ \ (1)$$
From obtained $3$ square brackets cases you should consider all $3$, not only one from them, because, sorry for repetition, "or" can be true depending on each of them.
Right side of implication we can (check it, please) wrote as
$$x \in \left(A\triangle C\right)\cap \left(B\triangle C\right) \Leftrightarrow \\ \Leftrightarrow
\Big[ x \in A \land x\in B\land x\notin C\Big] \lor \Big[ x \notin A \land x\notin B\land x\in C\Big] \ \ (2)$$
So, if we find one such case, where is possible to $(1)$ to be true, when  $(2)$ is false, then we say $(2)$ is not following from $(1)$ and we need to build existing example for this case. What you did is only writing plan how to proof, not looking in details, but it missed implementation, real example.
For example: suppose second square bracket case is true i.e.
$(\exists x)(x \in C \land x \notin A )$ is true. Immediately follows that $(2)$ is false. Now, all the rest is we need "alive" example.
Btw, DonAntonio, in his answer, brought counterexample exactly based on this case.


Qual erro é este e o que posso fazer para arruma-lo?

Question:

Error: ADB exited with exit code 1 Performing Streamed Install adb:
  failed to install C:\pedidos\build\app\outputs\apk\app.apk: Failure
  [INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package com.example.pedidos
  signatures do not match previously installed version; ignoring!] Error
  launching application on Mi 9 SE. Exited (sigterm)
Comment: **`Package com.example.pedidos signatures do not match previously installed version`**
Answer: Busque entender o erro:

[INSTALL_FAILED_UPDATE_INCOMPATIBLE: Package com.example.pedidos
  signatures do not match previously installed version; ignoring!]

Falha de incompatibilidade ao instalar o update, a assinatura do teu package (Seu aplicativo) não é igual a versão já instalada; Update ignorado!

Desinstale o aplicativo do seu celular e compile novamente que dará certo.
Isso as vezes ocorre quando você compila por outro computador, ou cria um outro projeto com o mesmo nome de um já previamente instalado em seu dispositivo.
Atenção
Fique alerta ao reinstalar, pois como seu celular é um Xiaomi irá pedir permissão para a instalação, então, quando aparecer o popup em seu celular marque a opção "Sempre permitir" e clique em Instalar.
Answer: Aconteceu comigo recentemente mesmo sem estar instalado o app no aparelho, verifiquei que eventualmente pode ter sido mal desinstalado, o que fiz para reparar foi instalar a versão que tenho na playstore e desinstalar através do comando
<code>adb uninstall 'packageName'
</code>
daí resolveu. Se você não tive-lo na playstore, você pode extrair o apk através de uma máquina virtual e instalá-lo no aparelho, ou ainda compilá-lo.


Drupal 7 adding rel to the href's of Login and Registration

Question: I'm using Lightbox as a modal box solution and have been having
an issue trying to get modal windows for the default Login and
Registration links. I'm trying to access from inside a module that
I"m currently using to make all the changes. I've tried several
other "Box" solutions and Lightbox seems to be what I'm looking for,
but I cannot figure out the hook to add rel='lightbox' to login and
reg. Could someone point out what it is for me?
EDIT I tried using this in my base theme, which will give me a
modal on both reg and login, but shows an empty form?
function spti_base_preprocess_page(&$variables) {
<code>/* .....stuff..... */

    // add the system user-menu into the page as its own thing
    $variables['platform_user_menu'] = menu_navigation_links('menu-platform-user-menu');

    foreach($variables['platform_user_menu'] as &$hijackLinks) { $hijackLinks['attributes']['rel'] = 'lightframe'; }

    $variables['page']['platform_user_menu'] = array(
      '#theme' => 'links__system_user_menu',
      '#links' =>   $variables['platform_user_menu'],
      '#attributes' => array(
        'id' => 'platform-user-menu',
        'class' => array('links', 'inline', 'clearfix'),
      ),
  );

/* .....stuff..... */

}
</code>
Answer: Yes you could spend time tearing apart templates, and hacking in the required code, I would say the cleaner, 'more drupal' solution would be to use a combination of

Menu and menu items
The module menu attributes

From the project page:

This simple module allows you to specify some additional attributes
  for menu items such as id, name, class, style, and rel.


Finding a solution to $xu_x+(y+1)u_y=u-1$ given an initial condition

Question: Consider the following PDE:  $$xu_x+(y+1)u_y=u-1.$$
Using this formula:  $$\frac{dx}{x}=\frac{dy}{y+1}=\frac{du}{u-1}.$$
This yields $c_1=\frac{y+1}{x}$ and $c_2=\frac{u-1}{x}.$
We have:
$$F\left(\frac{y+1}{x}\right)=\frac{u-1}{x}.$$
Given the following Cauchy condition - $u(x,2x-1)=e^x$.  This yields $$xF(2)+1=e^x.$$
Am I on right right track?  I'm a little confused because we have an $F(2)$.
Comment: I don't follow the line "This yields..." Aren't you supposed to integrate $\frac{dx}{x}=\frac{dy}{y+1}=\frac{du}{u-1}$?
Comment: You integrate two at a time.  For example, I did the left most and middle, and then the left most and the right most one.  That's how I yielded $c_1$ and $c_2$.
Comment: But integration should produce something like $\ln x$, $\ln (y+1)$, $\ln (u-1)$...
Answer: Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dx}{dt}=x$ , letting $x(0)=1$ , we have $x=e^t$
$\dfrac{dy}{dt}=y+1$ , we have $y+1=y_0e^t=y_0x$
$\dfrac{du}{dt}=u-1$ , we have $u(x,y)=F(y_0)e^t+1=xF\left(\dfrac{y+1}{x}\right)+1$
$u(x,2x-1)=e^x$ :
$xF(2)+1=e^x$ , which is impossible.
$\therefore$ There is no solution.


How to get screen space you've got for your app or the height of top- and bottom bar in MAUI?

Question: I have a problem calculating the position of some items and if they are visible on the screen in MAUI, using a function like
public Point GetScreenCoords(VisualElement view)
{
    var result = new Point(view.X, view.Y);
    while (view.Parent is VisualElement parent)
    {
        result = result.Offset(parent.X, parent.Y);
        view = parent;
    }
    return result;
}

More details see there: MAUI find out if something is on screen does not work as expected
Now I think I found the reason for the problem. I assume it is the space needed by the small bar at the top of the screen containing the battery indicator and also the bigger bar at the bottom of the screen containing the triangle, circle and square controls. I assume that that space is included in DeviceDisplay.MainDisplayInfo.Height but it is not really available for my app.
I assume if I could respect their heights in the calculation, it would be correct. So my question is:
How can I find out the height of these two bars under MAUI? Or do they posess any Android standard height? What would be this in MAUI device-independent units? Or in screen pixels?
Or alternatively, how can I get the screen height that I really do have for my app? (It is not DeviceDisplay.MainDisplayInfo.Height.)
I am aware of a similar question (MAUI: how to get the system navigation bar height on Android?) but that one only asks about the bottom bar and has got no accepted answer.
Comment: You really should consider the excellent plugin  [OnScreenSize Markup Extension.](https://github.com/carolzbnbr/OnScreenSizeMarkup.Maui) You then set size break points to ensure you content will scale correctly to fit on all displays.
Answer:
How can I find out the height of these two bars under MAUI?

You can try to use the following code to do that:
 var statusid = Platform.CurrentActivity.ApplicationContext.Resources.GetIdentifier("status_bar_height", "dimen", "android");
 var statusbarheight = Platform.CurrentActivity.ApplicationContext.Resources.GetDimensionPixelSize(statusid);
// this is the status bar height
 var navid = Platform.CurrentActivity.ApplicationContext.Resources.GetIdentifier("navigation_bar_height", "dimen", "android");
 var navbarheight = Platform.CurrentActivity.ApplicationContext.Resources.GetDimensionPixelSize(navid);
// this is the navigation bar height

how can I get the screen height that I really do have for my app? (It
is not DeviceDisplay.MainDisplayInfo.Height.)

You can use the following code to get the real scren height for your app:
var displaymanager = Android.App.Application.Context.GetSystemService(Android.Content.Context.DisplayService) as Android.Hardware.Display.DisplayManager;
var defaultdisplay = displaymanager.GetDisplay(Android.Views.Display.DefaultDisplay);
var gotheight = Android.App.Application.Context.CreateDisplayContext(defaultdisplay).Resources.DisplayMetrics.HeightPixels;
//this is the real height

And the DeviceDisplay.MainDisplayInfo.Height is the full screen height(contains the two bars).
===================================================
So you can do a judgment :
int realheight;
if(gotheight == DeviceDisplay.MainDisplayInfo.Height - statusbarheight -  navbarheight)
    realheight = gotheight;
else if (gotheight == DeviceDisplay.MainDisplayInfo.Height||gotheight == DeviceDisplay.MainDisplayInfo.Height -  navbarheight)
    realheight = gotheight - statusbarheight;

Comment: (1/2) Thank you. Your solution seems not to be 100% correct, but very close. I've got an Emulator with H=1920 pix = 640 device-independent units (diu).    I assume diu = pixel divided by DeviceDisplay.MainDisplayInfo.Density, which is 3 here.
I've measured the real space I have got for my app to be 570 diu.
The values I get from your code are
gotheight = 1776 pix = 592 diu,
statusbarheight = 72 pix = 24 diu,
navbarheight = 144 pix = 48 diu.
So gotheight - statusbarheight = (592-24) diu = 568 diu.
Comment: (2/2) Which is very near to what I am measuring.  Any explanations?
Did you mean that gotheight - statusbarheight = real space I have got?   I understood you that gotheight should be the real space I have got.
Comment: I tested on the RedMi physical device and the `gotheight = DeviceDisplay.MainDisplayInfo.Height - statusbarheight -  navbarheight`. @AndreasW
Comment: And can you show the way to get the 570 diu? @AndreasW
Comment: I get to the 570 diu real available height by creating a Border as top element in the mainpage and then changing its HeightRequest until it visually fits exactly. There might be a mesurement error of plus/minus 2 diu  ...... I see two of your comments are contradicting about gotheight, statusbarheight, navbarheight and DeviceDisplay.MainDisplayInfo.Height!? @Liyun Zhang
Comment: I have tested. On the emulator, the `gotheight = DeviceDisplay.MainDisplayInfo.Height -  navbarheight.` So if you want to get the real space can just use the `gotheight - statusbarheight`. And you said mesurement error of plus/minus 2 diu should be causedby the way you get the 570 diu. And the contradiction in my comments is because the different data between the emulator and the physical device. You can debug on physical device to check it. @AndreasW
Comment: So you say it is different for emulator and physical device. Wouldn't this contradict the emulator's purpose? And maybe it's caused by something different? It might be so on some devices and such on some others.......    How can I *in code* find out which one is true? @Liyun Zhang
Comment: Actually, according to the official document about the [DisplayMetrics.HeightPixels](https://developer.android.com/reference/android/util/DisplayMetrics#heightPixels), the gotheight is what you want. But you can do a judgment to detect if the `gotheight` or the `gotheight - statusbarheight` is you want. @AndreasW
Comment: And did you check it on a physical device? @AndreasW
Comment: I checked on three emulators and two physical devices. On all of them, gotheight - statusbarheight = available height.   Which is different from your results - and from the official documentation!?  Very strange. Still, it seems, there is no real answer on how to find out this height reliably!? @Liyun Zhang
Comment: Please check the code about the judgment in my answer. @AndreasW
Comment: After having accepted your answer, I found a case which is not represented there. I have a case where gotheight == DeviceDisplay.MainDisplayInfo.Height but realheight = gotheight - statusbarheight. May you extend your answer? @Liyun Zhang
Comment: Thanks for your feedback, but did that case have the bottom navigation bar? @AndreasW
Comment: It is an Phone-H-DPI emulator with Android 7 API 24 with a screen size of HxW=800x480, density is 1.5. Your code says (in px)  gotheight=800 statusbarheight=36, navbarheight=72.  The really available hight is 764 px. @Liyun Zhang
Comment: But if so, there is no space for the navigation bar. @AndreasW
Comment: There is no navigation bar on the screen. Check it out, create an emulator based on Phone H-DPI 4". @Liyun Zhang


Custom Application Encryption

Question: I am currently looking to add encryption to a server application (programmed in C) that passes raw data, unencrypted data over TCP to clients (a large number of different applications programmed in many different languages).
What is the best way to do this? Public-key cryptography? If so, how would the process go?
Thanks!
Answer: If you have to ask, you're probably not qualified to be doing cryptographic work. It is far to easy to make a subtle mistake in crypto processing that breaks your entire system's security, and unlike most other bugs, it is not at all obvious until someone else breaks your system.
Just use SSL (aka TLS). The folks that designed the SSL/TLS specs and libraries have already done all the hard work for you.
Comment: especially if you have "a large number of different applications programmed in many different languages". TLS is very widely supported.
Comment: Whether or not I'm qualified or not (which I'm not, admittedly) doesn't matter because the work needs to be done, and I'm the one to do it. So I'm therefore looking at the best way to get started.
Comment: Also, none of the other applications have support for encryption yet. The only thing I have control over is the server, so I'm looking for the best, most flexible way that other clients would be able to add this support for.
Comment: @Fran, what I mean by this is, it's fine to use a SSL library. But if you want to write a new SSL-like protocol from scratch, stop. Very few people have the kind of qualifications to do that and expect the result to be secure.
Answer: SSL: secure socket layers, which initiates and transmits encrypted data.
TLS: transport layer security, which asks to starttls and the answer to that is a list of capabilities, then the transmission can continue using the best mutually accepted encryption.
Note: the capabilities may include cleartext.
I suggest reading upon how to extend  your existing protocol to support TLS, by looking at an example, say, the smtp starttls( rfc 2487 ).  your time invested will be rewarded.
Answer: OpenSSL suits my needs! A quick view at the documentation and tutorials pointed me in the right direction.

Custom Application Encryption


jQuery.load to load HTML file

Question: I've never used jQuery before this, but I'll explain what I'm trying to do.
index.html
<!DOCTYPE html>

        <title>My Awesome Website</title>
        <link href="style.css" rel="stylesheet" type="text/css"/>
        <link rel="shortcut icon" href="/favicon.ico" />

Please enable Javascript!

navbar.html

<object width="64" height="64" data="favicon.svg" type="image/svg+xml"></object>

<object width="64" height="64" data="icons/tech.svg" type="image/svg+xml"></object>

<object width="64" height="64" data="icons/games.svg" type="image/svg+xml"></object>

<object width="64" height="64" data="icons/contact.svg" type="image/svg+xml"></object>

So what I'm trying to do here, is have many HTML pages which all link to one navbar html page, so when I change the navbar.html, I dont have to change every page.
I already have another question here. Davor Milnaric suggested "if you are using jquery, you can try with '.load()' function. api.jquery.com/load" but I can't get it to work. What am I doing wrong? How do I fix it? Any help would be much appreciated.
Answer: You need to do 2 things:

Use $(document).ready() - read here; All jQuery code must be wrapped like this:
$(document).ready(function(){

    //jquery code goes here....

});

Change
$('#navbar').load('./navbar.html');

to
$('#container').load('./navbar.html');

.. you don't have an element with id="navbar"
and according to this:

If no element is matched by the selector — in this case, if the document does not contain an element with id="result" (in our case "navbar") — the Ajax request will not be sent.
Answer: It's also possible that you need to wait for the DOM to load.

Comment: Hi, Thanks for you're reply. :) When I try this, nothing changes, the navbar still doesn't load... Any ideas?
Comment: if you open `dev tools` for the browser, you will see the error, it could be  'Cross origin requests are only supported for protocol schemes: http, data...'

jQuery.load to load HTML file


How best to estimate regression parameters subject to constraints?

Question: The setting
Consider a least squares model for $y$ as a function of $x,$ possibly nonlinear in the parameters.  Abstractly this can be expressed as
$$y = f(x;\theta) + \varepsilon$$
with the usual assumptions: the $\varepsilon$ are iid zero-mean errors of finite variance $\sigma^2.$
Further suppose this model represents a well-established mathematical or physical law that constrains the "reasonable" values of the parameter $\theta.$
As a concrete example, consider a standard model in radiological measurements such as a (simplified) Lorentzian peak at $x=0$ added to a constant background:
$$f(x,(\alpha,\beta,\gamma)) = \frac{\alpha}{\beta + x^2} + \gamma.$$
All three parameters $\theta = (\alpha,\beta,\gamma)$ are of interest and should be estimated as accurately as possible.   However, the only physically realistic values of the parameters are non-negative (and $\beta$ is nonzero).  Here is an illustration.

Generally, suppose there is a known nontrivial set $\Theta$ of realistic values of $\theta.$  I will refer to $\Theta$ as the constraints.
A fundamental question is whether the peak is present at all.  That can be tested with the null hypothesis $H_0:\alpha=0,$ a situation that often holds in reality (maybe the peak is produced by a contaminant that usually is not present, for instance).
When fitting such a model, it is possible for any of the parameter estimates $\hat\theta$ to lie outside the constraints.  (That is, $\hat\theta\notin \Theta.$)  For instance, $\hat\alpha$ might be negative when (a) the true value $\alpha$ is much smaller than the error standard deviation $\sigma$ and (b) due to random (bad) luck, it looks like the peak is inverted.  This happens frequently (about half the time) when $\alpha$ truly is zero.
The question
One has two options in these circumstances:

Use whatever estimates $\hat\theta$ the least squares procedure provides, even if they lie outside the constraints.

Force the least squares solution to conform to the constraints.

There are cogent arguments for and against both options: (1) can yield unrealistic estimates, but when applied to a large number of datasets might provide better average estimates on the whole; whereas (2) is forced to yield realistic estimates, but that can introduce a bias.  For instance, forcing $\alpha$ to be nonnegative will produce positive nonzero estimates from time to time even when $\alpha$ is truly zero.  In general, we're considering the possibility $H_0: \theta\in\partial\Theta$ that the parameter lies on the boundary of the constraints and wish to test the alternative $H_A:\theta\in \Theta \setminus \partial\Theta$ (the interior of the constraint space).

Is one of these options preferable?  If so, which one and why?  Is one of these options so problematic that it should not be used?  If so, which one and why?

I also invite suggestions for additional options (such as regularization, penalized least squares, and so on), provided they can be shown superior to both (1) and (2).

I welcome answers from varying perspectives (classical, Bayes, etc.) and have enough bounty points to reward multiple good answers ;-).
Comment: I would submit that another advantage of approach 1) is that getting unrealistic estimates of model parameters can prompt us to take a step back from the modeling phase of data analysis and head back to the EDA phase, or maybe even the data collection phase, because it allows our expectations to be contradicted if something unexpected is going on.
Comment: @John Agreed, but this is not EDA or a modeling phase.  Imagine that this fitting procedure is, say, converting an electrical response in a consumer scale to a weight and it will be used in an automatic turnkey capacity to drive an LED readout of that weight.
Comment: This seems to be a very cool example of the bias-variance trade-off Hastie, et al discuss with regularization methods. My question to you is whether you're more interested in accurate information or with consistent information. Obviously both solutions you pose are feasible, it sounds like you're interested in a more philosophical answer, yes?
Comment: My concern about option #1 is what to do with a preposterous value. For instance, we could do something wild and get a variance estimate below zero. Okay, we have our $\hat\sigma^2_{\text{weird}}<0$, but what does that mean?
Comment: In empirical likelihood estimation it is all about incorporating constraints https://en.m.wikipedia.org/wiki/Empirical_likelihood maybe a potential answer can discuss this method as well, although this may not be needed if the distribution of measurements is known. Incorporating constraints may be required when convergence to a feasible mimimum of the loss function is a problem.
Comment: @whuber stop me if you've heard this one before, but this sounds like it might be relevant information that had ought to be edited into the body of the post ;)
Comment: Did you see https://stats.stackexchange.com/questions/212138/what-are-some-motivations-for-using-nonnegative-least-squares
Comment: @Ggjj11 Thank you for drawing attention to that thread, because it definitely is relevant.  My actual problem (which is more complicated than the simple example I give here) is close to Example 1 in the post by Sextus Empiricus.
Comment: I argue against #1 on the basis that your best possible estimate for $\theta$ must include your prior beliefs, including physical or mathematical constraints.
Answer:
Is one of these options preferable? If so, which one and why? Is one of these options so problematic that it should not be used? If so, which one and why?

Depends on your goal. If you trust your priors, model specification and error distribution, you would like to include as much of those prior beliefs in the model as you can.
If you want to perform an analysis on a large number of samples, on the other hand, you might want to perform a different analysis altogether. Of course, if you need to find out whether there is some systematic bias in your measurements, you need to use an estimator that has minimal bias -- but then could choose to model the bias directly.
So in general, I would dismiss your pro towards the method (1): can yield unrealistic estimates, but when applied to a large number of datasets might provide better average estimates on the whole, and only worry about the bias if it is the quantity you want to model.
Frequentist vs. Bayesian interpretation
There was a paper I found comparing frequentist constraints and bayesian priors, the difference of which comes down to interpretation as well as practical usage. Since the frequentist approach treats the parameter $\theta$ as unknown, but fixed, element of $\Theta$, it does not make much sense to me to allow values that are physically impossible -- i.e. there is no sensible interpretation for those. In practice, then, this means that the estimation must be restricted to a set of parameters that satisfy the constraints, if you wish to set them. Alternatively, you simply accept that your model doesn't actually model the phenomena.
In the Bayesian framework, the parameter itself is a random variable, for which we know at least that $\theta \in \Theta$. Of course, there are infinitely many distributions that can be used to assign total probability of 1 to that space. The interpretation  of prior distributions to restrict parameter values is straightforward, and you get the (posterior) probability distribution of the parameter values, which, again, has quite simple interpretation. It could include physically impossible values, but in that case it is clear that they were, also, included in your prior beliefs.
I would say, then, that in the Bayesian case it is quite OK to not restrict the parameter to a certain range, and this has a simple explanation: We chose to allow the parameter to take those values, even if we knew that they were impossible. Conversely if you choose to restrict the parameter space by using a prior, the meaning of that is clear and reflects the analyst's prior beliefs: There is zero probability that the parameter could take these values.
If you are concerned about systematic biases introduced by the prior, one option would be to use cross-validation to check the distribution of the errors.
Bayesian approach in practice
Most common (and trivial) case where you restrict the parameter space by a prior functions is when setting a prior for variance of normal distribution: Inverse gamma distribution is often used. For most parameters there is often enough data that accurate prior distributions matter little, and noninformative, computationally easy (e.g. conjugate) priors are often chosen.
More relevant to your question, perhaps, is this is done with physical models in practice. One paper that might be of interest is A Bayesian Search for the Higgs Particle, where one distribution of the prior is based on the theoretical, expected mass of the Higgs Boson -- and another on what we might see if it does not exist.
The same author also had another paper that is more general and thus maybe more relevant to your question.
Answer: Option 1 is better. Here's why:
My favorite professor (Herman Friedman) used to say ``if you're not surprised, you haven't learned anything.''
Option 2 is a way of telling the data not to surprise you. It's the antithesis of science.
But what if option 1 gives you surprising values? Then you figure out why. You learn something. Maybe it's something mundane (often, data entry errors or coding errors) and you just fix the problem. But once in a wonderful while, it isn't mundane and you discover something. The model is wrong. Or, at least, wrong in your application.
Suppose you are interested in the heights of men and women. Maybe you have some theory about covariates. But you know men are taller than women, so you constrain the estimates. But what if you discovered some subgroup of people where men are not taller?  That's really, really interesting. And someone else will find it, not you, and there goes your great discovery.
(I don't understand your example well enough to use it, but if it is really an absolute physical constraint, then you are in the first paragraph, and finding the weird estimates lets you discover that.)
Comment: I understand where you're coming from, and am sympathetic, but I have to disagree with your logic.  First, there's a question of how significant these impossible results are: they might be within a couple standard errors of the parameter boundary.  That's no evidence of bad data or bad code.  Second, if they are *way* off, then indeed that's a nice check of the algorithm, but it doesn't really answer the question.  What should one do when the code and the data are *good*?
Comment: Good point.  My main reason for thinking Bayesian for this problem is that it doesn't require a dichotomous solution (hard constraints).  Favoritism of the constraint still allows some possibility of negative values, for example.
Comment: @Dave No. You can have prior beliefs, whether you formalize them in a Bayesian framework or not. But you can still be surprised. Bayesians let the informative priors be adjusted by data.
Comment: @Frank I was hoping someone would advance such an argument.  One of my concerns, though, rests on the effects of strong priors, especially (as in many practical applications) the amount of data is relatively small.  (My illustration is typical and in many settings there are even fewer data points than I have shown.)  Any further thoughts you (or others) might have about Bayesian approaches would be most welcome.
Comment: Isn't your argument against option #2 equivalent to arguing against informative prior distributions?
Comment: In the circumstances you posit, I agree,  But I guess I need to re-emphasize that having a *negative* peak is not a surprise: it's non-physical.  This isn't a matter of scientific discovery, but purely of estimation and testing.  Here's another example: suppose the model estimates weights of solid objects placed on a scale.  Are you arguing that the scale should report negative weights to its users?
Comment: @whuber No, I'm arguing that, if you get impossible results, either you have bad data or bad code. Either of those should be fixed. But if you somehow force your program to give you something plausible, you won't find the error. But your results will still be wrong, just not so obviously wrong.
Comment: Along the lines of @PeterFlom's comment above, Bayesian priors can be used to strong favor positive parameter values, but allow for negative values.  Importantly this approach allows one to compute the probability that the constraint is real.
Comment: @whuber You could also argue that when the data is small, that is precisely when you need to use strong priors to get any meaningful results at all. Of course, those priors need to be sensible and warranted, and you need to understand that they might swamp your data altogether, but otherwise you would have no meaningful signal at all. Hierarchical modelling, where applicable, would be another approach.
Comment: @PeterFlom in your example, if you constrained the estimates would you then not see the same results when your model breaks down for this specific group? The only difference being instead of outlier parameter value you see outlier error distribution or summary statistic.
Answer: During reading What are some motivations for using nonnegative least squares? I came across nonnegative least squares which imposes the constraint of all coefficients being nonnegative. The main argument seems to be that prior knowledge is encoded in the constraints and solutions which violate the constraints are known to be unreasonable.
Comment: Thank you. This restates point (2) in my question -- but it doesn't seem to take us any closer to a resolution of the tension between points (1) and (2).
Answer: One dimensional simple model
A simple model that illustrates a bit what is going one is a single parameter model
$$X_i \sim N(\theta,1) \quad \text{with the constraint $\theta \geq 0$}$$
For a sample of size $n$

the sufficient statistic is $ T=\bar{X}$ (and we could use this as an unconstrained estimate $\hat{\theta}_{unconstrained} = T$)
the constrained maximum likelihood estimate is $\hat{\theta}_{constrained} = \max(0,\bar{X})$.

Histograms for the distributions for these, when $n=5$ and $\theta = 0.5$, look like below. The distribution of the constrained estimate is a rectified Gaussian distribution.

That peak at $mle=0$ is a point mass and represents the tail from $T<0$ that is now closer to the true value $\theta$. In this case the boundaries are making the mean squared error smaller.
Variance, bias, and combining multiple experiments
The sufficient statistic $T$ has no bias but the variance is large and the mean squared error will be larger.
$$\text{mean}(T) = \theta\\
\text{var}(T) = \frac{1}{n}\\
MSE(T) = \frac{1}{n}$$
The constrained maximum likelihood estimate $\hat{\theta}_{constrained}$ has a bias, but due to a smaller variance the mean squared error will be smaller.
(for derivations see: Expectation and Variance of Gaussian going through Rectified Linear or Sigmoid function)
$$\text{mean}(\hat{\theta}_{constrained}) = \theta (1-p) + \frac{\phi(z)}{\sqrt{n}}\\
\text{var}(\hat{\theta}_{constrained}) = \theta^2 p(1-p) + \frac{\theta}{\sqrt{n}} \phi(z)(2p-1) + \frac{1}{n} (1-p-\phi(z)^2) \\
MSE(\hat{\theta}_{constrained}) =  \frac{1}{n} (1-p) - \frac{\theta}{\sqrt{n}} \phi(z) + \theta^2 p$$
Where $z = -\theta \sqrt{n}$ and $p = \Phi(z)$ and $\phi$ and $\Phi$ are the standard Gaussian pdf and cdf.
The issue/consideration for the one dimensional simple model is

(1) can yield unrealistic estimates, but when applied to a large number of datasets might provide better average estimates on the whole;

When we have multiple estimates then the variance will reduce and the error of the average of estimates will approach the bias.
So when we use averages of estimates then using biased estimates can be a disadvantage, albeit these estimates having a smaller error when compared individually.
Depending on how the model is used we may prefer methods 1 or 2.

If we are not using averages then method 2 is better because the mean squared error is larger.
If we will use some averaging of several estimates (and we are not able to use all the data at once making a single estimate instead of averaging multiple estimates) then model 1 might be better. It will depend on the ratio between variance and bias.

Method 2 might give a better estimate, but that estimate might not be the best statistic for further analysis. In the example above this has been made more salient by method 1 being equivalent to the sufficient statistic, and method 2 is effectively loosing information. The same principle might be true for other methods (like regularised regression) where some estimate has 'improved' properties, but results in a loss of information.
Comment: At the end I wrote "It will depend on the ratio between variance and bias". In a situation like non-negative least squares with many correlated components as in the elsewhere linked question [What are some motivations for using nonnegative least squares?](https://stats.stackexchange.com/questions/212138/), the variance of the unconstrained model will be very large. In such a case, even when method 1 may lead to a better estimate for averages, it only does so when the number of averaged samples is extremely large.
Comment: In addition, in the case of peak detection and the prior assumption that peaks are mostly absent, it might not be useful to allow negative values. These negative values will coincide with other values being positive. An interesting alternative for nnls might be LASSO https://stats.stackexchange.com/a/426984/
Comment: Thank you for your analysis, +1.  But please bear in mind the "fundamental question," that is, whether the peak is present at all.  That is *so* very important (it's the question of whether a substance has been detected and that can have huge consequences) that variance isn't even a secondary consideration except insofar as it might be a proxy for estimation precision.
Comment: @whuber the example here is a lot more simple to investigate what is going on. I believe that this main issue is that approach 2 might be a good estimate, but it is not a good (informative) statistic. If applied to some hypothesis test, then a similar issue should be going on, that we rather have as data the different values T instead of the different values $\hat{\theta}_{constrained}$.


How do I translate empty text of a view?

Question: I have created a view with empty text using PHP code. Now, when I try to translate it through the translation interface (admin/build/translate/search), while I find the string (it show up all the PHP code) and translate it (I did it by adding the PHP code again with the translated strings), when I change the language of my site I see nothing. When I come back to English, it showed up correctly.
Does anyone have any idea?
Answer: If this view is showing inside of a block then make sure you have the translation "Make this block translatable" is checked, and what ever language you want to translate to is also checked.
hope this helps.
Comment: Thank you for your answer. No the view isn't inside of a block. I use a page display of the view as a panel pane.
Comment: do you have your text wrapped around t('like this')?


Find Jordan-Normal form of a given matrix

Question: I am trying to write the matrix $A=\begin{pmatrix} 2 & 2 & -5 \\ 3 & 7 & -15 \\ 1 & 2 & -4 \end{pmatrix}$ in Jordan-Normal Form.
It's characteristic polynomial is $|A-xI|=x^3-5x^2+7x-3=(x-1)^2(x-3)=0$
So, it has eigenvalues 1 and 3. I calculated three eigenvectors $v_1=\left(\begin{smallmatrix} 1 \\ 3 \\ 1 \end{smallmatrix}\right), v_2=\left(\begin{smallmatrix}5\\0\\1\end{smallmatrix}\right), v_3=\left(\begin{smallmatrix}-2\\1\\0\end{smallmatrix}\right)$.
So $Z=\begin{pmatrix} 1&5&-2\\3&0&1\\1&1&0\end{pmatrix},\text{ }Z^{-1}=-\frac{1}{2}\begin{pmatrix}-1&-2&5\\1&2&-7\\3&4&-15\end{pmatrix}$
$Z^{-1}AZ=\begin{pmatrix}3&0&0\\0&1&0\\0&0&1\end{pmatrix}$, but shouldn't the answer be
$Z^{-1}AZ=\begin{pmatrix}3&0&0\\0&1&1\\0&0&1\end{pmatrix}$?
Thanks.
Answer: Everything you have calculated is correct. A Jordan-Normal-Form for your matrix is $$\pmatrix{3 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 1}$$
Another solution would be for example $$\pmatrix{1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 3}$$
The Jordan-Normal-Form do not have to be unique and depends on how you arange the vectors in your matrix $\mathcal{Z}$
But $$\pmatrix{3 & 0 & 0 \\ 0 & 1 & 1 \\ 0 & 0 & 1}$$ cannot be a Jordan-Normal-Form of your matrix. For the eigenvalue $1$ the dimension of the corresponding eigenspace is $2$ so your matrix is even diagonalizable!