About open subsets of affine schemes.

Question: Let $A$ be a commutative ring with unity. Consider its associated affine scheme $(\operatorname{Spec}(A),\mathcal{O}_A)$. I was wondering if the restriction morphism,
$$A \xrightarrow{r|^X_U} \mathcal{O}_A(U)$$
would induce an open immersion of $\operatorname{Spec}(\mathcal{O}_A(U))$ into $\operatorname{Spec}(A)$. I know this for the case of distinguished opens. What happens in the general case?
Comment: It is true if $A$ is a UFD. My first source to look for a counterexample would be a Dedekind domain with a non-prinicipal ideal. I am not sure though.
Comment: I am sorry my previous example was wrong .. but you can instead use the examples given in this post http://math.stackexchange.com/questions/143954/isolated-non-normal-surface-singularity
Comment: Just a comment--not fleshed out. Let's assume that $A$ is a domain. Then if $U=X-Z$ for $\text{codim}(Z)\geqslant 2$ then 'algebraic Hartog's lemma' implies that $r\mid_U^X$ is an isomorphism, and so no question there. So, the case when $A$ is normal one only has to worry about complements of codimension $1$ primes. One might then, assuming that $A$ is locally factorial (e.g. if it's regular) reduce to the local case since every codimension $1$ prime (i.e. every divisor) is locally principal--i.e. reduce it to the distinguished affine case.
Comment: @AlexYoucis These were precisely the thoughts I had in mind, when I said that its true for UFDs. If the closed complement has codimension $2$, we are done by Hartog's lemma and in the codimension $1$ case, the ideal will be principal, hence it is a distinguished affine open.But how do you reduce to the local case, if the codimension $1$ ideals are only locally principal, i.e. for Dedekind domains with non-trivial ideal class group? Are you saying that it is always an open immersion if $A$ is regular?
Answer: Let me work out the counter example proposed in the comments.
Let $X = \operatorname{Spec}A$ be a non-normal isolated surface singularity, as constructed here: isolated non-normal surface singularity. Let $p$ be the singular point and $U = X \setminus \{p\}$ be the open complement. It turns out, that this will always be a counter example, and luckily we dont have to do any concrete computations.
Let $A \to \bar A$ be the integral closure (which is a finite extension, since $A$ is of finite type over a field), and $Y = \operatorname{Spec} \bar A \xrightarrow f X$ be the induced finite morphism of affine schemes. This induces an isomorphism over the normal locus, i.e. $Y \setminus f^{-1}(p) \xrightarrow{\sim} U$ .
Since the map is finite, we have that $f^{-1}(p)$ has codimension two in the normal scheme $Y$, hence by Hartog's lemma:
$$\mathcal O_X(U) = \mathcal O_U(U) = \mathcal O_{Y \setminus f^{-1}(p)}(Y \setminus f^{-1}(p)) = \mathcal O_Y(Y \setminus f^{-1}(p)) = \mathcal O_Y(Y) = \overline A$$
Hence you are asking whether the map $$A \to \mathcal O_X(U) = \overline A$$ induces an open immersion. Of course we expect the map to be the inclusion into the integral closure, thus the induced map is the map $f$. To show this rigorously, note that the sheaf map $\mathcal O_X \to f_* \mathcal O_Y$ gives rise to a commutative diagram
$$\require{AMScd}
\begin{CD}
A @>>> \overline A\\
@VVV @VV\operatorname{id}V \\
\mathcal O_X(U) @>\cong>> \mathcal O_Y(Y \setminus f^{-1}(p))=\overline A
\end{CD}$$
By functoriality of $\operatorname{Spec}$, we get a commutative diagram
$$\require{AMScd}
\begin{CD}
 Y @>\cong>> \operatorname{Spec} \mathcal O_X(U)\\
@V\operatorname{id}VV @VVV \\
Y @>f>> X
\end{CD}$$
Thus the map $\operatorname{Spec} \mathcal O_X(U) \to X$ is an open immersion if and only if $f$ is one. But $f$ is surjective and not an isomorphism, hence it can not be an open immersion.
Comment: i believe it is unfair that you forgot to remark that your answer is just an exapnded version of my comment above.
Comment: @skeptic you are right. I added that remark. If you had shown any signs of filling in the details, I would not have posted that answer.

About open subsets of affine schemes.


How can I find the IP addresses of an AWS RDS instance

Question: I have an RDS instance on AWS running MySQL.  "Public availability" is set to "yes", and I can connect using the endpoint dns name.
Using the AWS console, how can I find both the public and private IP addresses of the instance?
Comment: Why do you want your mysql accessable remotely - sounds like a problem waiting to happen??
Comment: Try SSH Port forwarding [so you don't need to expose the relatively insecure DB connection]
Comment: How else would I access it?  From time to time I need to investigate tables using MySql Workbench.
Answer: There is only endpoint for RDS. Public and Private IP address might change if there is failover happen. You may refer to this documentation.
You may use nslookup command to look for the IP address, you will get public IP address if it's outside of VPC and private IP address if it's within the same VPC as your RDS.
Answer: EC2 > Network Interfaces

Then look for your RDSNetworkInterface - usually identifiable by the security group. It will list the Public and Private IP there.


What is the system administration equivalent to dogfooding?

Question: Software developers have the concept of "dogfooding", which is where they personally use the software that they are developing, often on a regular basis. For some projects, the direct interaction it provides can be invaluable in debugging the system. So I ask the community:

What is the system administration equivalent to dogfooding?
Comment: I hate it when I see system administrators leveraging personal exceptions just because they can. Of course you run the standard sysadmin image, use the same firewall rules as the users and so fourth to the point that you can still do your work anyway... anything less would be a serious issue imo ^^
Answer: Place the same trust in your backup system that your users do, and delete your home folder. If that sounds scary, or if you think it'll take too long to recover, maybe you need to improve your backup system.
Comment: Ooooo, haven't done this one, not sure I'd do that much dogfooding...
Comment: Very good example of dogfooding...:-P
Comment: This is a remarkably good idea.
Answer: I don't think there'll be as clear an answer as for programming, but a couple partial answers come to mind:
Using a PC that's set up from a standard image the same as anyone else.
Running with user privs. most of the time, elevating only when necessary.
Another thought: Ask a close friend or relative to go through your documentation and follow it and tell you honestly if it's clear.
Comment: +1 running with user privileges. (and question is now community wiki)
Answer: Report an problem using the same issue tracking software as your users, rather than just fixing it yourself. If possible, get another sysadmin to handle the issue via the software instead of directly talking to you.
Answer: In software development, "dogfooding" is just an overhyped word for what I think should be called "testing".  Actually using the product?  Like a customer would?  Should be a very obvious step.
The term was popularized by Microsoft, but they are one of the companies out there for whom "eating their own dog food" is a bit more sensible than in other companies.  If you make software for managing dental office management, it's a different situation than if you are developing, say, an operating system / word processor / web browser / mail server / software development tool ... something that a software developer would normally use on a regular basis.
But by the same token, it makes sense for sysadmins for a lot of the same reasons -- we are often maintaining the same systems that we use anyway.  So whenever you can use the same script / restrictions / application / database / server / diskimage / network / whatever that your users do, you should do it -- that's dogfooding.  Try everything once.  After a while, try it again.
Also note that eating the dog food yourself too often is bound to produce bloat, in my opinion.  This is not just a pun!
Comment: Using a software product the same as a customer would is not applicable to a dev in many situations.  For example, I develop financial reporting software but I don't use it because I'm not a financial reporter.
Comment: @squillman: having been a developer i agree....but also gotta say, we use our ERP system for internal paperwork.
Answer: Using Websense with the same blocked pages as end users.
Answer: As has been mentioned, I think that good sysadmins should be doing this by default. As a systems admin, you should be building standardised environments and procedures that allow all users to work as efficiently as possible. That includes yourself. :)
Some behaviours which reinforce this:

Running as a standard user (be it on Windows or *NIX) and elevating only when necessary.
Using standard workstation hardware running the same OS build and packages that your users use.
Enforcing the same policies on IT staff (and developers) as normal users, unless there is a business reason to do otherwise. If the company standard is to use IE and IE only, then there should be no installs of Firefox on IT machines.

All of this allows you to demonstrate to your users that you practice what you preach.
Comment: /me looks in mirror...does not run as a standard user, uses a newer OS and hardware, does not use the same apps and browser as users do. :(
Answer: Use the same system image and workstation configuration that the users you support use.
Use a standard user account for logging on to your workstation and running your LOB applications (word processing, email, CRM, etc).
Never elevate your standard user account. Log on to the relevant system with the relevant credentials when needed.
I don't run any systems administration tasks from my own workstation or using my own user account. I have a separate management server for performing systems management tasks and I log on to that system with the relevant credentials, dependent on the task being performed.
Answer:
Dogfooding  - (dôg-fūd-ĭng)

What happens to poorly functioning system administrators. Refer to this and this for further details.
Answer: Running with the locked-down GPO's of your user base. Ewww ... sometimes dogs throw up.


Proof of Triangle Inequality for $d(g; x, y) = \left(|x-y|^4 + g\,| x \times y |^2\right)^{\frac{1}{4}}$

Question: I am seeking assistance in proving that a function, denoted as $d(g; x, y)$, defined on $\mathbb{R}^2 \times \mathbb{R}^2$ and parameterized by the non-negative real number $g$, may satisfy the triangle inequality. The function is defined as follows:
\begin{align}
d(g; x, y) &:= \left(|x-y|^4 + g\,| x \times y |^2\right)^{\frac{1}{4}} \\
&= \left( \left((x_1 - y_1)^2 + (x_2 - y_2)^2\right)^2 + g\,(x_1\,y_2 - x_2\,y_1)^2 \right)^{\frac{1}{4}}
\end{align}
where $x=(x_1,x_2),\,y=(y_1, y_2)$.
It is noteworthy that when $g=0$, $d(g;x,y)$ coincides with the Euclidean distance.
My ultimate goal is to prove that $d(g; x, y)$ is a distance function on $\mathbb{R}^2$ for a certain range of $g$.
While it is trivial that $d(g; x, y)$ is non-degenerate and symmetric with respect to $x$ and $y$, the proof of the triangle inequality is not straightforward. Through numerical calculation, I observed that the triangle inequality seemed to hold in the range $0\leq g \leq 6$.
In other words, the conjecture I wish to prove is as follows: for $0 \leq g \leq 6$, and only in that range,
$$
d(g;x,y)+d(g;y,z)≥d(g;x,z)
$$
holds for all $x,y,z \in \mathbb{R}^2$.
I am looking for guidance and information related to proving this statement.
Thank you for your assistance!
Comment: While contemplating the quantification of "similarity" for rectangles, I stumbled upon this by chance.

Consider a rectangle $R(x)$ with vertices at the origin, $x = (x_1, x_2)$, $(x_1, 0)$, and $(0, x_2)$. In this case, if $R(x)$ and $R(y)$ are similar, then $d(g;x,y)$ equals the Euclidean distance between $x$ and $y$. Otherwise, if $g$ is positive, then $d(g;x,y)$ will be greater than the Euclidean distance between $x$ and $y$.
Comment: What is the origin of this exercise ?
Answer: Here is the half of the answer : I am going to exhibit a family of counter-examples in the cases $g>6$ where triangular inequality is violated :
$$d(g;x,y)+d(g;y,z) < d(g;x,z)\tag{1}$$
A first remark : function $d$ is rotation-invariant and homogeneous :
$$\begin{cases}d(g;R(u),R(v))&=&d(g;u,v)\\d(g;k.u,k.v)&=&k.d(g;u,v)\end{cases} \tag{2}$$
The first property above allows to assume WLOG that the central point $y$ in (1) can be taken on the real axis (see (4) below).
I have begun by a vast similation making evident that the violation of triangular inequality occurs for any $g > 6$.
For example, in the case $g=6.1$, among $10^5$ random triangles in the unit disk, only 3 of them violate triangle identity, all with the peculiar shape of (almost) flat isosceles triangles :

I will use complex numbers representation which is slightly more convenient. One can write, by identifying vectors and their affixes (complex numbers) :
$$d(g;a,b)^4=\left(|a-b|^2\right)^2+g.\left(\Im(\overline{a}b)\right)^2\tag{3}$$
Let us consider the three points :
$$x=re^{i \theta}, \ \ \ y=s, \ \ \ z=\overline{x}=re^{-i \theta}\tag{4}$$
(with $s>0$, angles $0<\theta < \pi/2$ will be taken in the vicinity of $\pi/2$ : in this way we have an almost flat isosceles triangle).
Inequality (1) becomes :
$$2 \left((r^2-2rs \cos \theta +s^2)^2+g.(rs \sin \theta)^2\right)^{1/4} < ((2r)^4 \sin(\theta)^4+g.(r^2 \sin(2 \theta))^2)^{1/4}\tag{5}$$
Taking the power $4$ of inequality (5) then dividing by $16$, we get :
$$(r^2-2rs \cos \theta +s^2)^2+g.(rs\sin \theta)^2 < r^4 \sin(\theta)^4 + g \frac{r^4}{16} \sin(2 \theta)^2\tag{6}$$
Now let us make $s$ dependent upon $r$ and $\theta$ :
$$s=\frac{r}{4} \cos \theta \tag{7}$$
Rearranging (6), and simplifying by $r^4$, we get the inequality :
$$(1- \tfrac{7}{16}(\cos \theta)^2)^2+g.\frac{1}{16}(\sin \theta \cos \theta)^2 <  (\sin \theta)^4 + g.\frac{1}{16}(2 \sin \theta \cos \theta)^2\tag{8}$$
$$g.\tfrac{3}{16}(\cos \theta)^2 (\sin \theta)^2 > (\sin \theta)^4-(1- \tfrac{7}{16}(\cos \theta)^2)^2 \tag{9}$$
$$g > \underbrace{\tfrac{3}{16} \left(23+\tfrac{9}{(\sin \theta)^2}\right)}_{f(\theta)}\tag{10}$$
Continuous function $f$ is evidently $>6$ with $f(\theta) \rightarrow 6$ when $\theta \rightarrow \pi/2$ ; therefore it is always possible for each value $g_0>6$ to find a value $\theta_0$ such that $g_0>f(\theta_0)$, establishing the negation of the triangular inequality for any value of $g$ above $6$.
Comment: I appreciate the excellent results you shared! What particularly interests me is how the peculiar triangle with vertices $re^{i\theta}, r\cos\theta/4$ and $re^{-i\theta}$ sheds light on the derivation of the number 6.
Comment: I imagine that you have taken norm $L^4$ (with exponents $4$ and $1/4$) in order to be able to combine in a dingle formula the original euclidean distance and the norm of the cross product in order to have the two good behaviors (by rotation and by homothety)...
Comment: > I imagine that ... in order to have the two good behaviors (by rotation and by homothety)...

That's correct. I chose the form of $d$ with homogeneity and rotational symmetry in mind.
Answer: Some thoughts.
Let
$$u := \frac{\Big((x_1 - y_1)^2 + (x_2 - y_2)^2\Big)^2 + g(x_1y_2 - x_2 y_1)^2}{\Big((z_1 - x_1)^2 + (z_2 - x_2)^2\Big)^2 + g(z_1x_2 - z_2 x_1)^2},$$
and
$$v := \frac{\Big((y_1 - z_1)^2 + (y_2 - z_2)^2\Big)^2 + g(y_1z_2 - y_2 z_1)^2}{\Big((z_1 - x_1)^2 + (z_2 - x_2)^2\Big)^2 + g(z_1x_2 - z_2 x_1)^2}.$$
We need to prove that
$$u^{1/4} + v^{1/4} \ge 1.\tag{1}$$
It suffices to prove that, for all $a, b > 0$ and $x_1, x_2, y_1, y_2, z_1, z_2 \in \mathbb{R}$,
$$\frac{u}{a^3} + 3a + \frac{v}{b^3} + 3b \ge 4.\tag{2}$$
(Note: If (2) is true, letting $a = u^{1/4}$ and $b = v^{1/4}$, we have $u^{1/4} + v^{1/4} \ge 1$. )
(2) is written as
\begin{align*}
 &\frac{1}{a^3}\Big((x_1 - y_1)^2 + (x_2 - y_2)^2\Big)^2 + \frac{1}{b^3}\Big((y_1 - z_1)^2 + (y_2 - z_2)^2\Big)^2 \\[6pt]
 &\quad - (4 - 3a - 3b)\Big((z_1 - x_1)^2 + (z_2 - x_2)^2\Big)^2\\[6pt]
 \ge{}&  g\Big[ (4 - 3a - 3b)(z_1x_2 - z_2 x_1)^2 - \frac{1}{a^3}(x_1y_2 - x_2 y_1)^2 - \frac{1}{b^3}(y_1z_2 - y_2 z_1)^2 \Big]. \tag{3}
\end{align*}
We can prove that $\mathrm{LHS}_{(3)} \ge 0$ (the proof is given at the end). Thus, we only need to prove the case that $\mathrm{RHS}_{(3)}\ge 0$. Thus, it suffices to prove (3) when $g = 6$, i.e.,
\begin{align*}
 &\frac{1}{a^3}\Big((x_1 - y_1)^2 + (x_2 - y_2)^2\Big)^2 + \frac{1}{b^3}\Big((y_1 - z_1)^2 + (y_2 - z_2)^2\Big)^2 \\[6pt]
 &\quad - (4 - 3a - 3b)\Big((z_1 - x_1)^2 + (z_2 - x_2)^2\Big)^2\\[6pt]
 \ge{}&  6\Big[ (4 - 3a - 3b)(z_1x_2 - z_2 x_1)^2 - \frac{1}{a^3}(x_1y_2 - x_2 y_1)^2 - \frac{1}{b^3}(y_1z_2 - y_2 z_1)^2 \Big]. \tag{4}
\end{align*}
Some numerical experiment supports (4). However, I can not verify (4) using CAS (Computer Algebra System) in a short time (some minutes).
$\phantom{2}$

Proof of $\mathrm{LHS}_{(3)} \ge 0$.
Let $$p := \frac{\Big((x_1 - y_1)^2 + (x_2 - y_2)^2\Big)^2}{\Big((z_1 - x_1)^2 + (z_2 - x_2)^2\Big)^2}, \quad q := \frac{\Big((y_1 - z_1)^2 + (y_2 - z_2)^2\Big)^2}{\Big((z_1 - x_1)^2 + (z_2 - x_2)^2\Big)^2}.$$
It suffices to prove that $\frac{1}{a^3}p + 3a +  \frac{1}{b^3}q + 3b \ge 4$. By AM-GM, it suffices to prove that $4\sqrt[4]{p} + 4\sqrt[4]{q} \ge 4$ or
$$\sqrt{(x_1 - y_1)^2 + (x_2 - y_2)^2} + \sqrt{(y_1 - z_1)^2 + (y_2 - z_2)^2} \ge \sqrt{(z_1 - x_1)^2 + (z_2 - x_2)^2}$$
which is clearly true. We are done.


How to proceed towards MySQL performance testing for Drupal?

Question: We have lots of Drupal sites installed on our server. Some of the sites do have lots of views and blocks configured on it.   Occasionally, one of such Drupal site (with lots of views and contents) suddenly becomes unresponsive or very slow. But rest of the Drupal sites with less contents appear to work fine during that time. We have to restart MySQL database in order to bring unresponsive Drupal site back to normal. We were thinking of setting up a periodic MySQL restart using cron.
This periodic restart option do not appeal to me very much. I want to find the cause of this problem. I suspect that it is mostly because of MySQL, but still it is a guess.
I am not experienced in the server performance issues. What is the best way I should tackle this problem? How can I confirm that it is a MySQL problem and not because of other? If it is a MySQL problem, what basic steps I should take to solve it?
Answer: First tool, that can be used, is Devel - it will show there's long calls have been made.
And there's many tools for perfomancing and tuning mysql in internet.
Answer: I second the recommendations of the DBTuner and Devel modules. I also agree that you should avoid restarting Mysql whenever possible. It builds up a bunch of caches in RAM and will have to start all over if you restart. You should make sure your mysql is using at least my-huge.cnf or better. This thread at Drupal.org http://drupal.org/node/85768 has some info about tuning Mysql for better performance. Always test your my.cnf changes on a dev server because Mysql config changes often break the server without warning or explanation.
Also, make sure PHP has a good amount of RAM. PHP delays can give the appearance of slow db server if you're only looking at the site in a web browser. You want it to have memory_limit = 32M or greater (I usually do 64-126M). You don't want it crazy high though because that can start to have a negative impact on Apache's performance.
There is also a High Performance group here http://groups.drupal.org/high-performance . This is a good place to poke around.
Answer: I think if you ever need to restart MySQL regularly, especially scheduled, then there is a problem.
How often does this unresponsiveness occur? Do you have ssh access to the machine? Can you access the MySQL prompt and do 'show processlist;' ?
I suspect it is a locked table issue if a query is taking a long time.
Comment: There is no as such time that when this unresponsiveness occurs. It happens even if there is only 2-3 users accessing this site, but after the MySQL restart, site come backs to normal. I need to get together with system-admin to run the 'show processlist;' command.
Comment: Can you get the system admin to enable the slow query log? After restarting you could consult that to see if anything pops up.
Answer: I found the dbtuner module to be very helpful.  It even suggests and provides an easy way of indexing specific fields.  Give it a shot.
Answer: Next time this happens do a SHOW FULL PROCESSLIST in phpmyadmin/mysql. It will show what queries are running; what tables are locked and for how many seconds the query has been running for. Once you know the query, it's a lot easier to figure out whats wrong.
I'm slightly biased, but dbtuer is a pretty sweet tool for finding slow queries in views. Devel rocks for finding all slow queries.
Answer: If you're using version 7, some performance tips can be found at this post.


Adicionando e removendo elementos em um array

Question: Tenho a seguinte estrutura:

var elementos = ["teste1","teste2","teste3","teste4","teste5","teste6","teste7","teste8","teste9","teste10","teste11","teste12"];
var elementosPossui = [];

function carregaTabelas() {
  carregaTabelaElementos();
  carregaTabelaElementosPossui();
  document.getElementById("conteudoArrays").innerHTML = '['+ elementos.toString()+']['+elementosPossui.toString()+']';
};

function carregaTabelaElementos() {
  var k = 0; var tabela = '
';
  for (var i = 0; i < 4; i++) {
    tabela += '
';
    for (var j = 0; j < 3; j++) {
      if(typeof elementos[k] === "undefined"){
        tabela += '[0]	';
        k++;
      }else{
        tabela += '['+elementos[k]+']	';
        k++;
      }
    }
    tabela += '
';
  }
  tabela += '
';
  document.getElementById("elementos").innerHTML=tabela;
};

function carregaTabelaElementosPossui() {
  var k = 0; var tabela = '
';
  for (var i = 0; i < 4; i++) {
    tabela += '
';
    for (var j = 0; j < 3; j++) {
      if(typeof elementosPossui[k] === "undefined"){
        tabela += '[0]	';
        k++;
      }else{
        tabela += '['+elementosPossui[k]+']	';
        k++;
      }
    }
    tabela += '
';
  }
  tabela += '
';
  document.getElementById("elementosPossui").innerHTML=tabela;
};

adicionar = function(id) {
  log = document.getElementById("log");
  var index = elementos.lastIndexOf(id);
  elementosPossui.push(elementos.splice(index, 1));
  carregaTabelas();
  log.innerHTML = index;
};

remover = function(id) {
  log = document.getElementById("log");
  var index = elementosPossui.lastIndexOf(id);
  elementos.push(elementosPossui.splice(index, 1));
  carregaTabelas();
  log.innerHTML = index;
};

carregaTabelas();
Selecione um elemento:

Elementos adicionados:

Log:

Estou com problema para adicionar e remover do array o elemento que o usuário clicou.
A ideia é que ao selecionar o elemento da primeira tabela, ele seja adicionado na segunda, e ao selecionar um elemento da segunda, ele seja adicionado na primeira, sempre adicionando o elemento no fim da tabela.
Acreditava que a combinação dos métodos indexOf, splice e push desse modo:
index = indexOf(valorDoElemento);
array.push(array.splice(index, 1));

Solucionariam o problema, ao invés disso ele simplesmente não encontra o elemento no array.
Comment: Por favor, seja mais específico, `Estou com problema para adicionar e remover o elemento do array que o usuário clicou.` não ajuda nem um pouco =)
Comment: Mas no seu exemplo você não esta pegando o elemento clicado, você esta pegando sempre o último.
Comment: Não seria a falta de declaração das variáveis? var adicionar = function... e var remover = function...?
Comment: @gerep eu estava editando a pergunta enquanto você comentou rs
Não necessariamente, estou adicionando o elemento que retornou na posição do index vindo da função indexOf
Comment: Não sei se isso ficou muito claro...
Comment: @IvanFerrer não, não é isso
Comment: Acredito que seu problema está na forma de utilizar o `indexOf`. Está faltando o array =)
Comment: @MarceloBonifazio respondi, e no exemplo comentei os códigos que alterei, boa sorte ai nos estudos!
Answer: Para solucionar tens que alterar os seguintes pontos:

onclick() - Colocar sua string entre aspas.
splice() - Retorna um array, no seu caso o elemento sempre estará na posição [0] ao remover e ao adicionar.

Segue o exemplo abaixo com os comentários nas linhas onde foram feita as alterações.

<!DOCTYPE html>

    <title>Exemplo utilizando socket.io</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    Selecione um elemento:

    Elementos adicionados:

    Log:

Comment: Ah, mas seria legal já comentar de qualquer forma né. ;) PS: `de qualquer forma = antes do AP apresentar dúvidas`, pra ajudar outros com o mesmo problema e tals...
Comment: rsrs, sim acabei comentando, fica mais didatico, obrigado @gustavox
Comment: Aí sim... :) +1
Comment: @SneepsNinjA era exatamente isso, nunca tinha reparado que o método splice retornava um array de elementos que estão dentro do array
Answer: Se quiser, preservar a posição, faça dessa forma, espero que seja o que você precisa:

Comment: Não não @IvanFerrer, pra isso só seria necessário adicionar o elemento no outro array e dar um sort no array rs, mas valeu mesmo assim ^^


How to show following function is in $L^{\infty}(\mu)$

Question: If (X, $\Omega, \mu$) is a $\sigma$-finite measure space, $\phi:X \rightarrow \mathbb{C}$ is an $\Omega$-measurable function, $1 \leq p \leq \infty$, and $\phi f \in L^{p}(\mu)$ whenever $f \in L^{p}(\mu)$, then show that $\phi \in L^{\infty}(\mu)$.
I am trying this by using closed graph theorem.
Any help.
Answer: By contradiction, suppose that $\phi$ is not essentially bounded.
Define the sets $$B_n=\{x\in X~:~|\phi(x)|\in[n,\,n+1)\}\in \Omega.$$
There exists a sequence $\{n_i\}_{i=1}^\infty$ s.t. $\mu(B_{n_i})>0$ for any $i$. Indeed, if such sequence does not exists then for some integer $N>0$ we have $\mu(B_n)=0$ for all $n\geq N$, i.e. $|\phi|\leq N$ $\mu$-a.e.
Define $f\in L^p(\mu)$, $1\leq p <\infty$, as stepwise function:
$$
f(x) = \sum_{i=1}^\infty \frac{1}{{i\vphantom{)}}^{1+1/p}}\frac{1}{\left(\mu(B_{n_i})\right)^{1/p}}\mathbb 1_{\{x\in B_{n_i}\}}
$$
Check that $f\in L^p(\mu)$, $1\leq p <\infty$.
$$
\int\limits_X |f|^p \, d\mu = \int\limits_X \biggl(\sum_{i=1}^\infty \frac{1}{{i\vphantom{)}}^{1+1/p}\left(\mu(B_{n_i})\right)^{1/p}}\mathbb 1_{\{x\in B_{n_i}\}}\biggr)^p \, d\mu =\sum_{i=1}^\infty \frac{1}{{i\vphantom{)}}^{p+1}\mu(B_{n_i})} \int\limits_X\mathbb 1_{\{x\in B_{n_i}\}} \, d\mu =\sum_{i=1}^\infty \frac{1}{{i\vphantom{)}}^{p+1}}<\infty
$$
Look at $\int_X |\phi f|^p \, d\mu $:
$$
\int\limits_X |\phi f|^p \, d\mu = \sum_{i=1}^\infty \frac{1}{{i\vphantom{)}}^{p+1}\mu(B_{n_i})} \int\limits_X|\phi(x)|^p\mathbb 1_{\{x\in B_{n_i}\}} \, d\mu \geq \sum_{i=1}^\infty \frac{1}{{i\vphantom{)}}^{p+1}\mu(B_{n_i})} \int\limits_X n_i^p\mathbb 1_{\{x\in B_{n_i}\}} \, d\mu = \sum_{i=1}^\infty \frac{n_i^p}{{i\vphantom{)}}^{p+1}} \geq \sum_{i=1}^\infty \frac{i^p}{{i\vphantom{)}}^{p+1}}=\sum_{i=1}^\infty \frac{1}{i}=\infty.
$$
For $p=\infty$ simply take $f\equiv 1\in L^\infty(\mu)$. By a condition, $\phi f=\phi\in L^\infty(\mu)$.
Comment: Can you please explain how did you took summation outside from integral. We have power p of infinite sum. Plz explain
Comment: Only one of indicators equals 1 for any $x$.


Overriding 'user.login.http' method

Question: I am trying to override the core login method in Drupal\user\Controller\UserAuthenticationController by extending the UserAuthenticationController class so that I can inject custom data into the response object. I could achieve override by creating an Event subscriber service and using the alterRoutes method.
 public function login(Request $request) {
     $response_data = parent::login($request);

      return $response_data;

  }

However the response data is an object of type Symfony\Component\HttpFoundation\Response and there is absolutely no way to access the data. I would like to do the following but not able to modify the response object.
 public function login(Request $request) {
     $response_data = parent::login($request);
     $response_date = $this->fetchCustomdata($response_data);
     return $response_data;

  }

  private function fetchCustomdata($response_data) {
   // Do some work and return modified $response_dat
   return $reponse_data
 }

Is there any better way to inject custom data into the response parameters?
Note: The additional data I am trying to inject is additional fields i have added to the user profile like First Name, Email and other reference fields. It is required to deliver these along with the other default responses along with the default response on login.
Note: I tried copying the original method and modifying the data and it works but it goes against the good practice as we are trying to reduce duplication.
Comment: This needs more information. What is the data you are trying to insert into the response? Why are you trying to insert this data? What is your overall goal? You have shown us the method you are using to try to achieve some goal, but you have not told us what that goal is.
Comment: I have added extra information: Thanks
Comment: I'm sorry, you've still only written the method you are trying to use to achieve some goal, so I'm unclear on how to help myself, but hopefully someone else can understand better.
Comment: Thanks for looking into this @Jaypan. I see your point. I have updated it further.
Answer: I figured out how to actually do this. We need to go to the class from which the object was instantiated and figured out any public getter and setter methods. This should be obvious for someone well versed with OOPs. Here is I managed to modify the response.
public function login(Request $request) {
  $response_data = parent::login($request);

  // We need to get data in the original response and there is actually a
  // a public method provided by the parent class getContent which we are using
  // below.
  $mydata = $response_data->getContent();

  // Original data is serialized so we need to decode it.
  $decoded_data = $this->serializer->decode($mydata, 'json');
  $uid = $decoded_data['current_user']['uid'];
  $user = $this->userStorage->load($uid);

  // custom function to process the user
  $mynewdata = $this->customfunction($user);

  // Adding to the original decoded response array and
  // then encoding again.
  $decoded_data += $mynewdata;
  $combined data = $this->serializer->encode($decoded_data, 'json');

  // Setting the content to the origina response object. Important!!!
  $response_data->setContent($encoded_sponsor_data);
  return $response_data;
}

Overriding 'user.login.http' method


Commerce line item views and html mail

Question: I have a view (commerce line item) with HTML (or unformated) list with several fields.
On each field i unchecked "place a colon after the label" but it does not obey that rule.
So i added custom CSS to fields and its working.
Each label has "strong" html elemement and that is working fine too.
When the order is complete commerce sends email and results are:
Label:
field
Label:
field
instead of
Label: field
Label: field
html strong tag displays fine.
I have tried with HTMLmail and MimeMail with emogrifier installed.
Answer: Was fairly easy to fix the issue.
In styling settings of a field in view i used "SPAN" for field.

Commerce line item views and html mail


How to do operations on state constructor variables in Flutter?

Question: I'd like to show change of wordCount in homeWidget
    return Scaffold(
      body: Column(
        children: [
          ...
          Expanded(
            flex: 1,
            child: RecorderView(
              onSaved: _onRecordComplete,
              wordCount:wordCount,
            ),
          ),
        ],
      ),
    );

the variablewordCount relies on RecordView method:
I write this to get state variable here
class RecorderView extends StatefulWidget {
  final Function onSaved;
  final int wordCount;
  const RecorderView({Key key, @required this.onSaved,@required this.wordCount}) : super(key: key);
  @override
  _RecorderViewState createState() => _RecorderViewState();
}

class _RecorderViewState extends State<RecorderView> {

//in one method
    widget.wordCount++;
}

I want to add wordCount here,but it says it's a final one.How could I inherit wordCount from homeWidget without final? I just want to change the word show in wordCount automatically,thanks!!
Comment: You would need to lift the state up or do a more advanced state management. Check out [InheritedWidget](https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html) for a flutter framework method, or something like provider
Answer: You cant inherit the variable, you can however initialize it to a value from the widget.
class RecorderView extends StatefulWidget {
  final Function onSaved;
  final int wordCount;
  const RecorderView({Key key, @required this.onSaved,@required this.wordCount}) : super(key: key);
  @override
  _RecorderViewState createState() => _RecorderViewState();
}

class _RecorderViewState extends State<RecorderView> {
int _wordCount;

@override
void initState() {
super.initState();
_wordCount = widget.wordCount;
}
}


disable viewport zoom iOS10 safari?

Question: I've tried all three of these but no luck:
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;
user-scalable=0;" />

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;
user-scalable=false;" />

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;
user-scalable=no;" />

Each are different values I found recommended by google searching or SO searching, but none of the 'user-scalable=X' values seem to be working
I also tried comma delimiting the values instead of semicolon, no luck. Then I tried ONLY having the user-scalable value present, still no luck.
Apple Says this

To improve accessibility on websites in Safari, users can now pinch-to-zoom even when a website sets user-scalable=no in the viewport.

Also tried:
<meta name="HandheldFriendly" content="true">
html {
   -webkit-text-size-adjust: none
}

Tried Javascript as well
document.documentElement.addEventListener('touchmove', function (event) {
      event.preventDefault();
}, false);

Javascript solution worked but it disables horizontal scroll as well. :(
none of above is working. Any ideas?
Comment: Possible duplicate of [disable viewport zooming iOS 10 safari?](http://stackoverflow.com/questions/37808180/disable-viewport-zooming-ios-10-safari)
Answer: This should work until Apple comes to their senses and stops removing features we all use...
document.documentElement.addEventListener('gesturestart', function (event) {
    event.preventDefault();
}, false);

Comment: This results inconsistent pinchzoom... sometime possible and sometime not coming back when zoomed :|  ... Apple has really overwritten things in a BAD way

disable viewport zoom iOS10 safari?


is mann whitney an alternative to t-test?

Question: can i compare both of them ?
As i may change the sample size , variance and also skew the distribution.
However,some researcher claimed that comparing both of them couldnt make sense as it is just like comparing apple with peach.
So ,it make me stuck.
As i am referring this paper actually "should we always choose a nonparametric test when comparing two apparently nonnormal distribution?" by Skovlund and Fenstad.
Answer: You cannot directly compare a t-test with the Mann Whitney U test.  You can use the Mann Whitney test as an alternative to a t-test when the assumptions of a t-test cannot be met.  The Mann Whitney U test is a nonparametric test that requires weaker assumptions, so it is often used in place of the t-test.  However, as it is a non-parametric test it is also less powerful.
Comment: I like the first sentence in the answer, but not the rest .  The two tests test different hypotheses, and so are not alternatives to each other.  The *t* test compares means and Wilcoxon-Mann-Whitney compares stochastic dominance...  The first thing is to decide what hypothesis you want to test.
Comment: Yes, I know.  I guess I was being so stark just to emphasize the difference in the hypotheses.  I wish we would teach students to think about these tests as testing different hypotheses, rather than a t-test being the default and a nonparametric test being an alternative.  (And there are other options for example if we want to think about medians or other quantiles, and so on). I apologize for my starkness.  +1 for the answer.
Comment: Therefore, is the shift of location the additional assumptions of mann whitney is valid? to test the equality of median or even mean.
Comment: ** in this assumptions ,it has the same shape of distribution.
Comment: @SalMangiafico, that's a fair point.  I guess I should have been more clearer and indicated that one often changes the hypothesis to be tested if the assumptions of a $t$-test cannot be met, in this way, the U test is frequently choosen to replace the $t$-test.
Comment: Oh, I didn't think you were being stark at all.  I think the comment was a good one.  I agree too with your sentiments regarding the teaching of this material too.
Comment: *less powerful* if the assumptions of the t-test is not met!


How to measure the tension or resolution of a chord?

Question: Let me begin..
A chord is fundamentally built off the selection of multiple intervals. Those intervals hold a position in a 12TET interval ranking from most consonant to most dissonant. Depending on the intervals used within a chord, the desired level of consonance, dissonance or possibly a mix of the two within a chord, is produced.
Correct? If not could you kindly correct this statement?
Follow up question..
If the statement is correct, how exactly would you specifically measure the consonance or dissonance of a chord based off the intervals used?
To give added context, im seeking this information to produce the specific desired amount of tension and resolution along an entire chord progression, lets say a 4 bar progression.
Thank you!
Comment: Hi Seery. The question body here doesn't quite seem to agree with the title - in the question body, you ask "how exactly would you specifically measure the *consonance or dissonance* of a chord based off the intervals used" - that has some answers [here](https://music.stackexchange.com/questions/4439/is-there-a-way-to-measure-the-consonance-or-dissonance-of-a-chord). How you measure the *tension or resolution* of a chord seems a different question to me, as it focuses more on what has come before the chord in time.
Comment: If you play the most consonant chord in the world (whatever that might be) and suddenly raise it by one semitone, there's a moment of transition when it won't sound consonant, or at least not the same. Was the _change_ consonant or dissonant? Was it expected or unexpected? If you're going to have a _progression_, its every step will have a context and expectations about what might happen next.
Comment: I guess just about every conceivable combination of, say, four chords has been used, over and over. Is it feasible to take some examples and examine those? I also guess that four chords in one piece will not have the same feeling of consonance/dissonance when found in different pieces.
Comment: @topomorto im going to check that post now. My question seems to be if i select intervals of a chord based off their position in the interval ranking, does that give me access to dictate the exact desired of tension or stability of a chord itself? I had tried that approach earlier and i can't seek out the formula which in my mind is i have 12 intervals, if i pick the 3rd most consonant interval, then the 7th most dissonant and then 11th dissonant interval, i have successfully dictated the level of tension/stability of a chord but that approach seems like a lot of jumble instead of consistent
Answer: The tension from a chord depends on context. The section on Ludmila Uhlela's book at thereelscore.com has a nice outline about the perceived tensions in various styles. Trivial example is the major-minor seventh which is a medium dissonance when used as a dominant seventh: V7-I or G7-C whereas as s German Sixth Ge6-I64-I or Ab7 (with the Gb enharmonically interpreted as F#)-C64-G7-C.
Even the 64 chord exhibits a different feeling of tension as a passing chord C-F64-C6 (C-E-G, C-F-G, E-G-C) or as part of a cadence ii65-I64-V7-or F-A-C-D, G-C-E-G, G-B-D-F, C-E-G-C (if parallels are taken care of).
Comment: @Seery - The C major chord sounds quite dissonant in the context of B major because, as the Neapolitan chord of B major, the C major chord is a strong sign that things are going harmonically south, and if the passage were tuned with just intonation instead of 12TET, the C major chord would likely use at least one wolf note or interval. I'd say the A# diminished chord sounds more consonant than the C major chord in a B major context because it is vii° (a dominant-function chord) in B major and is less likely to use wolf intervals. Note how many times I have used the word "context".
Comment: @Seery tension and resolution of a chord can't only be based off the intervals in the chord itself - when you're talking about tension and resolution, you are introducing a discussion of context.
Comment: Nothing wrong with what you are doing. However, in C minor, the d diminished chord (as ii) does seem less dissonant than an Ab7 chord treated as a German Sixth. You may want to expand your work at some time (it is exponentially harder to do chords relations though.)
Comment: "The tension from a chord depends on context" How is this so if for example, a C major chord will always be more consonant than a Diminished chord based off intervals used? I'm trying to seek out not so much contextual tension and resolution but tension and resolution of a chord based off intervals themselves. My question is, if im to build a chord by stacking intervals from interval ranking and use the ranking by specifically choosing my notes of the chord based off the position of the interval in the ranking, does that function in dictating specfic tension or stability of a chord?
Comment: @topomorto Sure. I am using consonance/dissonance and tension/resolution too interchangeably.
Answer:
Those intervals [of chords] hold a position in a 12TET interval ranking from most consonant to most dissonant.

No.
The problem is making a general statement like that and then trying to make it apply to your new composition method.
If the premise about chord interval tension where true, then the chords C major and G major would have exactly the same tension, as they are both major triads.
But just like dissonance in the other question tension and resolution are style dependent.
In common practice style C major and G major aren't equal within a key. In C major C is the tonic and a resolution point, but the G chord is the dominant and either resolves to C or can be a partial resolution point. In this way, in the key of C major, the G chord has more tension than the C chord. If the key is G then G major is the tonic and C major is the subdominant which yet again have different levels of resolution. Your could use C major and G major in the key F major and change the resolution roles yet again!
Also, in common practice notions of resolution aren't very dependent on chord dissonance. The viio6 chord is diminished and the V chord is major, both commonly resolve to the I chord. viio6 I isn't heard as a stronger resolution than V I. If anything, it's the other way around. V I would be the stronger resolution.
Common practice resolution is not a mathematical property. It's also not a matter purely of dissonance. In common practice chords operate more like a grammar. V I is the strong resolution, because that's the idiom. You could even say it isn't logical. The more dissonant viio6 should provide a stronger resolution in a logical system. But that isn't the idiom of common practice.
Of course you don't need to follow common practice conventions. You can make up your own mathematical system of chords and resolution, but you don't need to look for existing musical premises to do so. You don't need a universal definition of tension and resolution to make your system.
Answer: In a sense this question rests on the same core set of assumptions as your previous question, which I tried in my answer to address, but it seems that you are essentially viewing your goal through the same framework as before.
First let me say, the project of trying to understand music from theoretical, logical (even mathematical) principles is one I admire, and a passion I share.  And it seems like you have some interesting thoughts on the matter too.  However, I would caution you that when trying to approach this problem, "how to look at music through an essentially scientific standpoint", you look at the music that is in front of you, and try to work out theoretical principles that fit to the music, not the other way around.
When Newton looked at the motion of the planets, he didn't think up a neat and beautiful theory, and then work out how the planets motion could be explained by it; he looked at the planets and tried to work out what theoretical principle best explained their motion.
And when Einstein later approached the same problem, he didn't insist on making the planets conform to Newton's (or any other laws), he theorized, and then extrapolated his theories to their effects in reality. If the theory matched the observation, it was correct, and if not then it was discarded.
You propose the following ideas in your question (which fundamentally are the same ideas embedded in this previous question:

that all simultaneous combinations of pitches (or chords) have a quality of "dissonance" or "consonance"
that this quality is not absolute, but granular.  A chord can be said to be "more consonant", "more dissonant" or some combination of the two.  If you like, that there is a sliding scale between "consonance" and "dissonance" for a given chord, and every chord falls somewhere along that scale.
that this position on the scale between dissonance and consonance can be described in scientifically objective terms.  One chord can said to be "more consonant"/"less dissonant" than another, and vice verse.  Let us call this property "harmonic stability" so that we have an unambiguous word to describe it (call it anything you want of course, to (mis)quote Feynman, "you can call it lemon meringue pie if you like, it doesn't matter as long as it works"
that the "harmonic stability" of a chord can be measured or predicted in a way that is derived from a ranking of the stability of intervals which constitute that chord, perhaps by an addition of the ranking of the intervals within a chord for example.
that the tension or resolution of a series of chords (known is western music as a "chord progression") can be described based on this "harmonic stability", that a "more harmonically stable" chord will resolve to a "less harmonically stable" chord, and so on.

to quote you:

"Correct? If not could you kindly correct this statement?"
  and, if correct:
  "How exactly would you specifically measure the consonance or dissonance of a chord based off the intervals used?"
  with the qualifier
  "I'm seeking this information to produce the specific desired amount of tension and resolution along an entire chord progression"

So in order to answer these questions, let us go through the assumptions as I have outlined them (the form is different from your question, but I believe I have accurately characterised your standpoint).
1) all simultaneous combinations of pitches (or chords) have a quality of "dissonance" or "consonance"
This one ought to be relatively uncontroversial.  I have in my time here occasionally come across people who have argued "it's all relative" or "all cultural", but, while that is at least in part true, a look at the science (psychoacoustics), philosophy (a logical analysis of the our own subjective experience in relation to music from other cultures for example) or anthropology (more specifically, from comparative musicology/ethnomusicology) tells us that there is some fundamental human response to "euphony" and "cacophony" that is in some sense universal between different cultures.
2) This quality is not absolute, but granular
Again, let us for the purpose of this answer take this as read, for similar reasons.
3) This position on the scale between dissonance and consonance can be described in scientifically objective terms, (which I will call "harmonic stability")
Now we're starting to get to the interesting part, the meat of the problem. Whether this is true is indeed a very interesting question, and some theorists have done some very interesting work on this subject (which I admittedly, have only glanced at).  Whether this has been established as possible I couldn't say for certain, but it's certainly a worthy goal, and that's good enough for me (and I expect for you too).
4) The "harmonic stability" of a chord can be measured or predicted in a way that is derived from a ranking of the stability of the intervals which constitute that chord
Now this is certainly an interesting hypothesis. I've not heard this suggested in such terms before, but it's certainly food for thought.  I don't know that it's necessarily original (it seems like a relatively logical first step), but, on the other hand, it might be.
Your question seems to be "how is this done?", but in a sense, that's the wrong question, because it isn't yet something that's "done", to my mind, you're proposing a novel approach.
Other theorists have proposed ways of measuring the "harmonic stability" of individual chords (some of which I linked to in my previous answer), but I am not aware of any who used this approach.  My advice would be this; develop your approach, and see if it results in sensible answers that match your subjective observations of the "harmonic stability" (or euphony/cacophony) of individual chords.  If it works, then you might want to compare it to the results of other theorists, see whether the answers allign, or whether they differ.
I suppose a way you might do it, for example, would be to assign each interval a number based on the euphony/cacophony of that interval, and then look at all of the intervals within a chord, add them up, and assign a value based upon that.  Just an example, I'm not saying this would necessarily give good results, I'm just saying that if you want to pursue this "interval ranking" based approach, you yourself (or perhaps others too on a more "discussion based" forum rather than a Q&A site) need to come up with a way to realise this.  I can't answer the question "how is this done" because to my knowledge so far it never has been done.  And as for how it would be done, that's still an open question (but one I invite you to by all means pursue further)
5) The tension and resolution of a series of a "chord progression" can be described by looking at the "harmonic stability" of the individual chords within it.
No.  It cannot.
At least, not in western music, and not exclusively.
One of the reasons I coined "harmonic stability" as a descriptor, and used the greek "euphony and cacophony" rather than the latin "consonance and dissonance" is because the terms "consonance" and "dissonance" are associated with a western musical tradition which looks as harmony not just in terms of the individual chord itself, but as it appears in a context.  When looking at tension and resolution in western terms, there are multiple factors to take into account.  Yes, one of them is the stability of an individual chord, devoid of its context, but also:

the functional relationship between the current chord and its preceding and following chords (e.g. G chord following an F chord)
the voice leading between these previous and subsequent voicings of each chord (which is different from the functional relationship, and looks at the flow of individual voiced of the chord.)  As Jacob Collier points out, sometimes good voice leading is even more important than functional harmony, and nonsense chords can become part of a pleasant musical "sentence" even if there isn't much of a functional relationship, just because of the good voice leading.
the relationship of the chord to the "key" of the piece (e.g. an F chord in the key of C vs an F chord in the key of E are very different beasts)

The terms "consonance" and "dissonance" are often used in ways that include all of these concepts, not just the stability of a chord in its own right, but also in a music context (the key, the voice leading, and the functional relationships).  The Greek terms "euphony" and "cacophony" more unambiguously refer to just the chord it its own right; how "stable" or "unstable" a chord is, and the term I coined "harmonic stability", can mean whatever I want it to mean, so I decided to use it to refer to the property of a chord on its own.
Now, if your goal is to create a new way of writing music, then it would be very interesting to hear what music that completely eschews tonality and functional harmony, and instead focuses exclusively on the consonance and dissonance of individual chords, then that would be an interesting project, and I would be really interested to hear what music composed along those principles sounded like (it would certainly be unique!).
If your goal is to describe western music, as it exists, then it is insufficient for this purpose.
However, it is certainly one aspect of western harmony, and one of the many tools in the palette of a musician.  I think think of examples where using chords and voicings that are "less stable" at moments of tension, and chords and voicings that are "more stable" at moments of resolution has been used to great effect by musicians.  But it's by no means the only consideration.
I'll give an example here, I know what piece of music I want to use, and how this will show how dissonance and consonance of individual chords can be used to great effect, but how it also isn't sufficient to explain the song, but right now I don't have the time to write all the transcription (this has taken long enough as it is), so I'm just going to leave this answer here, as-is, in abstract terms without an example for now, and come back when I have some more time.
Comment: Many thanks for your extraordinary answer! I appreciate the investment in thought and time. I'm not approaching this subject from a basis of fitting a theory into science but instead like you stated, the other way around. Due to my first principle approach to this subect, at times it may seem the contrary but very well articulated on your part. I have taken all the information you have provided and will include the necessary into my documents. If any questions arise from your answer throughout my studies, i will reply to you again. I'm very grateful for your help, thank you!!


Help with Infinite series + Integral Test + Improper Integrals

Question: I am having some trouble with the infinite series $\displaystyle\sum_{n=2}^{\infty}\frac{1}{n\ln^2n}$ .
I used the integral test and simplified it to $\int_{\ln 2}^b - \frac 1{\ln(n)}$ (implied infinity since improper integral). But this website:
http://www.math.northwestern.edu/~mlerma/courses/b17-99w/b17w99-1mid-ans.pdf
# 2 on the website has the same exact question that I have but instead of the answer on the website being bounded from $\ln(2)$ to $b$, its $2$ to $b$. Doesn't the boundaries have to change because of the bounds should be in terms of the $u$-substitution? So since $u = \ln(n)$. Plug in $\ln(2)$...
Answer: You only change the limits of integration if you are trying to evaluate your integral in terms of your substitution. If you do a $u$-sub, integrate, then convert your antiderivative back before evaluating at the limits of integration, then you need the original limits.
The integral test says you need to evaluate $$\lim_{N \to \infty} \int_2^N \frac{dx}{x\ln^2(x)} = \lim_{N \to \infty}\left[ \frac{-1}{\ln(x)}\right]_2^N \\ = 0-\left(-\frac{1}{\ln(2)}\right) \\ = \frac{1}{\ln(2)}<\infty$$ so the sum is convergent by the integral test.
Comment: I understand, but I have another question. Wouldn't that mean that there is no point in changing the limits of integration in terms of u since you would be converting the answer back to its original form to get the answer? I don't understand when I would try to use the integral boundaries in terms of u in the first place.
Comment: Sometimes the sub is very nasty, and it's just easier to convert the limits instead of undoing the sub after getting the antiderivative. It's just an option we can choose, but in either case the same answer will result.
Comment: @Nocturne If you are interested in an example, check out the sub I used in my answer here. http://math.stackexchange.com/questions/1100394/how-is-the-integral-int-frac1aemxbe-mx-dx-solved/1100437#1100437

Had this been a definite integral, I would definitely have changed the limits instead of undoing the sub.
Answer: Here's where you got a bit mixed up: $~\displaystyle\sum_{n=2}^{\infty}\frac1{n\ln^2n}~\approx~\int_2^\infty\frac{dx}{x\ln^2x}~=~\int_{\ln2}^\infty\frac{dt}{t^2}$


Is there a way to stop Google Chrome from showing most visited sites on a blank tab?

Question: Whenever I open a new tab in Google Chrome I see the Google search bar plus 8 thumbnails of recently visited (or most visited) sites. I never click on the thumbnails and find them to be annoying. Is there anyway to disable this in Chrome?
I can think of a hacky workaround like creating a blank page someplace and setting that to be the new tab page, but there must be a better way. Any ideas?
Answer: Since nobody answered I thought I would post and answer to my question:
Use the Empty New Tab Page extension for a new blank tab instead of the default new tab.
There are also some redirect extensions such as Momentum, which loads a different full screen image each day.
Answer: type chrome://flags then Disable "Top Sites from Site Engagement"
Comment: This does nothing
Comment: It seems that every single version of Chrome need its specific solution :D
Comment: wow, who knew there were so many options in chrome --- that seems like a secret page.
Answer: Chrome allows extensions to run on chrome:// urls so one such possible future solution is if AdBlock explicitly requests the permission to run on chrome://newtab then you can just block the div with id most-visited. But currently AdBlock does not request this permission.
You could edit the manifest of AdBlock manually to include this permission or suggest it as a future feature.
Answer: The default new tap page's url is chrome-search://local-ntp/local-ntp.html. You can press F12 to check it. It's a local resource located in
C:\Program Files (x86)\Google\Chrome\Application\{Version}\resources.pak
or
C:\Users\%username%\AppData\Local\Google\Chrome\Application\{Version}\resources.pak
Open it with a HEX editor, search text
cur.style.opacity = 1.0
, and replace it with
cur.style.opacity = 0.0
Tested on Chrome 77.0.3865.90 .


Mean value of a (portion of an) exponential distribution satisfying a given inequality

Question: I have some questions about exponential distributions. I have tried googling around but with no success.
Imagine we have an HTTP server which serves Web pages in $x$ milliseconds, with a mean service time $s$. In my understanding, this can be modelled using an exponential distribution, right? Now:
a) If I consider only the requests s.t. $x \leq k$ (e.g. $k=400$ ms), will these still follow an exponential distribution?
b) Is it possible to compute the mean value of $x$ for the requests, when $x \leq k$ ?
c) Are the answers for (a) and (b) the same if I consider $x \gt k$?
Answer:
In my understanding, this can be modelled using an exponential distribution, right?

Perhaps - sometimes service time type distributions are reasonably close to exponential, and sometimes they aren't. What convinces you that for your particular problem, the distribution will be sufficiently close to exponentially distributed for your purposes?

If I consider only the requests s.t. $x≤k$
   will these still follow an exponential distribution?

No, if the distribution without the restriction was exponential, it will be truncated exponential.

Is it possible to compute the mean value of $x$
  for the requests, when $x≤k$?

Yes, it is possible to compute the conditional mean.
If the mean service time is $\mu$ (edit: that's your $s$) and you truncate at $k$ (so you only see those service times that don't exceed $k$, ignoring the others) then given that $p=e^{-k/\mu}$ is the probability that the service time exceeds $k$, the mean service time for those that don't exceed $k$ is $\mu-\frac{p}{1-p}\cdot k$.
This is readily obtained in several ways. I did it by treating the original service time as a mixture of the truncated part and the tail (the distribution beyond the truncation point), and the mean of the mixture is then the mixture-weighted average of the component means, which we then equate to $\mu$. All terms except the required mean of the truncated distribution can be written by inspection and then the resulting equation solved for the truncated-mean.

Are the answers for (a) and (b) the same if I consider $x>k$?

Yes in that they're still "No" and "Yes" but the distribution (shifted exponential) and the mean time ($k+\mu$) will be different.
Comment: The formula for (or a pointer to) the conditional mean would be much appreciated, tnx!
Comment: I have given the formula, and added some more my answer to the last part
Comment: Can we say that it's rather intuitive - the mean is the mean of the exponential decreased by the odds ($\frac{p}{1-p}$) of getting a service time $k$? Did you just "see" it, or did you derive it?
Comment: @Antoni I derived it using the approach I described in the answer -- by treating the original exponential as a mixture and equating the known mean to the mean of the mixture then solving for the truncated mean -- but since everything else but that value is obvious by inspection it only takes a couple of lines of simple algebra. (I then double checked by using simulation for a few values of $k/\mu$). It is nice the way the odds of exceeding the truncation point come in..


How can I print article author profile picture?

Question: I have a blog where basic author information needs to be printed out.
Basically, I want to print author name and profile picture in my article teaser template.
I tried googling but none of the answers seemed to help.
Can I somehow access Author object?
Answer: Put this on top of your node.html.twig or similar template
{%
  set author_pic = {
    '#theme':      'image_style',
    '#style_name': 'thumbnail',
    '#uri':        node.uid.entity.user_picture.entity.uri.value,
    '#attributes': { class: 'authorImg' },
  }
%}

Use this anywhere in the same template you want to output the author image
{{ author_pic }}

Comment: Thanks, works fine.
Though, I had to delete /* image style name */ comment, otherwise php error occurs.
Comment: Yes you are right I did not realize ... corrected it


Bootstrap ButtonGroup Select 1 Button Only

Question: I am using Boostrap 3.3.7 and are trying to use Buttons as 'Radio Button'.
This is the HTML:

    <button name="resolution" class="btn btn-default btn-sm">
        720
    </button>
    <button name="resolution" class="btn btn-default btn-sm">
        480
    </button>
    <button name="resolution" class="btn btn-default btn-sm">
        360
    </button>

When I select one button, then select another one, the first does not get deselected. I tried to deselect it with JQuery but it did not work:
$('.btn-group > .btn').removeClass('active')
$('.btn-group > .btn').eq(0).addClass('active')

How can I make sure I keep one selected only? My objective is to have one button selected so I could use it. Something like this:
$("#submitButton").click(function () {
                        alert($('.btn-group > .btn.active').text());
                    });

Answer: In order to maintain active the current button you may delegate the click event to avoid the event propagation and buttons change state.
So the snippet is:

$(document).on('click', '[name="resolution"]', function(e) {
  e.stopPropagation();

  // add class active to current button and remove it from the siblings
  $(this).toggleClass('active')
        .siblings().not(this).removeClass('active');
})

// for test purposes
$(function () {
  $('#myBtn').on('click', function(e) {
    console.log('Active button: ' + $('.btn-group > .btn.active').text());
  })
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <button name="resolution" class="btn btn-default btn-sm">
        720
    </button>
    <button name="resolution" class="btn btn-default btn-sm">
        480
    </button>
    <button name="resolution" class="btn btn-default btn-sm">
        360
    </button>

<button id="myBtn" class="btn">Click Me To debug</button>
Comment: @RonaDona I'm glad for you.
Comment: This solved my issue too after researching for an hour! Thanks!
Comment: gaetano@ when I do this, alert($('.btn-group > .btn.active').text()); does not give a value anymore. It gives an empty string.
Comment: @RonaDona: Now I added the feature: if you click again on the same button the state change from active to not active. This in order to give you the possibility to deselect the button itself. Let me know if this time it works like you want. Thanks again


Create an EventSubscriber for a specific module

Question: I'm attempting to make something occur at a specific event in the GatherContent module found here https://www.drupal.org/project/gathercontent
Based on the information here http://help.gathercontent.com/importing-and-exporting-content/drupal-integration/drupal-integration-extending-the-module-using-the-api and several tutorials and documentation
I created a module with the code entered like so
my_gathercontent.services.yml
services:
  my_gathercontent:
    class: '\Drupal\my_gathercontent\EventSubscriber\MyGatherContentSubscriber'
    tags:
      - { name: 'event_subscriber' }

src/EventSubscriber/MyGatherContentSubscriber.php
namespace Drupal\my_gathercontent\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event Subscriber MyGatherContentSubscriber.
 */

class MyGatherContentSubscriber implements EventSubscriberInterface {
    public function onGatherContentPostImport(DrupalgathercontentEventPostImportEvent $event) {
        \Drupal::logger('my_gathercontent')->notice('This is a test');
        drupal_set_message("Debug: This is a test.");
        var_dump($event);
    }
    public static function getSubscribedEvents() {
        $events['gathercontent.post_import'] = ['onGatherContentPostImport'];
        return $events;
    }
}

And none of those messages get logged. I do now receive a page not found message after performing an action that should trigger that event. I'm not sure what I'm doing wrong.
Is there something wrong with the way I'm attempting to subscribe to the event?
Answer: Each event in the $events array should itself be an array; try:
$events['gathercontent.post_import'][] = ['onGatherContentPostImport'];


How to apply a theme function/template to my form

Question: I think theme_form() is responsible for rendering forms! I want to change the look of a form, a lot. I think just instead of theme_form I can use my custom theme function/template file.
I can use hook_form_alter to change any form's structure using my module. Now my question is, how do tell the form to use a theme function/template I've created?
Is there a #theme property (or something like that) available for forms, which I can set to my theme function/template file?
P.S. I checked out this but I need more explanation, when the case is: I'm trying to theme a form defined by another module/core modules.
Answer:
Is there a #theme property (or something like that) available for forms, which I can set to my theme function/template file?

Yes there is. Take a look at the #theme key in the Form API Reference. Take a look at the code for theme_form() for the default implementation.
Answer: Open template.php of your theme
function YOURTHEMENAME_theme($existing, $type, $theme, $path) {
  $hooks['form_id_of_form'] = array(
    'template' => 'path_to_tpl_file',
    'arguments' => array('form' => NULL),
  );
  return $hooks;
}

Also you can try
function hook_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'form_id_of_form') {
    $form['#theme'] = 'path_to_tpl_file';
  }
}

Comment: This is not quite right. In your hook_theme, you declared the theme callback to be "form_id_of_form". Therefore, the hook_form_alter should implement $form['#theme'] = 'form_id_of_form', not 'path_to_tpl_file'


Need advice to improve response on click button

Question: Need advice for AsyncTask. I have inside my activity private class which extends AsyncTask and I in doInBackground create new AsyncTask and repeat that all time ( parse JSON and update some labels on screen). Problem is that I have bad response on buttons when I click on  them, so I need advice how to improve response on click ( when I click button is green and that is couple seconds  before starts action ). Do I need to put Thread.sleep in doInBackground  or there is some better way to improve  ?
Comment: Try removing the private part from your inner class.
Answer: I think you should not create a new AsyncTask inside doInBackground. instead, perform some kind of loop (depends on your code). If you create multiple instances of AsyncTask (one inside another) you create way too many threads and make the UI thread much more busy too.
Comment: I do it in onPostExecute so I don't create new threads, I think, because one die another create and so on...
Comment: It's not what you wrote... please re-phrase the question


How to assign column data into column name

Question: Please find below sql query
create table test_bin (date1 varchar2(10), desc varchar2(10), values number(10));
insert into test_bin values ('10DEC2015', 'ABC', 10);
insert into test_bin values ('10DEC2015', 'CDE', 20);
insert into test_bin values ('10DEC2015', 'XYZ', 35);
insert into test_bin values ('12DEC2015', 'ABC', 10);
insert into test_bin values ('12DEC2015', 'CDE', 45);
insert into test_bin values ('12DEC2015', 'XYZ', 98);
insert into test_bin values ('13DEC2015', 'ABC', 76);
insert into test_bin values ('13DEC2015', 'CDE', 86);
insert into test_bin values ('13DEC2015', 'XYZ', 63);
commit;

question:-
I am expecting following output, I tried my level best i can't able to get proper query
DESC 10DEC2015 12DEC2015 13DEC2015
ABC     10          NULL    NULL
CDE     20          NULL    NULL
XYZ     35          NULL    NULL
ABC     NULL        10      NULL
CDE     NULL        45      NULL
XYZ     NULL        98      NULL
ABC     NULL        NULL     76
CDE     NULL        NULL     86
XYZ     NULL        NULL     63

Comment: It's much better to store dates in `date` column not `varchar2`
Comment: If you add another row with a new date to your table, do you expect that date to show up as a new column when you run your query?
Comment: But for a fixed window of 4 days, from some supplied start date? Or some other numbers of days? What about days with no data, like 11DEC2015 - the column should not appear? What would the output be if you added a record for 14DEC2015, or 07MAR2015? (Which is what jarlh was asking really). You need to clarify your requirements, and then show us how far you have got and what issues you are having.
Comment: HI Sagi, am using oracle 10g.
Comment: Do you have a starting 'date' and a number of days from that to always show? Or a maximum number of 'dates' that the table may contain? Or does it need to be completely dynamic, with a variable number of columns? (Or does the question title mean you know how to manually pivot the values, but not how to set the column *name* in the result set?)
Comment: @Aleksej : Already it has been defined, we can't change data type
jarlh : we can't able to add one more new column
AlexPoole: Yes alex, this date will increase day by day.
Answer: It's just one way :
select desc,
       SUM(case when date1='10DEC2015' then values end) as "10DEC2015",
       sum(case when date1='12DEC2015' then values end) as "12DEC2015",
       sum(case when date1='13DEC2015' then values end) as "13DEC2015"
from   test_bin
group by date1, desc;

It supposes that you already know all existing values for date1, except if you create dynamically your request.
PS : be careful about using SQL keyword as column name
PS1 : http://www.sqlfiddle.com/#!9/20068f/5, it's in MySQL because 10g was not available and Oracle is far away from me AND column name has been changed to avoid conflict with SQL keywords
Comment: Oracle identifiers can't start with numbers unless they're quoted. But I think the OP wants it to be more dynamic than this as well; it still isn't clear though.


QNX USB Utility not found?

Question: I have a physical box with QNX 6.3.0 installed.  PS/2 mice and keyboard work fine.   I'm trying to see if I can get a USB mouse going.  What info I could find seemed to say I should start with:
usb -vvv
However, I get this:
$ usb
/bin/sh: usb: not found

Where's the usb utility supposed to be installed at, and why is it not found?  Isn't it supposed to be a default utility?
Answer: I think you should try for :
cd /fs/usb0 In my case this usb0 is the desired name . you can change accordingly .

QNX USB Utility not found?


AppManagementServiceApplication throws "Microsoft SharePoint is not supported in 32-bit process." when registering hosted app on site

Question: I'm on SP 2013 enterprise single server dev machine
I have prepped SP to host a remote on prem hosted app.
I navigate to /_layouts/15/AppRegNew.aspx and enter the App Id, Secret, etc and hit create ... error ID 3 and 1309 are thrown:
ID 3 is:
WebHost failed to process a request.
Sender Information: System.ServiceModel.ServiceHostingEnvironment+HostingManager/1660113
Exception: System.ServiceModel.ServiceActivationException: The service '/9fabc3ed921a42739ebeb5576c6b4e6a/AppMng.svc' cannot be activated due to an exception during compilation.  The exception message is: Microsoft SharePoint is not supported in 32-bit process. Please verify that you are running in a 64-bit executable.. ---> System.PlatformNotSupportedException: Microsoft SharePoint is not supported in 32-bit process. Please verify that you are running in a 64-bit executable.
followed by 1309:
Exception information:
Exception type: ServiceActivationException
Exception message: The requested service, 'http://servername:32843/9fabc3ed921a42739ebeb5576c6b4e6a/AppMng.svc' could not be activated.
The app management and subscription services are started and running. I have a valid trust setup.
Thoughts?
Answer: In IIS there were app pools that had enable 32-bit set to true, so I set it to false and was enable to register the app.


Users can choose image style on content type?

Question: I want to display image style list in particular content type. Users can choose their image style from the list provided.
Is it possible to achieve this?
Answer: Hopefully I've understood you properly; I think you're looking for the Formatter Field module:

The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.
Comment: The Formatter Field is a generic solution, which allows to change the formatter field of any field type (not only the Image fields). However, as a consequence the list of image styles to select from cannot be limited (as asked in the question)..
Answer: If you want an user to select an image style when he/she uploads an image, take a look at the Image Style Selector module. The list of image styles that the user can select from is configurable by the website administrator.
The screenshot below shows the (basic) functionality of this module.


Why does my Tizen Web App behave differently in debug mode?

Question: In debug mode
tizen.application.getCurrentApplication().getRequestedAppControl()

works like a charm. But in run mode my app chrashes at this line.
Comment: Have you tried to call them seperatly in order to get the function call that causes the error?
Answer: If you want to check for a launch request, use a try-catch block like following:
function checkLaunchRequest() {
        var appControl
        ,   appOperation
        ,   tmp
        ;

        try {
            appControl = app.getCurrentApplication().getRequestedAppControl().appControl;
            appOperation = appControl.operation;
            console.log("checkLaunchRequest operation: " + appOperation);

            if (appOperation.indexOf("http://tizen.org/appcontrol/operation/view") !== -1) {
                ...Do something here...
            }
        } catch (err) {
            console.error("Invalid launch request: " + err.message);
        }
    }

Also be sure you have set correct privilege in config.xml. You will need to set "http://tizen.org/privilege/application.launch".


How to identify a paragraph?

Question: Is there a way to identify a paragraph in Drupal 8. Like is there a function to get the type as paragraph in code level?
I need to get it from a form alter function. My requirement is to get all the paragraphs in a form. Or identify the paragraph fields.
Comment: try `$paragraphs->bundle();` or `$paragraphs->getType();`
Comment: @NoSssweat Thanks ! but i need to get it from a form alter function. My requirement is to get all the paragraphs in a form. Or identify the paragraph fields.
Comment: Can you not do this within `TEMPLATE_preprocess_paragraph` ?
Comment: Can you add more details about the form? Is it an entity add/edit form or a custom one?
Answer: You probably should look at the paragraphs module code, it does a lot of this.
That said, the basic process would probably be:

Identify the form fields that are entity_reference_revision fields.
Check that the field is limited to paragraph types (can just check
1st one).
If it is an update form, get the referenced entities from the field.
You will then need some recursive code to walk the paragraph tree to
get sub paragraphs.

This will require using a lot of the field definition classes to get the information needed.

How to identify a paragraph?


Can a randomized system cause unfair dice to make a fair result?

Question: Say I have 6 dice with 6 faces in a bag that are all weighted unfairly so that each dice have the same unfair probability of landing on a different side. (i.e. the probability that one of the unfair dice has a higher chance on landing on the one's side has the same probability as another unfair dice to land on the twos side that another die has the same probability on the threes side ect)
I then grab a die at random from the bag and I roll get a number then put it back into the bag. I then randomly grab another dice.
Dose the resulting number have the same chance as a regular 6 sided dice ($\frac{1}{6}$)?
Rather then doing the math I have tried using logic and I believe that it will cause the resulting number to be fair but I probability is not strong suit and I would love to hear someone else's opinion.
Answer: Yes, this is fair. Think of the bag as containing $36$ possible faces. Your hypothesis about how the weighting is distributed means that each of the six possible values has the same probability when you choose a die and roll it: $1/6$.
The hypothesis is very strong. The only way I can imagine satisfying it in a physical situation is to have six blank dice equally unbalanced in the same known way. Then mark the faces as specified.
Answer: For each die, there is probability $p$ to land on the biased face. Then, it has probability $\frac{1-p}{5}$ to land on any of unbiased faces. Since each number is biased on $1$ die and unbiased on $5$ dice, we have
\begin{align*}
P(\text{rolling a 1}) &= P(\text{rolling a biased 1}) + P(\text{rolling an unbiased 1}) \\
 &= \frac{1}{6} \times p + \frac{5}{6} \times \frac{1-p}{5}\\
&= \frac{1}{6} \times p + \frac{1}{6} \times (1-p) \\
&= \frac{1}{6}
\end{align*}
Therefore, this process replicates rolling an unbiased 6-sided die.


Best way to sanitize callback for jsonp?

Question: What's the best way to sanitize the callback for jsonp?
I currently have something like:
<code>function api_output($data) {

    if (isset($_GET['callback'])) {

        $cb = preg_replace("/[^][.\\'\\\"_A-Za-z0-9]/", '', $_GET['callback']);
        send_js_headers();
        print sprintf('%s(%s);', $cb, json_encode($data));
        exit(0);

    }

        send_json_headers();
        echo json_encode($data);
        exit(0);

}
</code>
Why? :
Do I need to sanitize the callback parameter from a JSONP call?
Comment: Hi Carlos, can you be more clear about what you're trying to do, and quickly, before your question gets closed!? If it's what I think you're asking, I'm curious to see the answers. Good luck!
Comment: Why do you try to sanitize the callback-parameter? If someone uses jsonp wrong it's his own fault.
Comment: I'm not sure why you're trying to at all.  You're trying to prevent a client from XSS'ing itself??
Comment: The function `api_output` should have two parameters instead of one. `$_GET` should be moved out of that function. But what exactly do you feel is in need of getting sanitized? And why?
Comment: The GET parameter was just there for clarity, this is a wrapper, our class is way more complicated.
Answer: The callback must be a valid javascript identifier, and your server side code should verify this. Javascript identifiers can only contain alphabets, numbers, underscore and $ symbol.
As long as the callback name is a valid JS identifier, you don't need to encode/escape it. And if the callback isn't a valid identifier, you should simply return a 400 error code.
You must NOT replace characters in the callback name. There just isn't any point in doing so, because the client code will no longer have the callback function defined.


Can Windows Sharepoint Foundation 2010 be installed on Windows Server 2008 R2 Foundation?

Question: I think the question is quite straightforward; is it possible, has anyone tried it, or does anyone know of any issues encountered when doing it?
Thanks,
Yusuf
Answer: Yes it's possible, see here for more information:
Windows Server 2008 R2 Foundation


composer.json to install vendors on development environment differently

Question: How to set composer.json to install some vendors on development environment different than on production eg. PHPUnit install on development and not on production.
Answer: You can use require-dev section for this:
"require-dev": {
    "phpunit/phpunit": "~4.7"
}

If you want to install only packages from "require", e.g. on your production server, you can do it like this:
composer install --no-dev

It will exclude "require-dev" packages, see composer install options docs for more.
Comment: And run `php composer.phar install --dev` after
Comment: @Inurosen No need for that, it's on by default. To turn it off add `--no-dev` (see [`composer install` options](https://getcomposer.org/doc/03-cli.md#install)).
Comment: @fico7489 It's not related to prod (site.com)/dev (localhost) as we know it. It's only on your root `composer.json` on by default. Meaning on production, you'd install composer it via `composer install --no-dev`. To exclude all development-only packages.
Comment: how composer know which enviroment is dev ? Only --dev in argument while instaling is option ?


ASP.NET Windows Authentication using server-local accounts?

Question: I'm trying to set up an ASP.NET application to use Windows Authentication.
But the IIS server is not part of a domain, it is a sole server hosted in our Rackspace account.
I'd like to have the Windows Authentication module validate against the list of local Windows users on the IIS server. Is this possible?
Anonymous Authentication is off
Basic Authentication is off
Windows Authentication is on
But when I enter credentials for a local machine account as
machinename\user
password
it doesn't seem to work. It just prompts me again.
Answer: It appears that you can use local accounts, but I'm getting some kind of server error when the account tries to authenticate.
Once I found the error in the event logs, and got the status code, I was able to track it down, and find this answer, which worked exactly!
Answer: Is possible make a local machine validation, like this:
var bool valid = false;
using (var  context = new PrincipalContext(ContextType.Machine))
{
    valid = context.ValidateCredentials(username, password);
}

Comment: This looks like you would be doing Forms authentication though, and just checking it manually against the local machine yourself? We need it to be Windows authentication, and pop up with the browser prompt for user/password.
Comment: This case, is only enable Windows Authentication in a IIS Site.
Comment: That's what I have. I have Anonymous Authentication turned off, and Windows Authentication turned on. But it doesn't seem to work with a local account that exists on the server (NOT a domain account).
Comment: I did a local test successfully. See https://pasteboard.co/JiSPSOP.png


Do I need to account for combinations in this probability calculation?

Question: Consider a problem of this sort:

We know that a certain drug has 75% chances of curing a disease. If the drug is administered to 20 patients, what is the probability that exactly 15 of them will be cured?

Now, should the solution be $$0.75^{15}\cdot0.25^{5}$$or  $20\choose15$$\cdot$$0.75^{15}\cdot0.25^{5}$?
If I do need to account for combinations, then why is that?
Comment: Your first calculation computes the probability that a specific group of $15$ is cured.  Note:  you should clarify whether you mean "exactly $15$" or "at least $15$".
Answer: You need to account for combinations because the way your wrote your expression could be read as: the first fifteen persons to take the drug are cured and the last five are not.
Since the question says implicitly that any fifteen out of twenty were cured, you need to account for all possible sets of fifteen persons being cured, which is done using combinations (we are choosing without replacement).
Answer: As already answered (correctly) by Ertxiem, I just want to elaborate more. Suppose there are three patients, A,B,C. By "drug has 75% chances of curing a disease" means that if the drug is applied to A, he has 75% chance of getting cured, same for B and C. Now the probability of
A getting cured, B getting cured and C not getting cured is 0.75.0.75.0.25.
A getting cured, C getting cured and B not getting cured is 0.75.0.75.0.25.
B getting cured, C getting cured and A not getting cured is 0.75.0.75.0.25.
So finally the total probability of exactly two getting cured is $3 \choose 2$0.75.0.75.0.25


Water year time series: resampling annually for custom non-calendar year dates

Question: I am writing my very first loop since resampling doesn't allow me to use custom start dates for annual sampling. My goal is to sum up each series of 12 consecutive months in a 30 years time series for a non-calendar year calculation (hydrologic water year Oct-Sept). The dataset begins in the month of October, so I figured I would simply add together the first 12 rows, the next 12 rows, and so on. Perfect for a loop, right?! Two questions:
1) What is the simplest way to add 'n' rows together which is output into a new DataFrame, indexed by year.
2) My attempted solution to question 1 is below, and it works. However, the data type of the output is a 'NoneType' which I cannot merge back with another DataFrame via pd.concat. How do I fix this?
def Water_Year_Total(Monthly_Data_30yrs):
    for i in range((len(Monthly_Data_30yrs))//12):
        x=0
        y=12
        new_value=sum(data[(x+(12*i)):(y+(12*i))])
        print(new_value)

The for loop first counts the number of rows via the len() function, then divides it by 12 to get the number of years in the dataset, and then iterates the sum loop i times before printing out the result.
Answer: Your function doesn't return anything, which is why it yields a NoneType when it finishes running. Create a variable before the for loop, add the different new_values to it, and then return that variable after the for loop completes.


odoo / openERP one2many fields dynamic domain

Question: I want to search records of one2many field that depends on another fields.
here my code,
Parent class:
class SaleOrder(models.Model):
    _inherit = 'sale.order'

    customer_product_ids = fields.One2many('product.product',
                           compute='_get_partner_products')
    order_line = fields.One2many('sale.order.line', 'order_id')

Child class:
class SaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    order_id = fields.Many2one('sale.order')
    product_id = fields.Many2one('product.product')

View
 <record id="view_ata_sale_order_form_inherit" model="ir.ui.view">
        <field name="name">view.ata.sale.order.form.inherit</field>
        <field name="model">sale.order</field>
        <field name="inherit_id" ref="sale.view_order_form"/>
        <field name="arch" type="xml">
            <field name="partner_id" position="after">
                <field name="partner_channel_id" invisible="1"/>
                <field name="customer_product_ids"/>
            </field>
            <xpath expr="//tree/field[@name='product_id']" position="attributes">
                <attribute name="domain">[('id', 'in', [rec.id for rec in parent.customer_product_ids])]</attribute>
            </xpath>
        </field>
    </record>

By default, a customer can see all the products defined.
In my case, I need to filter the products depends on customer selected.
Each customer can have different list products or if they didn't categorize they can see all the products.
I tried the code above but got error:
Uncaught Error: Expected "]", got "(name)"

I guess the error come from this code:
<attribute name="domain">[('id', 'in', [rec.id for rec in parent.partner_product_ids])]</attribute>

my question,
is it possible to do python loop comprehension like the code above (within view)?
Thank you.
Answer: In your case you need to use onchange and return dynamic domain to your one2many field
you should have some thing like this:
@api.onchange('partner')
def onchange_partner(self):
    ids=search for products that have this partner
    then return some thing like this {'domain': {'Many2one or One2many': [('id', 'in', ids)}}

i will not write the code for you,so you must search for the onchange and apply it.You can find some info here .
Comment: hello Mostafa,  yeah, I'm a new guy for odoo development, I've tried your suggestion but it's not working as the expected. I have post my solution, and it works. :)
Answer: I've tried the solution from Mostafa Mohamed, but it's not affected the products list (they keep displaying all the products).
What should onchange methods do and return?
Here my code,
@api.multi
def onchange_partner_id(self, part):
    res = super(SaleOrder, self).onchange_partner_id(part)
    domain = [('active', '=', True), ('sale_ok', '=', True)]
    if part:
        partner = self.env['res.partner'].browse(part)
        if partner and partner.sales_channel_id:
            domain.append(('sales_channel_ids', '=',
                           partner.sales_channel_id.id))
    product_ids = self.env['product.product'].search(domain)
    res.update(domain={
        'order_line.product_id': ['id', 'in', [rec.id for rec in product_ids]]
    })
    return res

I've tried another solution, so I override search_name and search method within product.product model and it's works.
here my code,

inherit sale_view.xml
<xpath expr="//tree/field[@name='product_id']" position="attributes">
    <attribute name="domain">[
        ('sales_channel_ids', '=', parent.partner_channel_id),
        ('sale_ok', '=', True),
        ('active', '=', True)
    ]</attribute>
    <attribute name="context">{
        'partner_channel_id': parent.partner_channel_id,
        'partner_id': parent.partner_id,
        'quantity': product_uom_qty,
        'pricelist': parent.pricelist_id,
        'uom': product_uom,
        'company_id': parent.company_id
    }</attribute>
 </xpath>

and the override method
2) search_name method:
@api.model
def name_search(self, name, args=None, operator='ilike', limit=100):
    if 'partner_channel_id' in self._context:
        target_domain = findDomain(args, 'sales_channel_ids')
        if len(target_domain) == 1:
            idx = target_domain.keys()[0]
            domain = target_domain.values()[0]
            if False in domain:
                args.pop(idx)
    return super(ProductProduct, self).name_search(name=name,
                                               args=args,
                                               operator=operator,
                                               limit=limit)

search method:
@api.model
def search(self, args, offset=0, limit=None, order=None, count=False):
    if 'partner_channel_id' in self._context:
        target_domain = findDomain(args, 'sales_channel_ids')
        if len(target_domain) == 1:
            idx = target_domain.keys()[0]
            domain = target_domain.values()[0]
            if False in domain:
                args.pop(idx)
    return super(ProductProduct, self).search(args=args,
                                          offset=offset,
                                          limit=limit,
                                          order=order,
                                          count=count)

What I try to do here is when they detected 'partner_channel_id' in context and domain like this ['sales_channel_ids', '=', False], I removed that domain and keep the rest (customer doesn't have channel can see all the products, no filtering products from them).
Comment: for sure it is a good solution, I'm just telling you mine is shorter and easier :) besides, I've used it in my own code!
Answer: You can't put such code in there. I'd do it in a different way:
Change the product model adding its customer
class Product(models.Model):
    _inherit = 'product.product'

    parent_id = fields.Many2one('res.partner')

then the view can be changed much easier:
<attribute name="domain">[('partner_id', '=', partner_id)]</attribute>

or
<attribute name="domain">[('partner_id', '=', parent.partner_id)]</attribute>

(depending on where is your product_id field...
Comment: Hello Alessandro, thanks for your suggestion, I think I've found another way to make it :)


Slicing series with t-test

Question: I am trying to develop a system for automated performance regression detection. Usually this boils down to setting range for the performance counters manually (e.g. no more than 5% drop in throughput vs. baseline/average of N last results) but I wanted something that could also detect smaller drops that stay in the results for many observations. I could do different thresholds for floating averages etc., but I was thinking about something statistically more sound.
My naive approach was to analyze the last N values (up to last detected change) and do a t-test for x1 .. xk vs. xk+1 .. xn for each k (requiring the subset to have at least few values) at 95% confidence level. I was wondering why I am getting many false positives on real data, so I've generated random series from normally distributed data with the same mean and I've observed the same.
I think that my request to see no false positives is contradicting the set confidence level - is that correct?
Can you suggest a better approach, besides increasing the confidence level? Am I completely off path?
False positives would be more frequent since in fact I will have 10s of counters for each nightly run and the chances multiply.
Answer: I think there might be some other issues related to the interpretation of these sequential test results, but one small suggestion is that you could use the Bonferroni correction to reduce the number of false positives. It will, however, come at the cost of more false negatives.

Slicing series with t-test


javascript HTMLCollection access

Question: I made a website and need to impelment javascript. I would like to get the child nodes from my HTML menu.
Here is a part of my HTML structure:

So, I would like to get the "active" element.
I made the following code:
    function getmenuItem(){
   var SelectedItem = document.getElementsByClassName("active");
   console.log(SelectedItem);
   console.log(SelectedItem.length);
    }

Here comes the problem:
I displayed the console via Firebug and it showed me
HTMLCollection[]
0

Then I tried to access the Collection with SelectedElement[0] but I got "undefined".
Please show me how to get the children of the active element.
Comment: You dont have 'active' class anywhere.
Comment: I thought with active I got the  because there is the active statement.
Answer: The element can only be found after the HTML page has been constructed. If your piece of code is standalone in a

javascript HTMLCollection access