Proof that a certain subset of the reals is not a ring

Question: Let $A = \{x \sin x : x \in \mathbb{Z}\} \subset \mathbb{R}$. Is $A$ a ring under the usual addition and multiplication operations of $\mathbb{R}$? It looks like it's not, but I can't find something concrete to justify this.
Comment: Is this even closed under negation? After all, $(-x)\sin(-x) = x\sin x$ because $\sin x = -\sin (-x)$...
Comment: Under *what operations* ? The usual ones in $\;\Bbb R\;$ ?
Comment: Another identity is that $f(1 \sin 1, 2 \sin 2) = 0$ where $$f(x,y) = y^2 - 8 x^2 (1-x^2) (1-2x^2)^2$$
Comment: It's not immediately clear why there isn't some $y\in\mathbb{Z}$ such that $y\sin{y}=-x\sin{x}$ though (I agree that this is unlikely).
Comment: To take things even further (and actually possibly point to a proof): is there even one non-trivial identity among some finite number of members of $A$?
Comment: @Steven: $\sin n$ is a polynomial in $\sin 1$ whenever $n$ is odd.
Comment: Point taken. Will edit.
Comment: To me it seems hard to refute any closure claims.
Answer: Suppose $A$ were a ring; then in particular, we have $2\sin 1=n\sin n$ for some $n$.  Now, use the duplication formulas for $\sin$ to write $\sin n$ as $(\sin 1)\cdot P_n(\cos 1)$, where $P_n(x)$ is a polynomial of degree $n$ (this can be shown straightforwardly via induction; these polynomials are known as the Chebyshev polynomials of the second kind).  This yields an identity of the form $nP_n(\cos 1)-2=0$, contradicting the fact that $\cos 1$ is transcendental.  In fact, this shows that no non-trivial linear relation can hold among any finite number of members of $A$.
Comment: Thanks, the "additive identity" helps a lot.  So it seems that you're actually proving that $\{\sin(n) \mid n \in \mathbb{N}\}$ is a $\mathbb{Z}$-linearly independent subset of $\mathbb{R}$.  Very nice!
Comment: Could you at least hint at a justification of the last sentence?
Comment: @MannyReyes I should correct that to 'additive identity', actually (I was thinking of $A$ as a group, not a ring).  The proof in that case is almost identical: use the $\sin n$ identity to write each of the terms in the form $(\sin 1)\cdot P_n(\cos 1)$, sum, and derive a contradiction.
Comment: (Note that similarly to a now-deleted answer from @MarcinŁoś, this uses the Lindemann-Weirstraß theorem to derive its conclusion - in my case, it's implicit in the assertion that $\cos 1$ is transcendental.)
Answer: There is no 1 (multiplicative identity) so it is not a ring. x sin(x) is either 0 (when x=0) or is a transcendental number due to Lindemann–Weierstrass theorem when x <> 0
Comment: Depends on your definition of a ring. Rings are not usually required to have an identity though.
Comment: True that is unclear from the question if they mean ring with identity or not. The other answer also assumes there is a 1 in the ring when it say there is an n such that 2 sin 1 = n sin n. Because the 2 here is an element 2 in the ring to multiply 1 sin 1 by. Hence it assumes there is a 1 in the ring to make the element 2 from.
Comment: Now I am curious if you assume that there is not a 1 in the ring if you can still prove the statement :-)
Comment: I think that Steven's answer tackles closure of addition, i.e. whether $1\sin 1 + 1 \sin 1 = 2\sin 1$ is an element of this set or not.
Comment: Aha I had missed that point. Thanks for explaining! So given we are using the 1 from R here in regular way it seems like we must be assuming the ring has identity.
Comment: But the unity element of a subring need not be the same as that of the ambient ring, assuming the said identity exists. I hope I haven't misinterpreted your question.
Comment: Yes you are right. Thanks for clarifying. Now I get that 2 sin(1) is just 1 sin(1) + 1 sin(1) and Steven showed the set is not closed under addition.


Switching Gears from 4/4 to 7/8 and back to 4/4

Question: When I count 4/4 time signatures like the one bellow, I do it like this
1 e and a 2 e and a 3 e and a 4 e and a
My question is, how would I switch gears and count the 7/8 bars?
How do you count 8th notes when they are subdivided in 16nth notes in a bar that you're supposed to count 8ths?
This is purely curiosity question, I can play the sheet bellow just fine but I count it like I would a normal 4/4 measure and just start over where the bar ends.
I would like to know a more efficient/"in the book" way to do so.
The reason for this, is that I'm practicing to be able to sight read and counting like that is my approach, so far it works.
Thank you in advance.
Answer: The 7/8 bars here are written so that they are timed a half beat (quaver) short of the 4/4s. Wanting to start with a 'one' count, you could count 1e&a 2e 3e&a 4e&a, giving you all the semis on a syllable each. The reason I've left out &a of 2 is that the phrasing in this case does just that - it's split the bar into 3 and 4, making 7, thus appearing to miss out &a of 2. Since 3 is an important emphasis in 4/4 and can be counted as an emphasis in 7/8, let's leave that '3' count there.
As Bob says, this will not work for a different phrasing of 7/8 - like 4 and 3.The 'short last beat' trick works better for 4 and 3.
Looking carefully, the 7/8s here are split 3-2-2 rather than 3-4, but the 'missing bit' has still gone from beat 2.
Answer: You'll probably find it easiest to move away from counting every semiquaver (16th) in each bar, and just count quavers (8th). This still helps you count semiquavers, though, as every semiquaver note is either on or off a quaver beat. But, you should feel that your counting and playing both flow better, and feel less rushed, as you are counting half as many subdivisions. Also, you can now simply count 4/4 bars as 8 quavers long and 7/8 bars as 7 quavers long.
After a while you should be able to just "feel" the rhythmic changes between 4/4 and 7/8. I often do this by feeling a 7/8 bar as four beats long, just like a 4/4 bar, but with a short last beat. This does depend upon the grouping of the 7/8 bar though.
Comment: I don't find it easier at all to count quavers. It just gets too complicated to count it right. The bars above just have to do with a time signature change, other bars in the same song are crazy, mixing 16th triplets and 16th with dotted (don't know how to call this in English) 8th notes and put in the weirdest places of the bar. First thing I tried, is what you suggest here. Didn't work at all. The method you suggest could easily work for me in simple pieces of music, I do count it like that then. For this song, it doesn't work for me that way. (Song is not THAT bad, but you get the idea). Ty
Comment: No problem. That's just the way I find it easiest to switch between bars with quarter and eighth subdivisions. A lot of musicians I know that play contemporary classical and jazz use this way to count, too. But the most important thing is to use a system you're comfortable with.
Comment: I understand that, actually I believe that if I keep at this, I'll be able to do it the way you suggest, but since I just started counting instead of playing by memory. It's easier for me as a beginner in this field (counting) to count each and every note. The reasons for this are two: 1. The hope to get the feel of each subdivision of the bar (knowing exactly where I am without thinking about it in the end). 2. The hope that I will reach the level to do what you suggested. But first I have to know how it sounds/feels before I can do it without much effort. Thanks again for your answer.


Nonparametric test to compare link prediction algorithms

Question: I have some experimental data, and I want to use a non-parametric test to verify my results. I am considering link-prediction on complex networks.
I have a complex network $N$ and an algorithm/model $A$ which finds structure in $N$. I then remove some of the edges in $N$, first $10\%$, then $30\%$ up to $90\%$. For each of these states of $N$, I use $A$ to infer the structure, and then compute and AUC-score. I repeat this procedure 3 times, so I get a total of 15 scores.
Now I take a new algorithm $A'$, which is a modification of $A$, and perform the same tests for $A'$. I now have 30 scores, 15 for $A$, and 15 for $A'$.

     10%   30%   50%   70%   90%
A1    x     x     x     x     x
A2    x     x     x     x     x
A3    x     x     x     x     x
A'1   x     x     x     x     x
A'2   x     x     x     x     x
A'3   x     x     x     x     x

Now I want to use a non-parametric test (probably a rank-sum test), to verify that $A$ is better at inferring structure in the networks. How do I go about doing this?
I am using MATLAB for my experiments, so a call to ranksum($x,y$) is the solution to "how to do the  test". What I am looking for here, is the arguments $x,y$, and if there are any things I need to consider about independence?
There seem to be two obvious possibilities for the input:
$$x = [A_1 (10\%), A_2 (10\%), A_3 (10\%), A_1 (30\%), \ldots , A_3 (90\%)]$$
$$y = [A'_1 (10\%), A'_2 (10\%), A'_3 (10\%), A'_1 (30\%), \ldots , A'_3 (90\%)]$$
or
$$x = [A_1 (10\%), A_1 (30\%), \ldots, A_1 (90\%), A_2 (10\%), \ldots, A_3 (90\%)]$$
$$y = [A'_1 (10\%), A'_1 (30\%), \ldots, A'_1 (90\%), A'_2 (10\%), \ldots, A'_3 (90\%)]$$
Are any of these correct, and if only one of them, why?
Answer: It sounds like you're trying to do a calibration study to show the non-superiority of the new test. As you know, inverted hypothesis tests are complex. Since updating A to give you A' takes time and energy, wouldn't you be okay with a rule which says something like, "If A' doesn't provide better discrimination, then maintain A", i.e. a superiority test in which you could look at the AUC and even confidence intervals for it.
It also sounds like you have multiple metrics of model performance though the problem description is not clear. As I understand it, you're predicting various levels of complexity in the network, e.g. 10% means you're looking to correctly predict perhaps 10% of the edges of a network graph... or is it 10% sensitivity?
If you have several different outcomes, you should think carefully about how you would like to weight each outcome based on its importance for desired application. Perhaps you're more interested in the 30% network... or 90% network. Or you could just take a flat average of all the predictive performances (as measured by the AUC).
Comment: As stated in the question, the $10\%$ refers to removing 10 percent of the edges from the network. Making $A$ into $A'$ does not take time and energy, actually $A'$ is just a simplification of $A$.
Comment: Yes, but what you haven't stated is how/why this is performed. Are they removed at random? Or do they represent specific nodes that are lower priority? Or are they part of an isolated network, like a hidden layer in a neural net? How do you interpret the differences in predictive accuracy for each of these models? Is A' then a model which can be considered to be nested in A?
Comment: To answer your questions: They are removed at random. $A'$ can be viewed as a model nested in $A$.

I see your point about the weight of each outcome. I am interested in "proving" that $A$ in general, does not outperform $A'$, and there does not seem to be a most important percentage to consider.
Answer: When looking back, I think what I did not know, was the actual meaning of paired-tests. The ranksum-test in MATLAB is non-paired whereas the ranksign-test is a paired non-parametric test. In the paired test, both of the two possible ways of permuting the data are correct.


Is there any benchmark which compares PHP and JSP?

Question: I don't want to make a holy war. I just want to know if there is such benchmark? Or maybe you can say something about this thread from your experience?
Answer: I just stumbled over the language shootout yesterday, again where you can compare some performance characteristics of both languages while running different programs. I didn't find a benchmark for web performance, though.
Fact is, that interpreted languages like PHP are always slower than a compiled language. JSP files get compiled, too, so once the server is up an running and doesn't get changed anymore, the performance will be better than a PHP script that gets interpreted every time a request comes in.
On the other hand, the first performance bottleneck you will have will probably be the database speed, anyway. And then there are still lots of other ways for improving performance like pre compiling your PHP scripts, externalizing heavy calculations into C etc. And compared to the monster of Java web development PHP is easy to learn and to get along with. In the end, if you have the choice, you should go with the language you are most comfortable with. If you are starting a new project you may not even know if all the performance considerations will ever be important because you don't have the users yet and just want to get your application out there quickly.
Answer: While Daff's explanation of PHP vs JSP is technically wrong, the essential gist of his post is correct: choose the language that is best for you. Only very rarely will you find yourself in a position where performance really matters badly. At that point, you are much more likely to be able to make significant architectural optimizations in your language of choice - and these optimizations are likely to have significantly more effect than the difference between PHP and JSP.
One of the core rules of programming has always been to avoid premature optimization - if for no other reason than because until you're actually under pressure you don't know what you actually need to optimize, nor do you have a means of determining whether it worked.
In the event that you believe there's a possibility you may face performance issues, no website can help you. The most vital thing is to create your own load testing benchmarks that represent the specifics of how your site works, simulating how your users do things. Only once you have done that are you able to move on to tweaking your code, implementing things like caching, load balancing, data and request partitioning etc with any confidence that the changes you are making are having a positive impact on your site performance.
There are books specifically about the process of optimization in general, but the key sequence is this:

Benchmark
Change test
Benchmark to see if change indicates performance improvement
Go live
Evaluate live response to see if benchmark prediction was correct

(People forget #5 a lot and cause themselves grief)
If you're going to spend time worrying about performance, spend time setting up that sequence, don't spend time worrying about your language choice.
Comment: I have no problem to set the explanation right. But you just stating that it is wrong without saying why doesn't help very much with that...
Comment: I believe that your generalization of "avoid premature optimization" to "avoid optimization until customer complains" is incorrect.  You should always choose the *best*_algorithm_ for the purpose and then use it in the simplest way possible while still being correct.  Then occasionally bottlenecks occur in unexplected places, but then you rarely have to rip out the guts and replace it with something new, but merely find the bottleneck and give it special attention (in form of something more complex but still correct).


Gambler tosses coin PGF

Question: A gambler tosses a coin repeatedly until it comes up tails. He gets £1 for each head that comes up before that happens, and pays back £1 for the tail. Find the probability generating function for his winnings and show that it can be written in the form $\frac {1}{t(2-t)}$. By differentiating this function, show that it is a fair game, find the variance, and determine whether the distribution is positively or negatively skewed.
I have $G(t)=(1/2)t+(1/2t)$ but I can't get it in the form shown above. I have proven that it is a fair game by showing G'(1)=0 and found the variance = 2. How can I show whether it is positively or negatively skewed?
Comment: How did you arrive at this expression for G?
Comment: @Did $(1/2)t^1+(1/2)t^{-1}$
Comment: Quite unrelated.
Comment: @Did How then should I do it?
Comment: You should first determine all the possible winnings, then compute the probability of each.
Comment: @Did Are all possible winnings £1, £0 and £-1?
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/7386/discussion-between-user52187-and-did)
Comment: Read again: the possible winnings are -1, 0, +1, +2, +3, +4, +5, +6, ...
Comment: @Did if this goes on forever then $G(t)=(1/2)t^{-1}+(1/4)+(1/2)t+(1/4)t^2+(1/8)t^3...=(1/2t)+(1/4)+(t/2)(1/1-(t/2))$
Answer: If the first tail appears after $n\geqslant0$ heads, the gambler's fortune $X$ is $n-1$. This happens with probability $2^{-n-1}$, hence
$$
G(t)=\mathbb E(t^X)=\sum_{n\geqslant0}t^{n-1}2^{-n-1}\stackrel{[s=t/2]}{=}\frac1{2t}\sum_{n\geqslant0}s^n=\frac1{2t}\frac1{1-s}=\frac1{t(2-t)}.
$$
To compute the successive derivatives of $G$, one might want to rewrite it as
$$
G(t)=\frac1{2t}+\frac1{2(2-t)},
$$
which yields, for example,
$$
G'(t)=-\frac1{2t^2}+\frac1{2(2-t)^2},
$$
hence,
$$
\mathbb E(X)=G'(1)=0.
$$
The computations of the variance and the skewness are similar.
Comment: Is it true that the skewness is given by the third central moment? If so how do I calculate that from the PGF?
Comment: Wait, you are asking a question involving the skewness of a random variable and you do not know the definition?
Comment: I know the definition but I don't know how to calculate it. I suggested the third central moment because that is one of the ways that you can do it, but I don't think that is the best way.

Gambler tosses coin PGF


IBM Worklight 6.1 - How to add custom written native code from Eclipse to Xcode?

Question: We created a hybrid application on Iphone 5s.  The worklight server version is 6.1, Xcode version is 5.0.2.  We noticed that after we deleted our native folder under Iphone, our self-written native codes were gone.  Therefore, we need to manually add these native codes to Xcode when we build a Xcode project from Eclipse.  I am just wondering if there is a more convenient way to do it?
Thank you very much.
Answer: If you delete the native folder, then any user-files you've placed in it will be deleted as well. When building the application again after deleting the native folder Worklight can only re-generate the Worklight-files, not user-files...
Your files are your responsibility.
Thoughts:

You can place the class files (the .m and .h files) in the iphone\nativeResoures\Classes folder (create this Classes folder). Now upon every build in Worklight Studio the class files will be copied  from the iphone\nativeResources\Classes folder to the iphone\native\Classes folder. So this is a sort of a back-up in case you delete the native folder.
But note! Copying via nativeResources or manually placing the class files in the iphone\native\Classes folder in Eclipse, is not enough. Eclipse does not know how to reference your class files in the Xcode project. This is something you must do in Xcode so that they will be referenced in the project's .pbxproj file.
Eclipse cannot do this for you and I would not recommend on doing this referencing manually.
This is also explained in the "Adding native functionality to hybrid application with Apache Cordova plugin" training module provided in the IBM Worklight Getting Started training materials.
If you develop in Mac, then you can open the .xcodeproj file (located in the native folder) from the Eclipse workspace after you build the project; this means that any changes you will do in Xcode will be part of your project in Eclipse (because you are working on the same files)... So this too is a way to ease on development.
But be careful if you do this while also using the nativeResources approach, because then you will lose your changes in Xcode upon build in Eclipse.

You can use both of these approaches if you act carefully. Always backup your class files to the nativeResources folder before building in Eclipse after changing the .m or .h files in Xcode.
You are working with 2 IDEs, so you need to juggle...


Como tirar o fundo num select option?

Question: Tenho um select option com vários países eu criei o CSS para tirar o estilo padrão dele nos navegadores.
Estou com dois problemas, um preciso tirar aquele fundo azul quando passo por cima de cada opção preciso que fique só o texto e que sim ao mudar de opção mude a cor do texto só.

O segundo problema e o overflow no google chrome não me aparece que e como eu pretendo, mas no firefox continua aparecer.

.select_pt {
  width: 200px;
  overflow-x: hidden;
  overflow-y: hidden;
  overflow: hidden;
  border-top: 1px solid gray;
  border-bottom: 1px solid gray;
  border-left: none;
  border-right: none;
  margin-top: 7px;
  text-align: center;
  border: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: none;
}

.select_pt option {
  text-align: center;
  color: black;
  font-weight: bold;
}

.select_pt option:checked {
  font-weight: bold;
  font-size: 13px;
  color: blue;
}

.select_pt option:not(:checked) {
  color: gray;
}
<select id="select_pt" class="select_pt" size="4">
    <option value="alemanha">Alemanha</option>
    <option value="austria">Áustria</option>
    <option value="belgica">Bélgica</option>
    <option value="bulgaria">Bulgária</option>
    <option value="chipre">Chipre</option>
    <option value="croacia">Croácia</option>
    <option value="dinamarca">Dinamarca</option>
    <option value="eslovaquia">Eslováquia</option>
    <option value="eslovenia">Eslovénia</option>
    <option value="espanha">Espanha</option>
    <option value="estonia">Estónia</option>
    <option value="finlandia">Finlândia</option>
    <option value="franca">França</option>
    <option value="grecia">Grécia</option>
    <option value="holanda">Holanda</option>
    <option value="hungria">Hungria</option>
    <option value="irlanda">Irlanda</option>
    <option value="italia">Itália</option>
    <option value="letonia">Letónia</option>
    <option value="lituania">Lituânia</option>
    <option value="luxemburgo">Luxemburgo</option>
    <option value="malta">Malta</option>
    <option value="polonia">Polónia</option>
    <option value="portugal" selected >Portugal</option>
    <option value="reino_unido">Reino Unido</option>
    <option value="republica_checa">Republica Checa</option>
    <option value="romenia">Roménia</option>
    <option value="suecia">Suecia</option>
</select>
Comment: Mais porque você está usando as propriedades?

overflow-x :hidden;
overflow-y: hidden;
overflow: hidden;

Retire elas que o chrome vai criar o scroll automaticamente.
Answer: Relativamente a alterar o fundo do select quando navega as opções, não é possível fazê-lo.
No entanto, pode usar bibliotecas como o select2 ou o selectize para estilizar o select como desejar.
Segue um exemplo usando select2:

jQuery(document).ready(function($){
    $('select').select2({width:100});
});
.select2-results__options > li {
  background-color: transparent !important;
  color: black !important;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet"/>
<select>
    <option value="alemanha">Alemanha</option>
    <option value="austria">Áustria</option>
    <option value="belgica">Bélgica</option>
    <option value="bulgaria">Bulgária</option>
    <option value="chipre">Chipre</option>
    <option value="croacia">Croácia</option>
    <option value="dinamarca">Dinamarca</option>
    <option value="eslovaquia">Eslováquia</option>
    <option value="eslovenia">Eslovénia</option>
    <option value="espanha">Espanha</option>
    <option value="estonia">Estónia</option>
    <option value="finlandia">Finlândia</option>
    <option value="franca">França</option>
    <option value="grecia">Grécia</option>
    <option value="holanda">Holanda</option>
    <option value="hungria">Hungria</option>
    <option value="irlanda">Irlanda</option>
    <option value="italia">Itália</option>
    <option value="letonia">Letónia</option>
    <option value="lituania">Lituânia</option>
    <option value="luxemburgo">Luxemburgo</option>
    <option value="malta">Malta</option>
    <option value="polonia">Polónia</option>
    <option value="portugal" selected >Portugal</option>
    <option value="reino_unido">Reino Unido</option>
    <option value="republica_checa">Republica Checa</option>
    <option value="romenia">Roménia</option>
    <option value="suecia">Suecia</option>
</select>
Answer: Não sei se é isso que queres porém creio que a parte de alterar apenas a cor do texto quando o mouse passa por cima acho que funcionaria com o Hover.
.select_pt:hover {
    background:#ffffff;
    color:#000000;
}

Porém a parte do Overflow não sei informar ao certo o que pode ser.
Edição
.select_pt option:checked {
    font-weight: bold;
    font-size: 13px;
    background:#ffffff;
}

Comment: O meu prolema de aparecer esse fundo nao e ao passar o mouse por cima mas sim quando clico numa opção fica esse fundo ou entao ao mudar as opções pelas setas do teclado aparece sempre esse fundo
Comment: @CésarSousa entendi errado desculpe, creio que então na parte onde esta o `checked` deves trocar o backgroud pela cor que deseja, irei atualizar a resposta para mostrar
Comment: fiz isso mas mantem sempre o azul nao muda para branco eu quero que fique sem nehnhum fundo que passe as opcoes mas que mostro so o texto
Comment: @CésarSousa Supostamente do jeito que mostrei ele mostraria um fundo branco porém não entendo o porque não funcionou, farei uns testes e verei
Comment: isto e estranho porque se eu tirar do select o size="5" ele ja fica sem fundo porem so mostra uma opcao assim e eu quero que mostre varias como tem na imagem
Comment: @CésarSousa cara eu testei aqui e não tem lógica o porque fica marcado de azul mesmo tirando todas as opções de "azul" do código
Comment:  se eu tirar esse size="4" fica sem fundo com ele tem fundo tambem nao vejo logica mas e o que acontece
Comment: mas haver se percebes-te o fundo so aparece mesmo quando escolha a opção a select em si nao tem fundo isso eu consegui aparece e um fundo no texto da opção quando a escolho
Comment: Ao retirar o `size="4"` a opção que dei funciona quando uma option é **Selecionada** ela fica com o fundo branco porem preciso verificar ao mudar com as setas do mouse @CésarSousa
Comment: Vou testar isso não testei ao tirar o size 4 mas se tirar esse size só mostra uma opção e eu quero que mostre mais que uma opção como na imagem a ideia do size e essa percebe
Comment: @CésarSousa Chegou a testar?
Comment: sim ja testei quando selecionada uma opção aparece so o texto da opção sem fundo sem nada mas tambem so aparece uma opção
Comment: Certo então é tipo isso que quer né? só que com 4 linhas e quando passa o mouse e move com as teclas tbm não apareca nada no background @CésarSousa ?
Comment: certo isso mesmo como esta na imagem mas sem aquele fundo que tirando o size faz isso mas so fica com uma opção a mostra e eu preciso como esta na imagem
Comment: @CésarSousa Agora ja não sei mais o que fazer pois até com o hover não funcionou
Comment: Não sei porque o size faz isso

Como tirar o fundo num select option?


Unable to read xml hierarchy using python

Question: I am trying to read xml file using python. My xml file look like this:
<item_details>
    <item id="0001" type="donut">
        <name>Bicuit</name>
        <ppu>0.55</ppu>
        <batters>
            <batter id="1002"><name>Chocolate</name></batter>
            <batter id="1003"><name>Blueberry</name></batter>
        </batters>
        <toppings>
            <topping id="5002">Glazed</topping>
            <topping id="5005">Sugar</topping>
            <topping id="5006">Sprinkles</topping>
        </toppings>
    </item>
</item_details>

I am using the following python code to read this:
from xml.etree import ElementTree
nestedtree = ElementTree.parse(nestedxml)
nestedroot = nestedtree.getroot()

for item in nestedroot.findall('item'):
    itid = item.get('id')
    ittype = item.get('type')
    itname = item.find('name').text
    itppu = item.find('ppu').text
    for batter in item.find('batters'):
        baid = batter.get('id')
        battername = batter.find('name').text
        for topping in item.find('toppings'):
            toppingid = topping.get('id')
            tname = topping.find('topping')
            print(itid, ittype, itname, baid, battername,toppingid, tname)

However I am not able to read the topping details. I am getting only the below output with topping name as "none":
0001 donut Bicuit 1002 Chocolate 5002 None
0001 donut Bicuit 1002 Chocolate 5005 None
0001 donut Bicuit 1002 Chocolate 5006 None
0001 donut Bicuit 1003 Blueberry 5002 None
0001 donut Bicuit 1003 Blueberry 5005 None
0001 donut Bicuit 1003 Blueberry 5006 None

Need suggestion, how to read the below xml format:
<topping id="5002">Glazed</topping>

Thanks in advance..
Comment: Did you try  tname =  topping.txt instead of tname = topping.find('topping')?
Comment: thanks mate, its worked :-)
Answer: Another solution, for reference only.
from simplified_scrapy import SimplifiedDoc,req,utils
html = '''
<item_details>
    <item id="0001" type="donut">
        <name>Bicuit</name>
        <ppu>0.55</ppu>
        <batters>
            <batter id="1002"><name>Chocolate</name></batter>
            <batter id="1003"><name>Blueberry</name></batter>
        </batters>
        <toppings>
            <topping id="5002">Glazed</topping>
            <topping id="5005">Sugar</topping>
            <topping id="5006">Sprinkles</topping>
        </toppings>
    </item>
</item_details>
'''
doc = SimplifiedDoc(html)
for item in doc.selects('item'):
  itid,ittype,itname,itppu = item.id,item.type,item.name.text,item.ppu.text
  for id in item.selects('batter|topping'):
    print(itid,ittype,itname,itppu,id.id,id.text)

Result:
0001 donut Bicuit 0.55 1002 Chocolate
0001 donut Bicuit 0.55 1003 Blueberry
0001 donut Bicuit 0.55 5002 Glazed
0001 donut Bicuit 0.55 5005 Sugar
0001 donut Bicuit 0.55 5006 Sprinkles


Why did I get $\frac {1\pm1}0$ in the equation of characteristics of $u_{xy}+u_x+u_y=3x$?

Question:
Consider the partial differential equation $u_{xy}+u_x+u_y=3x$. Obtain the equation of its characteristics and reduce to the canonical form.

Attempt
The equation of its characteristics is given by $\frac{dy}{dx}=\frac{B\pm\sqrt{B^2-4AC}}{2A}$
For this particular case, $=0=$ (which are the coefficients of $_{}$ and $_{}$ respectively) and $=1$ (coefficient of $_{}$) so
the equation of its characteristics yields to $\frac{dy}{dx}=\frac{B\pm\sqrt{B^2-4AC}}{2A}=\frac{1\pm1}{0}$
What can I do here? This was not expected.. I can't go further, the next step was integrate respect to $y$.
Any kind of help is greatly appreciated.
Comment: I cannot understand your attempt.
Comment: @JJacquelin My professor told us that computing $\frac{dy}{dx}=\frac{B\pm\sqrt{B^2-4AC}}{2A}$ give us the equations of its characteristics. For this particular case, $ A=0=C$ (which are the coefficients of $u_{xx}$ and $u_{yy}$ respectively) and $B=1$ (coefficient of $u_{xy}$),
Answer: $$u_{xy}+u_x+u_y=3x$$
Let $\quad u(x,y)=\frac32 x^2+v(x,y)\quad$ which leads to :
$$v_{xy}+v_x+v_y=0$$
Search for particular solutions on the form $u=X(x)Y(y)$
$X'Y'+X'Y+XY'=0\quad;\quad\frac{X'}{X}=-\frac{Y'}{Y+Y'}=\lambda \qquad\begin{cases}
X=e^{\lambda x} \\
Y=e^{-\frac{\lambda}{1+\lambda}y}\end{cases}$
Particular solutions : $\quad v_\lambda(x,y)=e^{\lambda x-\frac{\lambda}{1+\lambda}y}$
The general solution is any linear combination of the particular solutions.
General solution expressed on the form of integral :
$$v(x,y)=\int f(\lambda)e^{\lambda x-\frac{\lambda}{1+\lambda}y}d\lambda$$
$f(\lambda)$ is an arbitrary function, in so far the integral be convergent.
$$u(x,y)=\frac32 x^2+\int f(\lambda)e^{\lambda x-\frac{\lambda}{1+\lambda}y}d\lambda$$
Or, equivalently :
$$u(x,y)=\frac32 x^2+\int g(\mu)e^{-\frac{\mu}{1+\mu}x+\mu y}d\mu$$
The function $f(\lambda)$ , or $g(\mu)$ , as well as the bounds of the integral, have to be determined according to the boundary conditions. This generally draw to solve an integral equation. Without well defined boundary conditions no further calculus is possible, even not to say if it is possible to analytically solve it and if there is a closed form for the solution.
Comment: JJaquelin I appreciate your answer but I was asking for the equation of its characteristics and then to reduce to the canonical form.


Convergence of finite difference scheme for PDE $u_t+au_{xxx}=f$

Question: From J.C. Strikwerda's book Finite Difference Schemes and Partial Differential Equations (SIAM), p. 57:

2.2.5. Show that the scheme $$
\frac{v_m^{n+1} - v_m^n}{k} + a\frac{v_{m+2}^{n}- 3 v_{m+1}^{n} + 3 v_m^n - v_{m-1}^{n}}{h^3} = f_m^n
$$
is consistent with the equation
$$ \left[ u_t+au_{xxx}=f \right] \tag{2.2.15}$$
and, if $\nu = kh^{-3}$ is constant, then it is stable when $0\leq a\nu \leq 1/4$.

Actually, I know how to solve this problem when $f=0$, consistency condition ($Pu-p_{k,h} u$ converges to zero as $k,h$ tend zero).

How can I deal with $f(t_n, x_m)$ in this case?! I think we need grid function instead of $f(t_n, x_m)$. can I suppose $f(t_n, x_m) =g^n \exp( imhs)$?
How to solve the stability part by using von Neumann analysis? Could you help me? Thank you in advance.
Comment: How can I deal with f(tn, xm) in this case?!  I think we need  grid function instead of f(tn, xm). can I suppose f(tn, xm) =g^n exp( imhs).?!!
Answer: For the consistency part, expand $v_m^{n+1}$ and $v_{m+M}^{n}$ as Taylor series about $v_{m}^{n} \simeq u(mh,nk)$
to be inserted in the scheme. As discussed in Definition 1.4.2 of the book by Strikwerda, the source $f$ does not matter in the definition of consistency. Thus,
$$
\frac{v_{m}^{n+1} - v_{m}^{n}}{k} \simeq (u_t)_m^n + O(h,k)
$$
$$
\frac{v_{m+2}^{n} - 3 v_{m+1}^{n} + 3 v_{m}^{n} - v_{m-1}^{n}}{h^3} \simeq (u_{xxx})_m^n + O(h,k)
$$
proves that the scheme is consistent.
As usual, the Von Neumann analysis consists in a Fourier transformation of the scheme (see Sec. 2.2 of the book by Strikwerda), and the source $f$ can be ignored. Under the periodicity assumption, we have $$
v_m^{n} = \frac{1}{\sqrt{2\pi}}\int_{-\pi/h}^{\pi/h} \text{e}^{\text{i}mh\xi}\, \hat{v}^n(\xi) \, d\xi
$$
to be injected in the scheme. This step defines the amplification factor $g(\theta)$ to be determined, which is defined in such a way that $\hat{v}^{n+1}(\xi) = g(h\xi) \, \hat{v}^{n}(\xi).$ Neumann stability imposes $|g(\theta)| \leq 1$.
Comment: Thank you so much


Mixed Effects, Doctors & Operations: predicting on new data containing previously unobserved levels, and updating our confidence accordingly

Question: Here's a quick sketch of a hypothetical situation. There are Doctors $\{1, \ldots, J\}$  who perform different types of operations $\{1, \ldots, K\}$.  Our response variable is whether the operation was a success ($Y_{i,j,k} = 1$ implying that for the $i$th patient for doctor $j$ for which he performed operation $k$ was a success).
Doctors have some inherent level of skill $\alpha_j$, and operations have some inherent level of difficulty $\beta_k$. We might think that there are some fixed known number of operations, but that Doctor skill is normally distributed, drawn from a population of doctors. So we assume that Doctor skill is distributed as $\alpha_j \sim N(0, \sigma_\alpha^2)$.
A crude model might look something like the following, where the Logit of the probability of success is a sum of some base intercept, the skill of the doctor, and the difficulty of the operation.
$$
\text{Logit}(\text{Pr}(Y_{i,j,k} = 1)) = \mu_0 + \alpha_j + \beta_k.
$$
This naive model seems to be a straightforward mixed effects model. Doctors are levels we observe from some larger population, and their skills are random intercepts. The Operations can be categorical fixed effects (determining difficulty). In reality we would certainly expect there to be an interaction between Doctor and Operation (they specialize!), but I'll ignore that for now as I'm just trying to understand a theoretical example.
Here's the crux of the issue. I want an approximate model (this need not be perfectly rigorous) which can look at a new batch of data and guess "About how many failed operations do we expect?". This is some function of the skill of the doctors involved, how many operations they do, and what those operations are. However, in practice, my new batch of data will contain a mix of doctors which I know a great deal about, as well as new recruits fresh out of med school! (Who lack previous data to indicate their skill).
Does a mixed effects model still work in this case? Basically, I want a model which defaults to some sort of baseline assumption of skill when we haven't observed this doctor in practice, and then updates it as we observe more (until we are very confident if we have a large sample for them). This is clearly a Bayesian framework: we have some prior belief about their skill, and we update it to reflect new information.
As a concrete example, our new data contains operations from Doctors A, B, and C. Doctor A is a veteran who has performed 5,000 operations, and we can confidently estimate that they are much more skilled than average as they rarely fail. Doctor B just moved from a different hospital, so we assume they are exactly as skilled as the average doctor. Doctor C has performed 100 operations with a higher failure rate than usual, so we think they are less skilled but recognize that it's a small sample so we hedge our bets a bit. Again, this is an obviously bayesian set-up, but I'm not sure if it can be accomplished using a mixed effects model, or how to actually build a reasonable bayesian model to reflect this.
So, in total,

Can a mixed effects model work here? (That is, update its confidence on doctor skill based on how much past data we've seen for this specific random intercept).
Should I instead move to a more directly Bayesian framework? (I'm sure the mixed effects model has a Bayesian interpretation, but again I'm not sure if it specifically does what I need here).
Do you have any ideas for models which might do what I need here? This is meant to be a rough benchmark, not an elite predictive model, so simple and intuitive is fine even if it doesn't exactly fit the scenario (the Doctors and Operations is just an example anyways).

Thank you all for any advice you can provide!
Comment: The model you gave out is a fixed effect model.
Comment: My apologies, I wrote it out wrong. It should not reflect a very straightforward mixed model (Doctor skill drawn from a normal distribution, Operation difficult is a fixed categorical variable).
Comment: A side note: if you believe that *experience* is likely to be a good predictor (as in your example), it would be worth including that as a covariate in your model as well.
Answer: What you describe is the concept of dynamic predictions from mixed models.
Initially, when you have no information for a doctor you only use the fixed effects in the prediction, i.e., you put his/her ability level equal to the average ($\alpha_j = 0$).
But, as extra information is recorded you can update your predictions by calculating the random effect of the doctor. You get this from the posterior/conditional distribution of the random effects $\alpha_j$ given the observed data $y_j$.
You can find more information on these predictions in the Dynamic Predictions vignette of the GLMMadaptive package.
Comment: As you noted in a comment to my answer the procedure you suggest involves approximating the posterior distribution, I think it would be useful to describe that here, as (my guess) not all mixed modelling packages would treat $\alpha_j = 0$ as uncertain.
Comment: Thanks for the response, I've started reading through the Dynamic Predictions vignette, and it seems up my alley.

However, thinking about it further, I'm a bit confused about the original premise. Doesn't a mixed effect model already update its "confidence" in the estimation of the random effect based on the observed sample size?

So do you have any advice for intuiting the difference between Dynamic Predictions and regular GLMM? Is it just the method of computation, which updates iteratively with new element of data? Or is there some fundamental assumption that separates them?
Comment: Indeed the algorithm/procedure is the same. The concept of *dynamic* predictions is that the Bayesian algorithm/procedure is iteratively applied with newly recorded data.
Answer: I think a Bayesian approach might be beneficial. When predicting for an unobserved category in a Bayesian mixed model, you generate posterior predictions by sampling the $\alpha_j$ from the fitted $N(0, \sigma^2_\alpha)$ (aside from sampling the fixed effects from the fitted posterior). This way, you will see high uncertainty for the new doctor - which is IMHO a good thing. The amount of uncertainty will be related to the fitted $\sigma^2_\alpha$, so when most doctors are similar, you will get lower uncertainty. After you have more data, you would refit the model and the uncertainty for the (now observed) doctor will gradually shrink.
Comment: That answer is spot on, and Richard McElreath presents an extremely intuitive Bayesian solution in his book _Statistical Rethinking_.
Comment: Actually the procedure behind my answer is Bayesian in nature, and account for the uncertainty you mention. The only difference from a pure Bayesian approach is that the posterior of the model parameters (excluding the random effects) is approximated by a multivariate normal distribution.
Comment: @DimitrisRizopoulos Sorry, I didn't follow the link. Probably better to not make any statements about other's answers without deeply understanding them :-) I have removed the reference.


Diferença entre recv e read, send e write

Question: Estou transmitindo e recolhendo dados a partir de uma conexão utilizando Sockets, para enviar os dados para o servidos, pode-se usar os comandos send e write, e para receber os dados recv e read.

Existe diferença nesses comandos?
Qual a vantagem/desvantagem pode ter em usar send ou write para enviar algum dado?
Qual a vantagem/desvantagem pode ter em usar recv ou read para receber algum dado?
Answer: Send
Tanto clientes como servidores utilizam a função send para transmitir dados. Tipicamente, um cliente envia uma requisição e o servidor envia uma resposta.
Recv
Tanto clientes como servidores utilizam a função recv para obter dados que foram enviados pelo outro.
Read e Write
Em alguns sistemas operacionais, como o Linux, as funções read e write podem ser utilizadas em vez de recv e send.
Vantagem do Read e Write
A grande vantagem de utilizar read e write é a generalização - uma aplicação pode ser criada com o objetivo de transferir dados para ou a a partir de um descritor sem saber se o mesmo corresponde a um arquivo ou um socket. Dessa forma, um programador pode utlizar um arquivo no disco local para testar um cliente ou um servidor antes de tentar se comunicar através da rede.
Desvantagem  do Read e Write
O programa perde a portabilidade quando é compilado em outro sistema operacional.
Fonte 01 : Rede de computadores e Internet - 6 ed. Douglas E. Comer
Fonte 02 : https://stackoverflow.com/a/1790775/2588695
Comment: Ainda o uso de read/write em substituição a send/recv implica na não utilização das flags permitidas pelas funções send e recv (é equivalente a passar 0 no lugar deste parâmetro nas funções que o possuem).
Comment: esqueci de colocar essa parte srsrsrs


Reliable methods to validate clustering of text phrases?

Question: Question is in the title. I have clustered the word embeddings of text phrases, and now want to try and check whether the resulting clusters are coherent enough. I have tried methods that are standardly used for cluster validation such as SSE, silhouette scores and Dunn index but none have proven effective in this case. Any other suggestions? Would be grateful for a detailed response or a link to any other methods which may work.
Comment: Please clarify why you consider the standard methods are ineffective - e.g. are you looking for a measure they don't provide? Or do the results not seem reasonable?
Comment: @Lynn Hey, sorry, I should have clarified, the results do not match with what I'd expect. A lot of the clusters deemed coherent by these seem incoherent upon my own manual revision, and vice versa.
Answer: You say you want to know whether the embedding is "coherent enough". It is not very clear what you mean by that, but I presume your question is somehow: How do I measure the quality of my embedding?
And that depends on what you want to do. The clustering property of the embedding might not have anything to do with the task you want to solve. So, find a metric that evaluates your overall task, and then tune your embedding according to this metric.
Comment: Thanks for the response, yes, I want to measure the quality of my clustering, specifically to check whether each individual cluster of phrases makes sense or not (i.e, each cluster has a common "theme", say one cluster talks about dogs, and another about cats, and another about both, ideally with no overlap). The metrics I have tried so far do not yield results which I think are satisfactory. I am looking for other metrics I may have missed, and would be grateful if you could suggest a few.
Comment: @aj2k1132 My main point is that I don't think that metrics for clustering are appropriate here because the isolation of clusters, which is what is mainly measured by those cluster validation metrics, should not be the priority for word embeddings, but that is, of course, just a hunch.


Distinguish two distribution using chi-square test

Question: I have two dice, each with four faces.
For first one, each of the numbers 1,2,3,4 occur
with 0.25 probability.
For the other, the faces have probabilities 0.4,0.3,0.28,0.02 respectively.
I take one die randomly and throw it 100 times. Now I want
to know is it 1 die or die 2.
We can use Chi-square test to find this.
Let outcomes are $n_1,n_2,n_3$ and $n_4$ respectively.
Then I calculate $\chi^2=\frac{(n_1-25)^2}{25}+\frac{(n_2-25)^2}{25}+\frac{(n_3-25)^2}{25}+\frac{(n_4-25)^2}{25}$. If $\chi^2$ is less than
some bound, it is from unbiased dice. Otherwise it is from biased dice.
So in hypothesis testing
  1. H_0: Dice is unbiased
  2. H_1: Dice is biased

Is there any other test, which is better than this test? How to find type 1 and type 2 error?  Instead of 100, if we increase  number of throws we can
bound both type 1 & type 2 error. How many throws are required so that both errors are less than 0.01?
Comment: Adopting one of the dice as a null hypothesis is artificial and asymmetric.  Instead, use the multinomial likelihood ratio to decide which die is being cast.
Comment: Your question is unclear. How do you propose to use a chi-square test? There doesn't appear to be an identified *null* here, just two competing options -- as far as I can see, it's not a hypothesis testing situation at all, but something nearer to an estimation / classification / decision problem. Can you explain the circumstances? How does this question arise? .... I believe there's an excellent way to decide between them (which at n=100 will almost never go astray) but first the question needs to be more clearly formulated. Are you certain this needs to be done as a hypothesis test?
Comment: 1. You're now using the terms "biased dice" and "unbiased dice", which does at least hint at privileging one of the options but you haven't clearly identified the underlying problem you're trying to solve (in a way that would make it more clearly a testing problem rather than a classification problem). 2. Please identify the source of the problem. Is this an exercise for some class?
Comment: You can't use chi-square to solve this problem, at least, not in the way that you did. Your method includes no information about the non-uniform distribution. If you ran the same chi-square against that distribution, you might easily reject both nulls (or fail to reject both nulls).
Comment: @user12290 That is indeed the "excellent way to decide between them" I had in mind in my earlier comment.
Answer: As whuber, Peter Flom and I all said (in different ways) in comments, a choice between two such options in the hypothesized circumstance isn't a standard hypothesis testing situation and that's not the best way to choose between them (though we can make use of the statistic -- see the note at the end).
The thing whuber was actually referring to (and which I alluded to previously as being an excellent way to decide between them) is as follows:

Compute the likelihood ratio for the two options. It doesn't matter which one goes on the numerator, that just flips the direction of a decision rule.
For a given set of observed counts in each category $(x_1,x_2,x_3,x_4)$, the likelihood for the biased die is proportional to $(0.4)^{x_1}\cdot(0.3)^{x_2}\cdot(0.28)^{x_3}\cdot(0.02)^{x_4}$ and for the unbiased die it is proportional to
$(0.25)^{x_1}\cdot(0.25)^{x_2}\cdot(0.25)^{x_3}\cdot(0.25)^{x_4}$ (with the same constant of proportionality). The ratio is thereby
$(1.6)^{x_1}\cdot(1.2)^{x_2}\cdot(1.12)^{x_3}\cdot(0.08)^{x_4}$
and the log of the likelihood ratio is
$d=\log(1.6)\cdot x_1 + \log(1.2) \cdot x_2 + \log(1.12) \cdot x_3 + \log(0.08)\cdot x_4$
This will be positive when the unfair die has the higher likelihood and negative when the fair die has the higher likelihood. We can just adopt the naive decision rule of assigning a set of outcomes to the die with the higher likelihood. This is the same as saying "when $d$ is negative, decide in favor of the fair die; if it's positive decide in favor of the unfair die".
(More generally we might want to shift the threshold a little way along from 0 to minimize the total cost - however at the large sample size we're looking at, the rate of the two kinds of errors are very similar, so if the costs of the two errors are the same we should be approximately at the optimum already.)

Let's look at its performance by sampling in exactly the fashion described in the question (choose a die at random, roll it 100 times) and then compute this log of the likelihood ratio criterion on the outcome; we can repeat that 1000 times.

As we see in the output there are two clusters of results, the orange ones in the left cluster, which are all the times a fair die was selected to generate the data, and the blue ones in the right cluster, which are all the times an unfair die was selected. At n=100, we don't see a single misclassified case. Indeed, if we do a million trials instead of 1000, we get only 33 misclassified cases:
table(data.frame(die=dres[1,],scoreneg=dres[2,]<0))
   scoreneg
die  FALSE   TRUE
  1     16 500339
  2 499628     17

Can we do something similar using a chi-square statistic?
Well, indeed, if we compute chi-squared statistics for each die (as if it were the null) and assign the outcome to the die which has the lower chi-squared statistic, we get quite good performance, though the misclassification rate is several times higher. On the other hand, we can improve it by moving the threshold a little (choosing the fair die only when the difference in the two chi-squareds $\chi^2_u-\chi^2_f$ is somewhat more negative).
As the sample size increases from 100, the performance of the two approaches (difference of log-likelihoods vs difference of chi-squared statistics) should become more and more similar.

Since someone nearly always asks, here's the R code I used to generate the histogram/rugplot above. I have not tried to make it pretty, nor
understandable, it's simply what I used.
p1=rep(1,4)/4
p2=c(0.4,0.3,0.28,0.02)
pr=p2/p1
w=log(pr)
p=cbind(p1,p2)
dres=replicate(1000,{ch=sample(2,1);pr=p[,ch];
       t=table(factor(sample(4,100,replace=TRUE,p=pr),levels=1:4));
       c(ch,sum(w*t))})
hist(dres[2,],n=50, main="histogram of log-likelihood ratio")
t2=c(40,30,28,2)
t1=c(25,25,25,25)
abline(v=sum(w*t1),col=2)
abline(v=sum(w*t2),col=4)
abline(v=0,col=3)
rug(dres[2,dres[1,]==1],col="orange",pch="|")
rug(dres[2,dres[1,]==2],col="blue",pch="|")
abline(v=0,col=3)

Comment: Thank you so much. Can we find the distribution of d? Actually I want to find number of trials so that  Type 1 error < 10^{-3} and Type 2 error < 2^{-30}.
Comment: I was not writing about a hypothesis test in my answer, because (as the problem is set up) a hypothesis test is the wrong tool. My answer *opens* with a discussion of that. If you're not doing a hypothesis test, you don't have type I and type II error; The way this is set up, you have misclassification probabilities. If you really do want it to work as a hypothesis test (*why*??), your problem setup needs to change (for example, your explicit specification of choosing between the two dice with equal probability is problematic)
Answer: Following @whuber's Comment: With the fair die, the distribution of the chi-squared statistic is approximately $\mathsf{Chisq}(\nu = 3).$ [Blue in figure.]
With the unfair die the
chi-squared statistic is approximately noncentral chi-squared with
$\nu = 3$ and noncentrality parameter as shown in the last section here. [Red in figure.]
For 100 rolls, the two distributions are sufficiently
different to provide a good chance of accurate discrimination.
Comment: Thanks a lot. But how to find the number of throws to bound the errors?
Comment: The noncentrality parameter is a multiple of the number of rolls. 100 seems pretty good. Somewhere between 11 and 12 may be a good critical value: in R, `qchisq(.99, 3)` returns 11.34487, and `pchisq(11.34, 3, 31.52)` returns 0.006632655.
.
Comment: Thank yo so much. I get the idea now. Is it the best way to distinguish the two events?


Singularity of a function $ f(z) $

Question: Which type of singularity the function
               $ f(z)= \frac{e^z}{z(1- e^{-z})} $ at $ z=0 $
I Know, we find the singularity of a function by expanding the given function by using Laurent series expansion.
I tried like this.  $ f(z)= \frac{e^z}{z(1- e^{-z})} $
                    $ f(z)= \frac{1}{z}{e^z}{(1- e^{-z})^{-1}} $
$ f(z)= \frac{1}{z}({e^z+1+e^{-z}+e^{-2z}+\dots)} $
from this i concluded that
 this function has essential singularity at $z=0$.
Is my conclusion correct??
Please help me. thank you.
Comment: $z=0$ is a zero both for $z$ and for $1-e^{-z}$, while the numerator is never zero. Hence it is a pole of order $2$.
Comment: $e^{-z}$ has infinite terms, how pole of order 2? can you explain.... @FedericaMaggioni
Answer: Hints:
 1. Function $f(z)$ can be rewritten as
$$f(z)= \dfrac{e^z}{z(1- e^{-z})}=\dfrac{e^{2z}}{z({e^{z}-1})}=\dfrac{ze^{2z}}{z^2({e^{z}-1})}=\dfrac{e^{2z}}{z^2}h(z)$$
 2. Function $h(z)=\dfrac{z}{e^{z}-1}$ has a removable singularity at $z=0.$
Comment: later function has a pole of order 2. so, what is the conclusion?  @M.Strochyk
Comment: Thus $f(z)$ has a pole of order $2$ at $z=0.$

Singularity of a function $ f(z) $


Why does Tkinter work in the terminal but not in Pycharm?

Question: Using Pycharm on Linux mint.
I installed the "future" package for the python interpreter which I'm using. Heres the script.
from tkinter import *

top = Tk()

top.mainloop()

Didn't work. It returns "ModuleNotFoundError: No module named 'tkinter'". Tkinter is infact installed. "python3 -m tkinter" confirms it. And when I compile the same code in the terminal, it displays.
Comment: The two environments probably are configured differently. Perhaps pycharm is configured to use a different version of python than what you get from the terminal.
Comment: Does this answer your question? [Why does tkinter (or turtle) seem to be missing or broken? Shouldn't it be part of the standard library?](https://stackoverflow.com/questions/76105218/why-does-tkinter-or-turtle-seem-to-be-missing-or-broken-shouldnt-it-be-part)
Answer: As Bryan says, you're probably not using the Python version you think you're using. PyCharm tends to install its own version of Python. Once you have more than one version of Python installed, things get trickier.
To see what's happening, try running this script:
import sys

print(sys.executable, sys.version)

Or run those similar commands from the command line.  That should help clarify matters.
The sys.executable will show you the full path to your Python executable. Great for seeing where the used Python installation is located.
I don't use Python on Linux, but perhaps one of your Python installations is version 2, in which case you would need to use:
from Tkinter import *

which is another way to confirm that the Python is version 2 rather than 3. If this is the case, you'll want to move to Python 3. I don't think anyone writes new projects in Python 2 anymore. It's defunct, purely legacy.
It's also possible that Python is installed on Linux without Tkinter. There are other posts on how to install Tkinter on Linux. For instance, you can check out ImportError: No module named 'Tkinter'
Answer: Thanks guys for the help I really appreciate it. But I found out the problem was because of Linux Mint's Software Manager. I initially downloaded pycharm using said software manager but it didnt work which is why I created the post. Then I deleted it, and downloaded pycharm through the tar.gz file from the jetbrains website. After doing that, it seems to work.


clustering,affinity propagation algorithm, minimal number of elements in one cluster

Question: Could someone please clarify the following:
I applied the Affinity Propagation (AP) algorithm to a dataset. The minimum number of elements in one cluster I got was three. I knew in advance that my dataset would contain some unique elements that should be allocated to a separate, alone cluster. So, I would like to set the minimum number of elements in any cluster to one and apply AP. Is it possible to do this in relation to AP (change some parameters), or is it a property of AP to do clustering such that each cluster has at least three elements?
Answer: Such answers are best answered if you would read the original publication of affinity propagation, and study the source code, rather than relying on some vague information from an online QA site...
It's fairly easy to see that AP does not ensure a minimum cluster size. Your control over cluster sizes is only indirect, based on a "self-responsibility" of each point.
Answer: You can't decide the minimal number of items in a cluster in the original AP algorithm. Here's a simpler derivation of it by the original authors:
https://www.psi.toronto.edu/pubs2/2009/NC09%20-%20SimpleAP.pdf
AP is essentially a max-sum, factor graph based algorithm. It maximises a negative similarity given the following 2 constraints:

There can be only 1 exemplar chosen per item.
An item can only choose an exemplar if it chooses itself.

There is nothing constraining the number of points that choose an exemplar however the paper above does detail how you might change the algorithm to do exactly that. I have not seen an implementation of it, but I have implemented AP myself, and it is pretty easy. You can get the matlab code from the authors website.
Finally, if you want to put a specific set of points into a cluster together, that can be done by making them very close together in your similarity matrix.


Query SQL retornando registros duplicados

Question: Tenho duas tabelas (adwords_performance e analytics_transaction) e preciso fazer um SELECT somando as colunas adwords_performance.clicks, adwords_performance.impressions e analytics_transaction.transaction_revenue.
Quando eu faço o SELECT ele me retorna valores de errados em adwords_performance.clicks e adwords_performance.impressions.
SELECT
adwords_performance.date,
Sum(adwords_performance.clicks) AS clicks,
Sum(adwords_performance.impressions) AS impressions,
Sum(analytics_transaction.transaction_revenue) AS revenue
FROM
adwords_performance
LEFT JOIN analytics_transaction
ON analytics_transaction.date = adwords_performance.date AND
analytics_transaction.adwords_id = adwords_performance.adwords_id AND
analytics_transaction.adwords_campaign_id = adwords_performance.adwords_campaign_id
WHERE
adwords_performance.date = '2015-03-01' AND
adwords_performance.adwords_id = '0123456789'
GROUP BY
adwords_performance.date

Resultado:
+------------+--------+-------------+---------+
| date       | clicks | impressions | revenue |
+------------+--------+-------------+---------+
| 2015-03-01 |    465 |       21017 | 1937.71 |
+------------+--------+-------------+---------+

Resultado que era para ser retornado:
+------------+--------+-------------+---------+
| date       | clicks | impressions | revenue |
+------------+--------+-------------+---------+
| 2015-03-01 |    364 |       18577 | 1937.71 |
+------------+--------+-------------+---------+

Tabelas:
mysql> describe adwords_performance;
+--------------------------------+---------------------------------+------+-----+---------+----------------+
| Field                          | Type                            | Null | Key | Default | Extra          |
+--------------------------------+---------------------------------+------+-----+---------+----------------+
| id                             | int(20) unsigned                | NO   | PRI | NULL    | auto_increment |
| adwords_id                     | bigint(255) unsigned            | NO   |     | NULL    |                |
| adwords_campaign_id            | bigint(255) unsigned            | NO   |     | NULL    |                |
| campaign_network_type          | varchar(255)                    | NO   |     | NULL    |                |
| date                           | date                            | NO   |     | NULL    |                |
| week                           | date                            | NO   |     | NULL    |                |
| week_day                       | varchar(25)                     | NO   |     | NULL    |                |
| clicks                         | int(255)                        | NO   |     | NULL    |                |
| impressions                    | int(255)                        | NO   |     | NULL    |                |
| cost                           | int(255)                        | NO   |     | NULL    |                |
| av_position                    | decimal(2,1)                    | NO   |     | NULL    |                |
| clicks_converted               | int(255)                        | NO   |     | NULL    |                |
| estimated_converted            | int(255)                        | NO   |     | NULL    |                |
| estimated_converted_rate       | decimal(10,2) unsigned zerofill | NO   |     | NULL    |                |
| clicks_converted_assisted      | int(255)                        | NO   |     | NULL    |                |
| impressions_converted_assisted | int(255)                        | NO   |     | NULL    |                |
| lost_budget                    | varchar(255)                    | NO   |     | NULL    |                |
| clicks_invalid                 | int(255)                        | NO   |     | NULL    |                |
+--------------------------------+---------------------------------+------+-----+---------+----------------+

mysql> describe analytics_transaction;
+----------------------+----------------------+------+-----+---------+----------------+
| Field                | Type                 | Null | Key | Default | Extra          |
+----------------------+----------------------+------+-----+---------+----------------+
| id                   | int(15) unsigned     | NO   | PRI | NULL    | auto_increment |
| analytics_id         | bigint(255) unsigned | NO   | MUL | NULL    |                |
| date                 | date                 | NO   |     | NULL    |                |
| time                 | int(2)               | NO   |     | NULL    |                |
| source               | varchar(255)         | NO   |     | NULL    |                |
| medium               | varchar(255)         | NO   |     | NULL    |                |
| city                 | varchar(255)         | NO   |     | NULL    |                |
| adwords_id           | bigint(255) unsigned | NO   |     | NULL    |                |
| adwords_campaign_id  | bigint(255) unsigned | NO   |     | NULL    |                |
| transaction_id       | bigint(255) unsigned | NO   | MUL | NULL    |                |
| transaction_revenue  | double(10,2)         | NO   |     | NULL    |                |
| transaction_shipping | double(10,2)         | NO   |     | NULL    |                |
| transaction_tax      | double(10,2)         | NO   |     | NULL    |                |
| product_quantity     | int(10)              | NO   |     | NULL    |                |
+----------------------+----------------------+------+-----+---------+----------------+

Comment: Não encontrei nada de errado no seu select. O que você fez pra acreditar que o resultado esperado realmente é o esperado?
Comment: O problema está no JOIN com os campos data. Para você ter o resultado esperado, as tabelas à direita (estas conectadas por JOIN) deveriam ter um único registro para cada registro da tabela principal. Como na tabela à direita você tem mais de uma ocorrência para a mesma data, o JOIN pelo campo data não vai funcionar como você espera. Você precisa arrumar outro jeito de ligar estas tabelas que não pelo campo data.
Comment: A tabela adwords_performance deve ser agregada em uma tabela virtual ou view e esta e que unir com as demais tabelas , os valores agregados devem estar no agrupamento.
Comment: @Caffé Entendi, você teria em mente alguma maneira de ligar essas tabelas com a estrutura que citei acima de tabelas? Não consigo imaginar outra maneira. Efetuei um teste mudando o campo 'date' para um 'id' e concatenando com JOIN as duas tabelas e ainda aparenta o mesmo erro!
Comment: @JeffersonSilva Eu faço dois SELECT separado um na tabela adwords_performance e outro no analytics_transaction "faço isso para ver realmente o select esta retornando os valores corretos" e ele me retorna aquele valor como citei acima de 364 clicks e 18577 impressions
Comment: @JoãoGabrielPellissari Não tenho nenhuma sugestão de JOIN no momento porque não analisei muito suas tabelas (isso toma tempo). Se você puder criar um exemplo mínimo verificável no sqlfiddle com certeza nós ajudaremos a resolver o problema rapidamente. http://sqlfiddle.com/
Comment: @Caffé Como você pediu é isso fiz uma query envolvendo todas as tabelas que eu utilizo http://sqlfiddle.com/#!9/48bec/4
Comment: O problema é que tem mais de um registro na `analytics_transaction` pra cada `adwords_performance`. Coloquei uma resposta com o método que achei mais efetivo pra resolver o problema
Answer: O problema é que a sua tabela analytics_transaction possui mais de um registro por adwords_performance multiplicando os cliques. Você pode resolver isso fazendo uma subquery para obter os resultados desejados desta tabela, eliminado o join. Porém como é necessário que todos os campos estejam no GROUP BY você deve utilizar um select baseado no resultado da query anterior. O resultado é o seguinte:
SELECT x.date,
       SUM(x.clicks) as clicks,
       SUM(x.impressions) as impressions,
       SUM(x.revenue) as revenue
  FROM (SELECT ap.date,
               ap.clicks AS clicks,
               ap.impressions AS impressions,
               (SELECT SUM(at.transaction_revenue)
                 FROM analytics_transaction at
                WHERE at.adwords_id = ap.adwords_id
                  AND at.adwords_campaign_id = ap.adwords_campaign_id
                  AND at.date = at.date) AS revenue
          FROM adwords_performance ap
         WHERE ap.date = '2015-03-01'
           AND ap.adwords_id = '0123456789') x
 GROUP BY x.date


Swift - How to find the index of an item that is in an array within an array

Question: I am only 10 years old an I am making a War (The Card Game) app. In the war app, I had to put arrays within arrays. How would I find an index of an item in this kind of array? Here's an example where I would get an error:
var card_array = [["2_of_clubs", "2_of_diamonds", "2_of_hearts", "2_of_spades"],
                  ["3_of_clubs", "3_of_diamonds", "3_of_hearts", "3_of_spades"],
                  ["4_of_clubs", "4_of_diamonds", "4_of_hearts", "4_of_spades"],
                  ["5_of_clubs", "5_of_diamonds", "5_of_hearts", "5_of_spades"],
                  ["6_of_clubs", "6_of_diamonds", "6_of_hearts", "6_of_spades"],
                  ["7_of_clubs", "7_of_diamonds", "7_of_hearts", "7_of_spades"],
                  ["8_of_clubs", "8_of_diamonds", "8_of_hearts", "8_of_spades"],
                  ["9_of_clubs", "9_of_diamonds", "9_of_hearts", "9_of_spades"],
                  ["10_of_clubs", "10_of_diamonds", "10_of_hearts", "10_of_spades"],
                  ["jack_of_clubs2", "jack_of_diamonds2", "jack_of_hearts2", "jack_of_spades2"],
                  ["queen_of_clubs2", "queen_of_diamonds2", "queen_of_hearts2", "queen_of_spades2"],
                  ["king_of_clubs2", "king_of_diamonds2", "king_of_hearts2", "king_of_spades2"],
                  ["ace_of_clubs", "ace_of_diamonds", "ace_of_hearts", "ace_of_spades"]]
var locationBottom = card_array.index(of: ["4_of_spades"])
var locationTop = card_array.index(of: ["king_of_diamonds2"])
print(locationTop)
print(locationBottom)

Answer: It looks like what you want is:
var locationBottom = card_array[0].index(of: "4_of_spades")
var locationTop = card_array[0].index(of: "king_of_diamonds2")

Instead, you're looking for an instance of an array containing solely one card in an array that contains an array of all 52 cards.
Comment: Thank you, I'm understanding this now
Answer: The first answer might be correct, but it's not as good as the following since calling an index of an array without checking if it exists will crash your program. :)
Below is an example where you first flatten the nested arrays down to one array, and the use the if let syntax to check for an optional value which is the index.
Then it prints the indexes to the console. I've also included a print statement of the flattened array for you to see what it looks like.
var card_array = [["2_of_clubs", "2_of_diamonds", "2_of_hearts", "2_of_spades"],
              ["3_of_clubs", "3_of_diamonds", "3_of_hearts", "3_of_spades"],
              ["4_of_clubs", "4_of_diamonds", "4_of_hearts", "4_of_spades"],
              ["5_of_clubs", "5_of_diamonds", "5_of_hearts", "5_of_spades"],
              ["6_of_clubs", "6_of_diamonds", "6_of_hearts", "6_of_spades"],
              ["7_of_clubs", "7_of_diamonds", "7_of_hearts", "7_of_spades"],
              ["8_of_clubs", "8_of_diamonds", "8_of_hearts", "8_of_spades"],
              ["9_of_clubs", "9_of_diamonds", "9_of_hearts", "9_of_spades"],
              ["10_of_clubs", "10_of_diamonds", "10_of_hearts", "10_of_spades"],
              ["jack_of_clubs2", "jack_of_diamonds2", "jack_of_hearts2", "jack_of_spades2"],
              ["queen_of_clubs2", "queen_of_diamonds2", "queen_of_hearts2", "queen_of_spades2"],
              ["king_of_clubs2", "king_of_diamonds2", "king_of_hearts2", "king_of_spades2"],
              ["ace_of_clubs", "ace_of_diamonds", "ace_of_hearts", "ace_of_spades"]]

let flatCardArray = card_array.flatMap({$0})
print(flatCardArray)

if let locationBottom = flatCardArray.index(of: "4_of_spades"), let locationTop = flatCardArray.index(of: "king_of_diamonds2") {
    print("index of locationTop is: ", locationTop)
    print("index of locationBottom is: ", locationBottom)
} else {
    print("oh no, couldn't find indexes!")
}

Or you could do
for (number, array) in card_array.enumerated() {
    if let locationBottom = array.index(of: "4_of_spades") {
        print("index of locationBottom is: ", locationBottom, ", in array number: ", number)
    }
    if let locationTop = array.index(of: "king_of_diamonds2") {
        print("index of locationTop is: ", locationTop, ", in array number: ", number)
    }
}

Comment: Mea culpa.  I'm used to Objective-C; the equivalent method in Objective-C will return NSNotFound if an item is not found in an NSArray.
Comment: @TimKokesh That sounds kinda nice. :)
Answer: You are using square array, so you have to find two indexes: one for a row, another for a column, here is a simple example:
let elementToFind = "king_of_diamonds2"
var columnIndex:Int?
var rowIndex:Int? = card_array.index(where: { (arrayInside) -> Bool in
    columnIndex = arrayInside.index(where: { (string) -> Bool in
        return string == elementToFind
    })
    return columnIndex != nil
})

print("Row: \(rowIndex!) Column: \(columnIndex!)")


How can I add a new field from config inside hook_update_N?

Question: I have to add taxonomy by php code. Taxonomy has to got 2 fields. I added new function to test_taxonomy.install, and it seems to work:
function taxonomy_update_8805() {

    $config_path = 'modules/feature/test_taxonomy/config/update/';
    $source = new FileStorage($config_path);

    \Drupal::entityManager()->getStorage('taxonomy_vocabulary')
        ->create($source->read('taxonomy.vocabulary.regulation'))
        ->save();
}

Added new vocabulary to taxonomy.
Content of file:
langcode: pl
status: true
dependencies:
  module:
    - test_remote_vocabulary
third_party_settings:
  test_remote_vocabulary:
    is_remote: 0
name: 'Test'
vid: regulation
description: 'Test desc'
hierarchy: 0
weight: 0

The problematic part is when i try to add fields to the vocabulary.
I created 2 files
field.storage.taxonomy_term.field_regulation_test.yml
langcode: pl
status: true
dependencies:
  module:
    - taxonomy
    - text
id: taxonomy_term.regulation.test
field_name: test_field
entity_type: taxonomy_term
type: text_long
settings: {  }
module: text
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

field.field.taxonomy_term.field_regulation_test.yml
langcode: pl
status: true
dependencies:
  config:
    - field.storage.taxonomy_term.field_regulation_test
    - taxonomy.vocabulary.regulation
id: taxonomy_term.regulation.test
field_name: test_content
entity_type: taxonomy_term
bundle: regulation
label: TEST
description: 'Tekst test'
required: true
translatable: false
default_value: {  }
default_value_callback: ''
settings: {  }
field_type: text_long

But i am not sure how can i load them in update_xxx function.
EDIT:
I tried
    \Drupal::entityManager()->getStorage('taxonomy_term')
        ->create($source->read('field.storage.taxonomy_term.field_regulation_abo'))
        ->save();

    \Drupal::entityManager()->getStorage('taxonomy_term')
        ->create($source->read('field.field.taxonomy_term.field_regulation_abo'))
        ->save();

but i'm getting Missing bundle for entity type taxonomy_term while trying to update module
Comment: It is requied from client. We have to update module and add requieded vocabulary with fields. I decided not to use file like shown above, and add fields programatically, using Naveed Quadri answer from [here](https://drupal.stackexchange.com/questions/139101/create-a-taxonomy-and-attach-a-field-to-it-programatically)
Comment: Uh, seems I misunderstood the problem in my answer below. Thought you wanted to create terms, after some fields were added to the terms. But you seem to try to create a vocabulary and fields from hook_update_N. Why's that? Why don't you create it from config?
Answer: Yes, you can't create content before the relying config has been imported. That's a classic Drupal 8 paradox which has just recently been solved by a new hook: hook_deploy_NAME(&$sandbox).
Update to the latest Drush and from now on run drush deploy as part of your deployment routine, which replaces the old drush updb && drush cim routine. Then create a new file in your module: MYMODULE.deploy.php. In there implement MYMODULE_deploy_NAME(&$sandbox) where NAME can be any unique name (or an incrementing number as well). And use this hook to create the terms, same as in the hook_update_N(&$sandbox) in your question.
drush deploy will ensure that this hook will be picked up at the very last in the deployment routine, after the relying config has been created from configuration import.
Comment: Seems there is no api doc page for this new hook yet.
Comment: https://www.drush.org/latest/deploycommand/


How can I learn foot-from-hand and foot-from-beat independence on the drums?

Question: Similar to How can I significantly improve my hand independence on piano?, I'm wondering how I can improve the independence of my feet from my hands.  I have not done much drumming but this was an obvious and major issue right from the start.  My feet tend to like to fall in line with my hands, but worse is that it's extremely difficult to pedal on anything but the beat.
I figure a lot of the same advice from the hand question holds, particularly starting slow and increasing speed as I get better, but I never had the same rhythm issues with my hands (rather just de-syncing them from each other).  So is there any foot-specific advice that would be useful?
Answer: The same advice from the hand question does hold: start slowly and build up speed slowly.  Please please please use a metronome and use it with discipline.
The thing is, for more inexperienced drummers, limb independence doesn't really exist. Rather, take the time to learn the specific patterns you want to learn, including those where the feet are off the beat.  Make some up if you like, or just copy ones from other drummers. Learn the patterns not with independence in mind but rather as a whole unit, feet and hands working together in concert.  Over time, as you master many such patterns, your muscle memory (i.e. strengthened neural connections) will allow you to play as though your feet and hands are independent, but that won't come for a good while.
Answer: I used to play with an outstanding drummer named Gene Peterson, who you can check out at

. I asked him how he developed such outstanding independence. He said, 'I played everything with each of my hands and feet, individually, in isolation. All my limbs have played it all before, so it's no problem combining them.' What did he mean by 'everything'? His father, Nick Peterson, published a book called, 'The Rhythm Method for Safe Music'. It is a book of rhythm sight reading exercises arranged very systematically. Gene played through every exercise with his right hand, then with his left hand, then with his right foot, then with his left foot, then in combination. It certainly worked. He also plays a keyboard while playing the drums, but that's another story.


Should the max depth of a binary tree exclude the root?

Question: So far, I saw 2 different implementations for a max depth of a tree here,

1st one, max depth === level - 1:
https://www.geeksforgeeks.org/write-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/

Which means, for the base case, if !node: return -1
So a three level tree has a max depth of 2

2nd one, max depth === level:
https://leetcode.com/problems/maximum-depth-of-binary-tree/

Which means, for the base case, if !node: return 0
So a three level tree has a max depth of 3

The implementation in javascript is just as simple as this:
function maxDepth(node){
   if (!node) return -1;
   return Math.max(maxDepth(node.left),maxDepth(node.right))+1;
}

Which one is correct? What am I missing here?
Also, max depth of a tree is equal to the height of a tree, right? Although it calculates in a different way, depth is from node to root, height is from node to leaf node.
Comment: Matter of opinion.
Comment: [Is your question answered?](https://stackoverflow.com/help/someone-answers)
Answer: The terms take different meaning at different places. So, it should be clarified wherever used.

For root, level = 1, depth = 0 and height = 1.
level = depth + 1.
Source: http://typeocaml.com/2014/11/26/height-depth-and-level-of-a-tree/

Wikipedia:

The height of a node is the length of the longest downward path to a
leaf from that node. The height of the root is the height of the tree.
The depth of a node is the length of the path to its root (i.e., its
root path). This is commonly needed in the manipulation of the various
self-balancing trees, AVL Trees in particular. The root node has depth
zero, leaf nodes have height zero, and a tree with only a single node
(hence both a root and leaf) has depth and height zero.
Conventionally, an empty tree (tree with no nodes, if such are
allowed) has height −1

Another interesting discussion on What is the difference between tree depth and height?.
Comment: Thanks, but isn't that means leetcode is wrong?
Comment: Can't say wrong because they have specified their usage of the terms.


How to invoke function once the dom element style is changed Javascript/jquery

Question: I have gone through multiple examples, and implemented the same behavior what the example has stated.
Once the page is loaded, if there is a change in the styling of the dom element I need to trigger a method.
Even if I change anything in the browser console, then also the style change event should trigger. the event will be on display none and display block.
In my code, if am changing in the browser console then the change method is not getting triggered.
This is what I tried:

(function() {
    var ev = new $.Event('style'),
        orig = $.fn.css;
    $.fn.css = function() {
        var ret = orig.apply(this, arguments);
        $(this).trigger(ev);
        return ret;
    }
})();

$('p').bind('style', function(e) {
    console.log($(this).attr('style'));
});
p {
    display: none;
}

 test

Comment: how are you `changing in the browser console` - using jquery .css? because your code seems to work just fine (though, I didn't try with jquery 1.11)
Comment: Use [MutationObserver](https://developer.mozilla.org/en/docs/Web/API/MutationObserver).
Comment: @JaromandaX: No am changing in the css style properties, it should work with jquery.css as well as changing the style property
Comment: @trincot: Can you please help me out with the demo of the same code what I posted
Comment: no it shouldn't, because all you've done is intercepted jquery .css method - nothing you've done effects regular dom methods - trincot's mutation observer is the way to go - read the documentation and have a go yourself - note, wont work in IE10 or earlier, and there's the prefix requirement for safari
Comment: I will post an answer with the use of that, @M-S.
Answer: You could use MutationObserver:
Demo:

// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        var oldDisplay = (mutation.oldValue + '').match(/display:\s*(\w*)/);
        oldDisplay = oldDisplay ? oldDisplay[1] : '';
        if (oldDisplay !== mutation.target.style.display) {
            console.log('element', mutation.target.id,
                    'style.display=', mutation.target.style.display);
        }
    });
});

// attach the observer to the elements of interest:
$('p').each(function () {
    observer.observe(this, {
        attributes: true,
        attributeFilter: ['style'],
        attributeOldValue: true
    });
});

// test it, by changing style.display through button clicks:
$('button').click(function() {
    $('p').toggle(); // show/hide
});

 test this
<button>hide/show</button>
Comment: wouldn't you want `attributeFilter: ['style']` to limit the observer to the style attribute? and `attributeOldValue: true` to see the `oldValue`
Comment: Yes, that would be better. I've added that just now.


Como é criado o escopo de um event listener definido em algum atributo no HTML?

Question: De acordo com a documentação, quando o listener de evento é atribuído como um atributo HTML, o código especificado (no valor do atributo) é envolvido em uma função, com os seguintes parâmetros:

event — para todos os atributos, exceto onerror;
event, source, lineno, colno, e error — para onerror.

O this da função é definido como o elemento HTML que contém o atributo de evento.

No entanto, uma outra pergunta aqui no SOpt (agora apagada[1]) me deixou curioso porque acessa a variável value dentro de um desses attribute handlers. Assim:

<input onkeyup="console.log(value)" />

Verificando se existe um argumento a mais, para a minha surpresa, não. Realmente, conforme colocou a documentação, somente event é passado (já que se trata de um event attribute que não é onerror):

<input onkeyup="console.log([...arguments])" />

Após maiores investigações, percebi que todas as propriedades de Event.target também estão no escopo. Saliento que value é uma propriedade desse objeto.
Então me parece que há algo como um with(event.target) em algum lugar, mas isso é uma suposição e não há confirmação. É, sem dúvidas, detalhe de implementação, já que a exposição desses valores pode ser feita de outro modo. O problema é que, vendo o source da função executada, não há nada além do parâmetro event:

<input onkeyup="console.log(arguments.callee.toString())" />

Pergunto:

Como isso acontece (como é criado o escopo desse attribute event listener)?
Isso está especificado?
Além de (aparentemente) todas as propriedades de Event.target estarem disponíveis, posso acessar mais algum valor?
Qual o suporte disso nos navegadores?
Comment: Não, porque você esta confundindo o comportamento "dentro do HTML", nele o **`this`** pode ser **"implícito"**, não é algo absoluto JavaScript, é do "HTML" (note as aspas). Não estou citando fonte técnica e nem especificação de linguagem, o teste é prático, o "implícito" só quer dizer que em HTML (dependendo de como usa nos atributos `*on`) o `this` ***não precisará ser escrito*** (ou seja esta "implícito")
Comment: @GuilhermeNascimento, procurei por referências, mas não encontrei motivos para entender que o comportamento do JavaScript mudaria dentro do atributo. Na minha concepção, se, dentro do atributo, código JavaScript é executado, então há de rodar seguindo as "regras do JS". Por isso a dúvida — o `this`, no JS, não é implícito (como você sabe), então ainda não consigo explicar ao certo. Aparentemente, realmente as propriedades do `this` são "espalhados" para o escopo do _attribute listener_, mas ainda não encontrei referência para isso. Você tem alguma fonte que corrobore essa sua última afirmação?
Comment: Creio que **isso seja como usar o `this`** aonde qualquer o objeto é o elemento DOM e os eventos são partes da interface "estendida", logo `value` é o mesmo que chamar `this.value`, para um teste rápido ``, outro teste com uma propriedade de um objeto Element `` ou ``, resumindo, esse é o comportamento natural em diversas interfaces usadas em JS, já o `arguments` e `Event` não tem haver com o objeto diretamente sobre o teste com `onkeyup="console.log(value)"`
Comment: @GuilhermeNascimento, o problema é que aí o acesso teria que ser explícito `this.value`, por exemplo. Se fizer `(function() { console.log(value); }).call({ value: 50 })` dará erro. Ainda mantenho a pergunta principal de como esse acesso "implícito" é possível. E eu sei que o `arguments` não tem a ver com isso, utilizei-o somente para fins de demonstração.
Comment: Ok, vou lhes adiantar, tem muita coisa que veio no HTML e JavaScript (esse por sinal da Mozilla, os demais são dialetos "semelhantes/quase identicos") que só começaram a ser DOCUMENTADAS e padronizadas depois, os comportamentos no geral foram apenas sendo copiados entre os concorrentes, desde o surgimento do JavaScript (e na microsoft o JScript), só uns poucos anos depois veio a ter o "ECMAScript", o w3.org já existia, mas não foram eles que definiram inicialmente o comportamentos do JavaScript, já que esse veio depois do HTML já existir ...
Comment: ... então uma coisa lhes garanto, não existem organização perfeita, muitas coisas vão sendo arrumadas ou documentadas depois, eu posso até encontrar alguma referencia no https://html.spec.whatwg.org/#event-handler-content-attributes, mas provavelmente será vago (mesmo que cite coisas mais especificas como o CSP), não quer dizer que vamos encontrar tudo bonitinho e bem escrito ou determinado que é regra, as empresas ficaram se copiando e coisas até mesmo "desnecessárias" existem por causa disso ...
Comment: ... inclusive erro de gramática em uma propriedade do Document em JS: https://pt.stackoverflow.com/q/123468/3635, então é provavel que eu não possa fornecer respostas "documentadas" de tudo, o que posso afirmar são com testes, que já citei no primeiro comentário, `this` é "implícito" em atributos HTML "on", assim como funções e variaveis globais também serão, isso foram testes que fiz, em diferentes navegadores, inclusive navegadores antigos. **É o que posso responder por hora, nem tudo em TI é feito ou planejado a perfeição. ;)**
Comment: Também já tinha encontrado esse mesmo trecho no _HTML Standard_, mas realmente é vago. De todo modo, continuo a procurar por uma referência (e também esperando por alguma resposta concreta, no caso de alguém a encontrar). Obrigado pelos comentários. :-)
Comment: Entendo perfeitamente a motivação, ainda sim espero que tenha dado atenção a histórinha sobre o JavaScript ser da Mozilla, antes de se juntarem a "ECMA International" e que outros navegadores (no caso o IE) tinha apenas um dialeto extremamente semelhante, então as coisas foram sendo "copiadas" de ambos lados, por isso espere achar muita coisa além, o que pode lhe confirmar algo talvez seria olhar os **códigos fonte** do Chromium https://github.com/chromium/chromium e FF: https://archive.mozilla.org/pub/
Answer: TL;DR
O elemento que contém o attribute listener é usado para derivar o escopo da função que será executada. Por isso que as propriedades do elemento (como textContent, value etc) podem ser acessadas diretamente — porque fazem, literalmente, parte do escopo da função.
Ressalto que esta resposta vale somente para attribute event handlers (isto é, aqueles definidos diretamente em atributos no HTML). Eventos adicionados via addEventListener funcionam (similarmente) de outro jeito. Não há modificação do escopo da função passada ao segundo argumento de addEventListener.

Cada evento a ser ouvido no navegador possui um struct associado, chamado Event Handler[1], que contém um campo listener (que corresponde ao ouvidor de eventos) e outro campo, value. No caso dos eventos adicionados através de atributos no HTML, o value desse struct corresponde ao que a especificação chama de internal raw uncompiled handler.
Esse internal raw uncompiled handler é uma tupla contém as seguintes informações: [2]

O corpo do script (não compilado — "uncompiled"), que é o código que está inserido no valor do atributo.
A localização de onde o script se originou, no caso de um erro precisar ser reportado.

Uma vez que o listener é acionado, o navegador procede à avaliação (compilação) do script, que será utilizado para a criação da função callback (que será executada). Para a criação dessa função, leva-se em conta este algoritmo [3], que faz uso da operação interna OrdinaryFunctionCreate (do ECMAScript).
A OrdinaryFunctionCreate é uma operação interna do ECMAScript com a seguinte assinatura:
OrdinaryFunctionCreate (functionPrototype, ParameterList, Body, thisMode, Scope)

Ela é usada para criar a função callback. Para isso, os seguintes argumentos são passados:

functionPrototype ⇒ é o Function.prototype (já somos familiarizados com esse protótipo com as outras funções do JavaScript, que também o assumem).

ParameterList ⇒ no caso de eventos que não são erros (como onclick, onkeydown etc), corresponde a event.

Body ⇒ o corpo da função é gerado dinamicamente através de concatenações com o nome do evento e o corpo. É, basicamente:
function <<name>>(event) {
<>
}

Em que <<name>> é o nome da função callback associada ao evento (como onclick) e <> é o código JavaScript adicionado no atributo de evento no HTML.

thisMode ⇒ passa-se "non-lexical-this".

Scope ⇒ O escopo é definido da seguinte forma:

Inicialmente, o escopo o objeto document;
Se o elemento que possui o attribute event listener está dentro de um formulário (possui um form owner), o objeto do formulário também é incorporado ao ecopo;
Se o elemento que possui o attribute event listener é não nulo, o objeto desse elemento também é incorporado ao escopo.

Desse modo, pode-se afirmar que o escopo surge através dessa tripla derivação (document → form owner → eventTarget). Por isso que, inteiramente, o escopo não será igual ao this.
Consulte o algoritmo completo para saber mais.
Uma vez que a função callback esteja criada, ela é executada. Para essa invocação, o this é definido como o elemento que contém o event attribute[4].

Conclusão
Concluímos, portanto, que valores como value, textContent (e todas as outras propriedades presentes no elemento que ativou o evento) são acessíveis "diretamente" desse jeito pois estão escopo da função callback criada pelo navegador. O conceito de escopo é explicado na MDN.
Não confundir escopo com this, que, a grosso modo, é apenas mais um nome do escopo de uma função.
Mesmo se o "this implícito" fosse possível em JavaScript (o que não é), o exemplo a seguir demonstra o porquê desse não ser o caso (há uma diferença entre o this e o valor do escopo):

<form>
  <button type="button" onclick="
    console.log({
      this_elements: typeof this.elements,   // undefined
      scoped_elements: typeof elements,      // object

      are_eql: this.elements === elements    // false
    })
  ">
    Clique
  </button>
</form>

Explicação

    Mesmo que fosse possível em JavaScript, o "this
    implícito" não poderia ocorrer nessa situação, já que há uma
    evidente (demonstrada acima) diferença de valores.

    O escopo da função, criado a partir do documento, formulário
    pai (se presente) e, enfim elemento associado ao
    attribute event, é diferente do this
    da função, que corresponde (ao contrário do escopo)
    unicamente ao elemento associado ao attribute event.

Isso acontece porque, quando a função callback (criada conforme expliquei acima) é invocada, seu this é definido como o elemento que contém o attribute event listener. Já o escopo (definido durante a criação dessa função callback) é criado a partir da derivação do objeto document, do form owner (se presente) e do próprio elemento referente ao evento. São, pois, diferentes.

Como isso acontece?

Explicado acima.

Isso está especificado?

Sim. As referências para a especificação estão no texto.

Além de (aparentemente) todas as propriedades de Event.target estarem disponíveis, posso acessar mais algum valor?

Na verdade (ao contrário do que eu inicialmente pensei), não é o event.target que é "colocado" como escopo, mas sim o elemento que contém o event attribute (o elemento associado ao evento). O event.target nem sempre a ele corresponderá.

Qual o suporte disso nos navegadores?

Os navegadores que seguem a especificação implementam isso e, portanto, suportam o que aqui foi discutido. A implementação varia entre host, já que a especificação não se preocupa em ditar como fazer, mas sim o que fazer.

Referência

ECMAScript® 2020 Language Specification
Seção "Events" do HTML Standard
Why is there no implicit this in JavaScript
Comment: Deem uma olhada [nessa modificação](https://jsfiddle.net/4qengm51/) do código de origem. Em `` além do `this` estar implícito também é possível referenciar os outros elementos identificáveis no contexto do  ``.
Comment: @AugustoVasques, realmente. Isso também está descrito no [algoritmo](https://html.spec.whatwg.org/multipage/webappapis.html#internal-raw-uncompiled-handler) ([veja esta imagem com algumas marcações minhas](https://i.stack.imgur.com/lQc2B.png)). O que ocorre é que o escopo é definido, primeiramente, como o documento e, depois, no caso de formulários, incorpora-se ao elemento do formulário e, depois, ao próprio elemento que possui o _event attribute_. :-) Quanto ao `this` estar implícito, isso não acontece no JavaScript (conforme explica o último link, nas referências de minha resposta).
Comment: Nesse caso, a grossas palavras, trata-se de uma "derivação tripla do escopo" — `document → form owner → eventTarget`. :D
Comment: Só pra constar, `OrdinaryFunctionCreate` traduzido seria como **"criar uma função qualquer/normal"**, então ele esta na especificação, não quer dizer que é esse nome em motores javascript que rodam em navegadores nem quer dizer que será exatamente assim que o motor funciona, o que precisa é ele atender a isso, mas não ser exatamente isso. E vale ressaltar que referir-se ao this naquele momento queria mais dizer, se comporta como tal, não quer dizer que internamente é exatamente isso.