Why is Hendrix's tuning at Woodstock in between Eb and E?

Question: I have the album Live at Woodstock in digital format. I noticed that everyone in Hendrix's band is (seemingly) tuned to some pitch between Eb and E.
I've heard some various, uncited sources that they were actually tuned to Eb, but the recording was played too fast on a record player which increased the speed and subsequently the pitch. I don't have access to the vinyl.

It's probably a slight difference in playback speed from the speed it was recorded at. This would be a particular problem if you are dealing with old recordings, live in a country that uses PAL, or both.

http://www.mylespaul.com/forums/cellar/249395-woodstock-hendrix-tuning.html#post4997246

It's E flat boys. The difference is in video, vinyl or digital whatever your listening to. I have a strobe turn table and when it is set proper everything is E flat.

http://www.mylespaul.com/forums/cellar/249395-woodstock-hendrix-tuning.html#post5000403
Yet it's clearly not Eb in the digital 1999 release of Live at Woodstock.

Could be that the speed of the recording is off a little causing a change in pitch.

http://www.strat-talk.com/forum/stratocaster-discussion-forum/223284-woodstock-hendrix-tuning.html#post1250476
Some circumstantial evidence:

Hendrix's other live recordings seem to all be near exactly Eb (Monterey, Filmore East, etc.)
The tempo of most of the songs seems to be faster than any other recordings of the same song (e.g., "Fire").

Is this "recording speed" theory truly the case? Or is it simply a result of precise, but inaccurate tuning?
Comment: What makes you think that when the band went on stage that they were concerned about being exactly in tune according to some external standard? As long as they were in tune  with each other, they did not care about anything else. It is the same with all bands everywhere, all the time. Furthermore in the 1960s there were no tuning devices for use in live performance other than a metal tuning fork and the performers' ears.
Comment: @WheatWilliams I don't think that at all, and nowhere did I imply that I do. In fact, it was always my understanding that this tuning was the result of exactly what you describe, until I read some comments about the record speed.
Comment: Could be either. It's difficult to draw a conclusive answer. It would not be the first time that a weird mastering error changes the pitch of a recording - The Beatles fell victim to this *lots* of times. Try a forum specifically for mastering geeks, e.g. Steve Hoffman's, maybe.
Comment: @SomeDudeOnTheInterwebs Thanks for the forum recommendation, I'll try there. I just find it curious that Kramer didn't correct this for the remix released in 1999.
Comment: If you spend some time on that forum you'll end up with a rather bleak view of mastering engineers and (especially) label managers. *Especially* from 1999.
Answer: Back in the 60s, unless there was an instrument that couldn't easily be re-tuned, i.e. piano, organ, etc, featuring in the set, all guitars were tuned to each other, probably using the first one that was in tune. It wasn't that important, as long as everyone was at the same pitch. Occasionally a piano was used, and the band would have to tune to whatever that was. So somewhere between Eb and E was common. Horns could be tuned to within a semitone, so no problem there.
Comment: Thanks, I've heard this before. I'd like a more specific and concrete answer, though.
Comment: It happened a lot. I remember playing a gig, two bands on, and at the end of the night, both bands decided to play together the no. 1 for that week. Key sorted, it was horrendous. Only after the gig did I realise why. The two bands were a demi semitone out with each other!. Didn't make any difference when one band was playing - why would it?
Comment: Considering the conditions at Woodstock it is not surprising that the tuning would not be in some traditional standard pitch. I mean they just jammed. Van Halen has tunes recorded like Ain't Talkin Bout Love that are tuned in between E - Eb.


Prove a number is composite

Question: How can I prove that $$n^4 + 4$$ is composite for all $n > 5$?
This problem looked very simple, but I took 6 hours and ended up with nothing :(. I broke it into cases base on quotient remainder theorem, but it did not give any useful information.
Plus, I try to factor it out:
$$n^4 - 16 + 20 = ( n^2 - 4 )( n^2 + 4 ) - 5\cdot4$$
If a composite is added to a number that is a multiple of $5$, is there anything special? A hint would suffice.
Thanks,
Chan
Comment: Why the condition $n>5$? It is enough $n>1$.
Answer: You can factor out $n^{4}+4$ algebraically by finding the four roots of $n^{4}+4=0$.
Since $n^{4}+4=0\Leftrightarrow n^{4}=4e^{i\pi }$, we have
$$\begin{eqnarray*}
n &=&4^{1/4}e^{i (\pi +2k\pi)/4}\quad k=0,1,2,3 \\
&& \\
n &=&\sqrt{2}e^{i\pi /4 }=1+i\quad \left( k=0\right)
\\[2ex]
n &=&\sqrt{2}e^{i 3\pi /4 }=-1+i\quad \left( k=1\right)
\\[2ex]
n &=&\sqrt{2}e^{i 5\pi/4 }=-1-i\quad \left( k=2\right)
\\[2ex]
n &=&\sqrt{2}e^{i 7\pi/4}=1-i\quad \left( k=3\right).
\end{eqnarray*}$$
Now combining the complex conjugates factors, we get
$$\begin{eqnarray*}
n^{4}+4 &=&\left( n-1-i\right) \left( n+1-i\right) \left( n+1+i\right)
\left( n-1+i\right)  \\
&=&\left( \left( n+1-i\right) \left( n+1+i\right) \right) \left( \left(
n-1-i\right) \left( n-1+i\right) \right)  \\
&=&\left( n^{2}+2n+2\right) \left( n^{2}-2n+2\right).
\end{eqnarray*}$$
Note: for $n>1$, $n^2+2n+2>5$ and $n^2-2n+2>1$.
Answer: This is a special case of a class of cyclotomic factorizations due to Aurifeuille, Le Lasseur and Lucas, the so-called Aurifeuillian factorizations of cyclotomic polynomials $\rm\;\Phi_n(x) = C_n(x)^2 - n\ x\  D_n(x)^2\;$. These play a role in factoring numbers of the form $\rm\; b^n \pm 1\:$, cf. the Cunningham Project. Below are some simple examples of such factorizations:
$$\begin{array}{rl}
x^4 + 2^2 \quad=&  (x^2 + 2x + 2)\;(x^2 - 2x + 2) \\\\
\frac{x^6 + 3^3}{x^2 + 3} \quad=&  (x^2 + 3x + 3)\;(x^2 - 3x + 3) \\\\
\frac{x^{10} - 5^5}{x^2 - 5} \quad=&  (x^4 + 5x^3 + 15x^2 + 25x + 25)\;(x^4 - 5x^3 + 15x^2 - 25x + 25) \\\\
\frac{x^{12} + 6^6}{x^4 + 36} \quad=&  (x^4 + 6x^3 + 18x^2 + 36x + 36)\;(x^4 - 6x^3 + 18x^2 - 36x + 36) \\\\
\end{array}$$
Answer: Try factoring as the product of two quadratic expressions: $n^4+4=(n^2+an+b)(n^2+cn+d)$.
Comment: The quickest way of factoring is probably to start like this: $(n^2)^2 + 2^2 = (n^2+2)^2 - (2n)^2 = \dots$
Comment: @Chan: Now try this: for which $t\in\mathbf Z$ does $n^4+t$ factor?
Comment: BTW, I first saw that problem in the first chapter of Apostol's *Introduction to Analytic Number Theory*. I immediately thought of using Fermat's theorem: $n^4+4$ is divisible by 5, but that only works when $n$ is not a multiple of 5. Now Apostol does not discuss Fermat's theorem till later, so there had to be a more fundamental reason. Alas, it was an algebraic reason, not really an arithmetic reason.
Comment: Thanks a lot for the information. I will try harder.
Answer: $$ x^4+4=\\
[(x^2)^2+4x^2+4]-4x^2\\
=(x^2+2)^2-(2x)^2\\
=(x^2+2x+2)(x^2-2x+2)\ldots $$
Answer: Factoring yields
$$
\begin{align}
n^4+4
&=(n^2+2i)(n^2-2i)\\
&=(n+1+i)(n-1-i)(n+1-i)(n-1+i)\\
&=(n+1+i)(n+1-i)(n-1-i)(n-1+i)\\
&=((n+1)^2+1)((n-1)^2+1)
\end{align}
$$
So for $n>1$, $n^4+4$ is composite.
Answer: In fact, it is true for $n>1$. You just need a clever way of factoring the expression:
$$n^4 + 4 = n^4 + 4 + 4n^2 - 4n^2 = \left ( \cdots + \cdots - \cdots \right ) \cdot \left ( \cdots + \cdots + \cdots \right )$$

Prove a number is composite


Error when try adding admob to the project

Question: I got this error when adding admob to the project.
full project link
<code>Severity    Code    Description Project File    Line    Suppression State   Suppression State
Error       error: MediationRewardedVideoAdListenerImplementor is not abstract and does not override abstract method zzc(Bundle) in MediationRewardedVideoAdListener
public class MediationRewardedVideoAdListenerImplementor    app\App8\obj\Debug\90\android\src\mono\com\google\android\gms\ads\reward\mediation\MediationRewardedVideoAdListenerImplementor.java 4
</code>
Comment: I can not download your project because it shows some danger, so can you take a look the Admob sample:https://learn.microsoft.com/en-us/samples/xamarin/monodroid-samples/google-services-admobexample/, if you still have some problem, please upload your sample at github.
Comment: thanks  Cherry Bu - MSFT
Answer: thanks Cherry Bu - MSFT
The cause of the problem occurred using an old version of Google's advertising libraries
Comment: Glad to hear that you have solved your problem, please remember to mark your reply as answer, it is helpful to others to find this answer, thanks.


Incorrect Kurtosis, Skewness and coefficient Bimodality values?

Question: This is my first post in CrossValidated and hope you can solve my problem. I've tried to calculate the bimodality coefficient (b) of two frequency distributions by using this formula:

where g is de skewness, K is the Kurtosis and n is the sample size. The b of a given emprirical distribution is then compared to a bencmark value of 0.555:  higher numbers point toward bimodality whereas lower numbers point toward unimodality. I've been working with two frequency distributions in order to detect the degree of bimodality for each one. Here I show the two plots:
1)

2)

So, to have a quick look, it seems that the second distribution is more bimodal (two peaks) than the first one (hump-shaped). However, the bimodality coefficients do not say the same when I run in the R programme:

Kurtosis Skewness        b
  1 4.046225 1.927172 0.6602856
  2 4.064557 1.843587 0.6145607

Apparently, both distributions are bimodal due to their b values  are higher than 0.55.  Seems logic for plot2 but plot1 has a clear unimodal distribution. Furthermore, I'm afraid that the values of Kurtosis and Skewness were incorrect. In theory, skewness values higher than 0 means that the distribution is right skewed but I could not see in the original plots. For Kurtosis >3 the distribution is leptokurkic which means to be sharper than a normal distribution.
Maybe I'm doing something wrong in the methodology to calculate Skewness and Kurtosis. I've used the e1071 package in R programme to calculate these variables by using the following script:
library("e1071")
  kurt<-kurtosis(frequency,type=2)
  skew<-skewness(frequency,type=2)

Formula type 2 for kurtosis: G_2 = ((n+1) g_2 + 6) * (n-1) / ((n-2)(n-3))
Formula type 2 for skewness: G_1 = g_1 * sqrt(n(n-1)) / (n-2)
It would be very useful to me if someone could explain me these results. Maybe I miss something in the methodology.
Thank you very much for your help!
Comment: I suggest that you give a source for this procedure, which strikes me as singularly bizarre. I see no reason why a complicated composite of kurtosis and skewness should be an especially good indicator of bimodality and the idea that something special happens around 0.555 is triply mysterious. An old-school view is that bimodality is evident on almost any distribution graph when it genuinely occurs. But those prejudices aside, documenting something as unusual as this is surely good practice.
Comment: Moment-based skewness and kurtosis results are frequently not as simple to interpret as many introductions imply. It's easily possible to get (e.g.) positive skewness even if a major mode is not in the left half in the distribution. Persistent debate over whether kurtosis measures peakedness or heavy tails can be resolved by showing examples where either or both can pull up kurtosis. Many threads here on such matters, as the tags imply: did you search previous posts?
Comment: Finding puzzling results is not a reason to suspect bugs in software like this. The problem lies in texts and courses that simplify a very complicated area; they have to do that, as it's their job to do so! The field is full of strange puzzles: e.g. for the Poisson, a textbook example of a right-skewed distribution except in the limit, it's possible and common for the median to exceed the mean!
Comment: A comment on Nick's comment, "Persistent debate over whether kurtosis measures peakedness or heavy tails can be resolved by showing examples where either or both can pull up kurtosis." Kurtosis *does* measure heavy tails. The supposed "counterexamples" only involve a measure of "heavy tails" that involves distributions crossing at some point. It does not correspond to the practical application of "heavy tails" which concerns potential outliers, which is in fact measured by the kurtosis statistic.
Answer: I agree with @NickCox : I think the mistake is in the first line of your post, where you define "bimodality coefficient". I Googled and found Pfister et al (which references SAS/STAT from 1990). That paper indicates problems with BC that are quite similar to the ones you found and recommends Hartigan's dip test, instead of BC (or in addition to it). The dip test is available in R through the diptest package. In addition, the kurtosis in the formula is supposed to be excess kurtosis and you appear to not have adjusted for that (although I am not certain of this)
The SAS documentation also mentions problems with BC, in particular

Very heavy-tailed distributions have small values of regardless of the
  number of modes.

The long tail of your second distribution is probably lowering the value of BC.
In short, the problem is in the formula, not in your code.  There is, as far as I know, no perfect measure of the number of modes.
Comment: Yes, I read Pfister et al 2013 despite facing problems with BC. I will use dip test with diptest package but as Pfister et al 2013 said: "both measures have merit for assessing bimodality but neither  statistic is perfectly sensitive and specific at the same time". Keep working


How to download a PDF file with selenium python webdriver?

Question: Website: http://mbct.com/wp-content/uploads/Eisendrath-Jan-2016.pdf
Error: unable to locate the element
Maybe this is because the download icon will disappear when I don't do something?
This is my code:
# coding=utf-8
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
import os
site = 'http://mbct.com/wp-content/uploads/Eisendrath-Jan-2016.pdf'
br = webdriver.Chrome()
br.get(site)
br.find_element_by_xpath('//*[@id="icon"]').click()

Comment: You appear to be trying to find an XML element in a PDF. PDF, unlike HTML, does not overlap with XML. The download icon that shows up if you visit a PDF in your browser is not a part of the webpage.
Comment: If your goal, as it seems, is to download the PDF... you can do that by just downloading the URL by whatever means you like - you shouldn't need to use a webdriver (or any Python at all) for that, just load it with curl in a shell script. If you do want to use Python for whatever reason, `urllib.request` (Python 3) or `urllib2` (Python 2) can do it.
Answer: Transferred from comment to answer:
You appear to be trying to find an XML element in a PDF. PDF, unlike HTML, does not overlap with XML, so that's not going to work.
The download icon that shows up if you visit a PDF in your browser is not a part of the webpage, so even if a PDF was XML, that wouldn't work. Also, there's a decent chance that there's more than one icon, in which case you'd probably be clicking on the wrong thing, and it might not be clickable (if you were using this for some non-PDF thing with a download button on the actual webpage).
To download a PDF from a website... you shouldn't need to use a webdriver (or any Python at all). Just load it with curl in a shell script, if you're on UNIX. There's probably a simple Windows equivalent but I don't know it. If you do want to use Python for whatever reason, urllib.request (Python 3) or urllib2 (Python 2) can do it.
Or, if it really is just that website, you don't need to run an automatic program at all - just right-click the link and choose "Save link as..." or equivalent in most browsers.


How can an augmented 3rd interval be considered dissonant?

Question: I'm reading a book where the augmented 3 interval(two note) is considered a dissonant. However being that its enharmonic equivalent is a perfect fourth, I can't see how this can be so.
I've done a little digging and some say that it has to do with the context of the music. So I'm presuming that if perhaps a composer for example drifted into a different mode/scale he may spell the perfect fourth interval as a Aug 3rd (and therefor a dissonant) in this new context. Depending of course on the scale.
So for example this interval would be written in as a Aug 3 if the composer was writing in c lydian; the e sharp clashing with the f sharp of the lydian mode.
Am I right in this thinking
Comment: Depending on the "language" (in the sense of style and other details), even the perfect fourth is considered dissonant if it's "alone", with no other voice to put in a context. Many examples of two-voice counterpoint that produce a perfect forth are considered like this. When a third voice comes into play, things change for the perfect fourth, and also put in different "situations" the resulting voice-conducting for the augmented third.
Also, if you consider it as a melodic interval (in a harmonic context), it's usually difficult to sing.
Comment: The key takeaway here is that dissonance is not a purely acoustical property.
Comment: As a clarification, you are referring to the interval (two notes) of an augmented third? (As opposed to and augmented triad (e.g., C E G#).)
Comment: Actually many people hear the P4 as dissonant.  So it is not clear that your question makes sense in this context.  Perhaps a little more reading on this topic would help.
Comment: Yeah, so C E#  . Sorry I should have made that clearer
Comment: Thanks. Then your understanding is correct. It depends on the context. In addition to the Lydian example you give, it could also theoretically come up during some sort of modulation. I don't know of an example in practice.
Comment: Related question: [Under what circumstances, if any, would we hear enharmomics of the perfect fourth or fifth (e.g. augmented third) in a tonal composition?](https://music.stackexchange.com/q/117998/70803).
Answer: All augmented and diminished intervals are considered dissonant. The interval C-E# is only equivalent to C-F in a tempered scale (particularly the equal-temperament that most keyboards now use.) On stringed and wind instruments as well as with voices, C-E# is different from C-F.
Augmented intervals generally expand and diminished intervals contract. Perfect, major, and minor intervals have their own voice-leading procedures.
Comment: "On stringed and wind instruments as well as with voices, C-E# is different from C-F": this is hardly universal truth.  Most musicians I know would have no clue about how or why they should treat them differently, and consequently would not treat them differently.
Comment: phoog's comment is right, but still +1 because C-E♯ is _conceptually_ not a 3:4 fourth. If the score says C-E♯ but the musicians intuitively intonate it as a fourth and the listener hears that as well, it's probably the composer's fault for not clearly bringing out the true intend in the context.
Comment: @leftaroundabout you assume that the composer intends there to be a difference, but what if the composer is one of those musicians who isn't aware of the difference? What if the composer's intent is that the E sharp be tuned as a 16:15 half step higher than E and that E is a 5:4  major third above C?  What if the composer's intent is that the piece be performed in some 12-tone temperament?  You should not draw conclusions about a composer's intent solely from the composer's choice of a particular enharmonic spelling option.
Comment: @phoog I didn't draw any conclusions about what the composers intend _is_, but I stand by it that the intend _isn't_ an audibly consonant fourth. That doesn't mean the actual frequency ratio can't be very close to 4:3, as it is for the 12-edo augm3, but then the context should divert attention away from that. If none of that applies, then I would indeed claim that it's a mistake by the composer. Either make the augmented third really dissonant to the listener, or just write a perfect fourth instead.
Comment: @leftaroundabout 364 days later, I have another thought: the conceptual difference is more important than tuning.  I am coming to the conclusion that people are using the (possible) tuning differences as an easy way to explain the difference, but it doesn't really do the job.  Literally decades before I understood anything about unequal temperament, I knew that enharmonic spelling mattered, but I wasn't terribly good at explaining why.  Even in equal temperament, the diminished fourth feels different from a major third, for example melodically in `iv7 V7 i`.
Comment: @phoog hm. Let me consider that for a couple of centuries, I'll come back to you then.
Answer: Upon first glance a perfect fourth and augmented third seem for all intents and purposes equal...

...they are enharmonically equal. On a piano they are literally executed with the same keys.
But by definition augmented and diminished intervals are considered dissonant.
Why? I think the reason is clear when we consider whether the modified interval is diatonic or chromatic.
Play something to just establish a diatonic setting...

...then play an augmented third that is not enharmonically equal to a diatonic perfect fourth...

...the sound is pretty jarring, because it's outside the key. It's a sort of dissonant against the diatonic context.
I don't know if that is the origin of the theory that all augmented and diminished intervals are dissonant, but it's my way of making sense of it.
One final thought going back to the diatonic, enharmonically equal example. If we add a note to create a triad, we get...

If the context was clearly a C chord, like a tonic in C or dominant in F, then spelling it with a B# is aggravating. It doesn't make a good example of an augmented interval as a dissonance. It's just an example of bad harmonic spelling.
Answer: Some of the answers focus on tuning here, but as Michael Curtis points out, that's not an issue on many instruments (and -- as phoog notes in comments -- isn't even an issue for many performers on instruments with more flexible tuning unless they're particularly sensitive to how they tune unusual intervals).  Historically, the distinction was partly wrapped up in tuning issues, but there's more to why ultimately all diminished and augmented intervals are declared "dissonant," even if they have enharmonic "consonant" equivalence.
And that has to do with function, something hinted at in a few answers.  Functionally, if an augmented or diminished interval is spelled correctly, then it is necessarily also occurring in a situation that would be considered melodically (and possibly harmonically) dissonant.  And any melodically dissonant leap would have additional contrapuntal rules placed upon it, such as whether it was possible to leap to or from those notes, or how that melodic leap should be used or resolved in subsequent melodic context.
This is easier to see by analyzing intervals that are more likely to occur in practice, like a diminished fourth.  Enharmonically, a diminished fourth on a piano is the same interval as a major third, but whenever a diminished fourth is properly spelled within a key, it acts as a dissonance.
For example, consider C minor.  If one leaps from E♭ to B♮, that is utilizing common notes within the minor scale, going from the normal third scale degree to the leading tone.  But that's a "charged" interval.  If you play for a few bars in C minor and then play that interval, you'll feel like it has to "resolve" (similar to how a tritone leap feels like it should "resolve"), and your ear will likely recreate a feeling of dominant harmony under the B, even if you don't play the chord.  The B♮ generally must resolve upward to C in a C minor context, particularly after a leap like that.
However, now reimagine the same keys on the piano played in the context of B major.  Now it's a leap down from D♯ down to B, and both of those notes feel like "stable" parts of the tonic chord.  There's no need for resolution.
I've done this demonstration many times for musical beginners to explain why spelling of intervals is important.  Playing in a C minor context, they feel like the E♭-B♮ diminished fourth "needs to resolve" melodically, but then I'll immediately follow that by playing the same notes where the D♯-B are in a B major triad, and suddenly they become confused and say, "huh, that's consonant and stable."
(The same would apply if that diminished fourth would be used as a harmonic interval.  In the scenario above, I suppose that could occur in the context of a dominant chord in C minor with an added minor thirteenth.  That's not a stable interval in classical harmony.  It would be treated as a dissonance.
Either the minor thirteenth is going to have to resolve down to become consonant with the rest of the V chord, or the chord is going to have to change -- say dominant to tonic, where the leading tone resolves and again gets rid of the diminished fourth interval.)
The same thing goes for an interval like an augmented third.  The problem is that it's quite a bit harder to demonstrate a situation where one would spell an augmented third melodically that way in a tonal context.  I've tried a bit to think of one that didn't seem contrived, but it's difficult.  In most contexts where I think this would likely occur, the augmented third would be part of some figure where the destination note is obviously a kind of chromatic appoggiatura that would be required to resolve.
Just to try to imagine a harmonic scenario, I suppose we might start in C minor again.  One might, I suppose, have a D♭, as the root of a Neapolitan chord, and then leap to F♯ as the third of a V/V chord.  This would generally be a very bad idea contrapuntally, but if you did it, you'd be obligated to resolve the F♯ upward to G as the leading tone to scale degree 5.  The melodic interval would be considered "dissonant" and require resolution.  If the harmonic context changed in such a way that you could actually respell the interval as a perfect fourth (e.g., a D♭-G♭ leap in the context of a modulation where the Neapolitan is used to modulate to the key of G♭ or something), the note leapt to would generally not require "resolution."
This is the sense in which "melodic dissonance" is meaningful: one or both notes of the interval are tendency tones that want to resolve in a particular direction, and after the leap, one is usually obligated contrapuntally to do so.  But that obligation on an augmented third would not generally apply to a melodic leap of a perfect fourth.
While the same concept would apply to a harmonic interval, the chances of encountering a legitimate correctly spelled augmented third in a tonal piece are possibly even lower than finding a melodic one.  I suppose one might consider a V7 chord in C.  Now imagine that the leading tone B uses a neighbor tone figure moving B-A♯-B.  That would create a "dissonant" interval of an augmented third between F and A♯ which is corrected ("resolved") by the A♯ moving back to the chord tone B.  But here the "dissonance" is mostly created by the context, just as it was in the diminished fourth example in C minor discussed above.  If we heard a passage with a bunch of chromatic lower neighbor tones in a piece, we'd know the A♯ needs to move back upward to the leading tone.  Out of context, the F-A♯ harmonic interval could be lots of things (and could sound like the stable perfect fourth F-B♭, and it might even create a minor-minor seventh chord in a different context).  But in that motivic/harmonic context, it's unstable and the A♯ must move to the B (which itself is part of a tritone that will then resolve as well).
In essence, spelling matters, even if the tuning of two enharmonic intervals is the same.  Enharmonically equivalent intervals are functionally quite different -- in one context, they may be stable and "consonant," but in another context (and with a different spelling), they may require resolution and in any reasonable harmonic context will sound locally "dissonant."  Pretty much any scenario you can come up with involving a harmonic or melodic use of an augmented third within a major or minor key and assuming that that spelling is correct is necessarily going to be unstable and require resolution.
Answer: At first sight some augmented intervals could be transformed in consonant intervals considering the semitones. So it might seem that mathematically this dissonance is only theoretically and supposed by the notation image.
But, as Pipetus says in his comment even the fourth is dissonant.
And yes, all augmented and diminished intervals are considered as dissonant. (Ttw).They are stressed, containing lead tones, leading to the nearby next tone.
https://en.wikipedia.org/wiki/Augmented_third
So we could also compare the augmented second with a minor third:
The augmented interval is dissonant with a tension of resolving into a nearest note step, defined by the melodic and harmonic context ( sharps leading up, flats leading down).
On a piano these dissonances are not always audible. (Bartok Mikrokosmos vol. IV, nr. 111

Read more about  Unusual Transformations in Bartok's "Minor Seconds, Major Sevenths"
https://www.esm.rochester.edu/integral/wp-content/uploads/2019/06/INTEGRAL_12_gollin.pdf
Comment: Yes, we should say *the fourth is considered as dissonance as suspension*. As an inversion of the 135 triad it is consonant of course.
Comment: The augmented second is an excellent example because it's such a characteristic feature of the harmonic minor scale. You simply cannot mistake that oversized step on the scale for a minor third.
Comment: The fourth is treated carefully in voice leading. It's treated as a dissonance against the bass (like in a 6-4 chord) but as a consonance against upper voices(like in a 6-3) chord.
Comment: @ttw or we could just say [the fourth is consonant but the eleventh is dissonant](https://music.stackexchange.com/a/71725/932).
Answer: Unusual augmented and diminished intervals are there to create color in the harmonic progressions in pieces where they appear and are applied..
They are normally a mixed structure, so to speak and don't appear in your regular diatonic contexts. Context differences are key here.
There are many possible combinations of a respective augmented third; (let's take the basic C to E sharp)
The C can belong to any key containing the note C, and the E sharp belong to any key that contains the note E sharp.
I am referring to regular scale keys here.
An example:
The C can belong to F major which would be the dominant scale degree in F major; whereas the E sharp can belong to f sharp harmonic minor, where the E sharp is the raised leading note in f sharp harmonic minor.


Dividir elementos de uma lista por um número

Question: Olá!
Eu sou estudante de astrofísica e estou precisando saber como se faz para "normalizar" uma função do astropy:
blackbody_lambda(wavelenght, temperatureG)
Para este valor específico:
1279894.374188775erg / (Angstrom cm2 s sr).
Utilizo o python.
Abraços!
Comment: O que seria normalizar a função neste caso? Qual é o resultado esperado?
Answer: Divisão
Você pode fazer:
myList = [1,2,3,4,5,6,7,8,9]
myInt = 10
newList = [float(i) / myInt for i in myList]

Ou se você precisar manter a referência na lista original
myList[:] = [float(i) / myInt for i in myList]

Você também pode usar a biblioteca NumPy
import numpy as np
myArray = np.array([1,2,3,4,5,6,7,8,9])
myInt = 10
newArray = myArray/myInt

Normalização
Agora se você deseja normalizar em relação à unidade usando a soma:
mySum = sum(myArray)
norm = [float(i)/mySum for i in myArray]

ou usando o máximo:
myMax = max(myArray)
norm = [float(i)/myMax for i in myArray]


Sum of generalized gamma variables

Question: This question is in a way duplicating this question, but I'm not happy with the final answer and feel like I need a deeper dive.
Assume that $X_j \sim \Gamma(\alpha_j,\beta_j)$, where $\alpha, \beta$ denotes shape and rate.
I'm interested in deriving the form of $GG(\gamma, \alpha, \beta)$ of the following sum, where $\gamma$ is the form/power parameter:
$$S = \sum_{j = 1}^{d} X_j^2$$
From the previous answer I understand, that $Y_j=X_j^2$ has a Generalized Gamma distribution with $\gamma = 1/2$. It follows, that $\sum_{j=1}^{d} Y_j^{1/2}$ has gamma distribution, therefore $S$ is also Generalized Gamma variable.
However, how would the final parameters of the distribution look like?
Assuming $\beta_j = \beta, \forall j$, it is known that $Z = \sum_{j=1}^{d} Y_j^{1/2} \sim \Gamma(\sum \alpha_j, \beta)$. Knowing $Z$, how should we proceed in deriving the form of $S$? The previous answer claims that it is straightforward from there as if it's $GG(\gamma, \sum \alpha_j, \beta)$, which doesn't feel true since $S^{1/2} \neq Z$.
Answer:
Knowing $Z$, how should we proceed in deriving the form of $S$? The previous answer claims that it is straightforward from there as if it's $GG(\gamma, \sum \alpha_j, \beta)$, which doesn't feel true since $S^{1/2} \neq Z$.

You can not apply the result from the other question.
The situation in the question that you reference is a lot different from your case

In the other question, the sum is of gamma distributed variables and not of generalised gamma distributed variables. $$z^d = \sum_i x_i^d = \underbrace{ \sum_i y_i}_{\substack{\text{sum of}\\\text{gamma distributed}\\\text{ variables}}}$$ If $X$ is generalized gamma distributed with parameter $d$ as power, then $Y=X_i^d$ is gamma distributed.

In the other question, the sum is of independent and identical distributed variables.
The parameters of $X$ and the associated $Y$ are the same. For independent and identical distributed gamma distributions you get that their sum is again a gamma distributed variable. So in that other question $z^d$ is gamma distributed and that makes $z$ generalized gamma distributed.

In your case

You seem to describe a case with non-identical distributed gamma distributions (or at least you define parameters with subscripts $\alpha_i$ and $\beta_i$ which suggests that the distributions can be different).
In this case you get that the sum follows a distribution that can be described as a mixture of exponential distributions.  (see Generic sum of Gamma random variables)

You describe a sum of generalised gamma distributions.
If $X$ is gamma distributed, then $X_j^2$ is generalised gamma distributed. This is an opposite situation from the referenced question.
You have a sum of powers, but note that the power operation is both a transformation that can transform a generalized gamma distributions to a gamma distributed variable as the other way around and transform a gamma distributed variable to a generalized gamma distributed variable.
If $X_j$ is gamma distributed then $X^{1/p}$ is generalized gamma distributed with parameter $\gamma = p$. If $X$ is generalized gamma distributed with with parameter $\gamma = p$.  then $X^{p}$ is gamma distributed.
So your analogy with the other question does not work

It follows, that $\sum_{j=1}^{d} Y_j^{1/2}$ has gamma distribution, therefore $S$ is also Generalized Gamma variable.

You indeed have that $\sum_{j=1}^{d} Y_j^{1/2}$ has a gamma distribution (but as the previous point notes only for iid variables), but your case is the sum $\sum_{j=1}^{d} Y_j$
Comment: The above answers the question about the connection with the other question. But it is a bit of an XY-problem and the underlying problem is not solved. To get that underlying question solved it might help to make a question that describes the problem more precisely. Depending on the situation one can solve it differently, for example one might use approximations.
Answer: For the sum of independent Gamma random variables with different shape and rate/scale parameters, the answer has been given in
Moschopoulos, P. G. (1985). The distribution of the sum of independent gamma random variables. Annals of the Institute of Statistical Mathematics, 37(3), 541-544.
The density can be expressed as an infinite sum involving some complicated expressions of the underlying parameters.

Perhaps this can be a base to work the sum of squared variables.
Comment: It's hard to see how this result (which is demonstrated at https://stats.stackexchange.com/questions/72479/generic-sum-of-gamma-random-variables/72486#72486 here on CV) can be applied to the sum of *squared* Gamma variables.  Do you have a suggestion about how to proceed?
Comment: @whuber  I leave that to the OP who, if interested enough they can lookup the reference, see there that the expression comes from working with the MGF of the sum, and likewise explore whether the same technique can be applied to the MGF of the sum of squares.

Sum of generalized gamma variables


Nested Quantifier placement confusion

Question: I'm working on a question right now that's asking me the difference between
"For every integer a, b, if for every integer x, ax+b is even ... " and
"For every integer a, b, x if ax+b is even ..."
I already proved the first statement as true but I'm struggling to find a concrete difference between the two statements. If anybody can sort of explain the difference for me, I'd greatly appreciate that.
Thanks!
Comment: Your sentences appear to be of the form:$$\begin{align}&\forall a~\forall b~((\forall x~\mathrm P(a,b,x))\to\mathrm Q(a,b))\tag 1\\[2ex]&\forall a~\forall b~\forall x~(\mathrm P(a,b,x)\to\mathrm Q(a,b))\tag 2\end{align}$$Is this so?
Comment: @BrianO Graham's sentence (2) might mean "for each couple and dog, the couple is a pet owner if the couple owns the dog"...
Comment: @GrahamKemp yep!
Comment: @GrahamKemp The second is more likely $\forall a\,\forall b\,\forall x\,(P(a, b, x) \rightarrow R(a, b, x))$, no? Otherwise, "who talks like that"? :)
Comment: Right, but it might also be, "for every integer a, b, x, if ax + b > 0 then a = 0 or x > -b/a".
Answer: Following Graham's comment and filtering out the $a,b$:
$$\big(\forall x~\mathrm P(x)\big)\Rightarrow\mathrm Q\tag{1e}$$$$\forall x~\big(\mathrm P(x)\Rightarrow\mathrm Q\big)\tag{2e}$$
Sentence $(2\mathrm e)$ asserts that $\ldots,\big(P(-7)\Rightarrow Q\big),\ldots,\big(P(0)\Rightarrow Q\big),\ldots,\big(P(31)\Rightarrow Q\big),\ldots$ are all true ($x$ is varying over its entire domain); equivalently, that if some $P(x)$ is true, then $Q$ is true; i.e., $$\forall x~\big(\mathrm P(x)\Rightarrow\mathrm Q\big)\;\equiv\;\big(\exists x~\mathrm P(x)\big)\Rightarrow\mathrm Q.\tag{2e}$$
In comparison, sentence $(1\mathrm e)$ is a weaker assertion: it is applicable (usefully invoked) in fewer scenarios, since its hypothesis $\big(\forall x~\mathrm P(x)\big)$ is harder to satisfy than $(2\mathrm e)$'s hypothesis $\big(\exists x~\mathrm P(x)\big).$
For completeness: $$\big(\forall x~\mathrm P(x)\big)\Rightarrow\mathrm Q\;\equiv\;\exists x~\big(\mathrm P(x)\Rightarrow\mathrm Q\big).\tag{1e}$$
Comment: For completeness, you should state the assumption that $x$ is not free in $Q$, otherwise your $\equiv$ statements aren't valid. [Their numbers are off: you already used (2e) and (1e).] For the first of OP's sentences, your first (1e), that's probably true of her "...". However, for the second, "For every integer a, b, x if ax+b is even ...",  in most cases "..." probably **does** involve $x$.
Comment: @BrianO 1. My first sentence made clear that the Answer is premised on Graham's suggestion/clarification, which the OP verified to be consistent with her Question's intent. My (1edited) & (2edited) correspond to Graham's (1) & (2).   2. Using (1e) and (2e) twice was intentional, and meant to exhibit the Prenex forms. 3. "$P(x)$" and "$Q$" appearing in the same sentence suggests that $x$ is free in $P$ but not in $Q.$
Comment: Ah ok, I see why you repeated the numbers – a good reason, too. I commented to @GrahamKemp similarly. It's unusual for anyone to say or write, "for all a, b, x, if ax + b is even then a + b is even"  when they mean, for all a, b, "if there is an x such that if ax + b is even then a + b is even". I don't think it's nitpicky: in statements of the form "for all $a, b, x$, if $A$ then $B$", often both $A$ and $B$ involve $x$.

Nested Quantifier placement confusion


rails 5 remove whitespace from string only if it exists

Question: I have a rails 5 app, I have a name field (string) and a compressed name (string)
when a user signs up they enter their company name, i am trying to compress the name like so:
"My Company Name Here" - name
into
"mycompanynamehere" - compressed name
I am using this on the account model as an after_initialize call
  def compress_name
    self.compressed_name = name.downcase.split.join
  end

The problem with this is it just leaves compressed_name as nil if there are no whitespaces in the name field.
Is there a better way to handle this?
Thanks in advance
Comment: Remove the bang `!` on `.downcase!`. And what does "it rolls back on account create" mean? It foils the validation and causes an exception?
Comment: yeah, if there is no white space in the name field, it just wont convert the name and leaves it set to nil in the database.. Ill update the question as i sorted out the rollback issue
Answer: Try below one , tested
2.4.2 :013 > "My Company Name Here".gsub(/\s+/, "").downcase
 => "mycompanynamehere"
2.4.2 :014 > "My CompanyNameHere".gsub(/\s+/, "").downcase
 => "mycompanynamehere"
2.4.2 :015 > "MyCompanyNameHere".gsub(/\s+/, "").downcase
 => "mycompanynamehere"
2.4.2 :016 > "mycompanynamehere".gsub(/\s+/, "").downcase
 => "mycompanynamehere"


How to teach a young child the correct intonation on the violin?

Question: I'm a parent who is teaching my child how to play the violin.
Unfortunately, my child is not consistent
about the placement of his left-hand fingers on the fingerboard.
For example, when my child presses his 3rd finger down
on the A string to play the D note,
it is sometimes too sharp, and other times it is too flat.
Are there any exercises that I can use to help him to get the right intonation?
Our violin teacher had uses stickers on the fingerboard,
but recommended that we remove them since he was getting older.
If I recall correctly, the teacher recommends
not worrying about intonation for the time being,
but letting the problem fix itself when he grows older
and his ear becomes more discerning.
Response to question in comment
Question:
Is he so far off it sounds like a different note, or just enough to bother a good ear? If he stops to think, can he tell you whether he was sharp or flat, or is he completely unaware?
Answer:
That's a great question.
For the first question, the maximum error is about half note off,
i.e. if he is trying to play D, he may play D♯ or D♭.
But sometimes, he is able to play D perfectly
for the entire song of "Twinkle Twinkle Little Star".
For the second question,
I have never asked him if he was sharp or flat.
Now that you mention it,
I should definitely ask him whether he is able to discern
whether he is sharp or flat.
If he is not able to tell,
then I should work on interval training.
Comment: I would suggest you to record exercises for him with MIDI playback for him to play along. You can get some sheet music editor or learn abc musical notation language and record the exercises, then export to .mid format.
Comment: Is he so far off it sounds like a different note, or just enough to bother a good ear? If he stops to think, can he tell you whether he was sharp or flat, or is he completely unaware?
Comment: @Karen That's a great question. See my response in the edited question.
Comment: @ILiketoCode Now that it's been a few years, any tips you can give to a beginner about this problem?
Answer: Since his teacher recommended taking the stickers off, I'm going to assume your son is in the ballpark of the right note, and that if he takes the time, he can tell whether he is sharp or flat. Once a player can get reasonably close by ear, marking tapes won't help get the exact note, and can distract from learning to listen, and on the violin, you get the best intonation by listening to what you're playing.

Play scales at different speeds, and in different rhythms. For at
least one scale a day, have your son focus on intonation until he
sounds better than he did when he wasn't focusing on it. If your son
finds them too boring, look for easy tunes that include runs of 3-5
notes (or more), and play them in keys he knows the scales of. Go
through the scales or tunes slowly enough that he has time to think
about how he needs to correct when he's out of tune.
Have him try playing a scale with his eyes shut, so that the only
    way if he knows he's right is by listening.
Have him listen for ringing tones, where the note you are playing is
    the same as an open string. The D on the A string is one example. It
    will make the D string ring audibly when it is perfectly in tune. Do
    this on any exercise, or any piece.
Play with a drone tone in the background. So if you are playing an
    exercise in D, have a recording of a D note in the background. This
    makes it painfully obvious when you are playing out of tune. You can
    find free MIDI notes online, or you can buy a recording of 10
    minutes Cello drones of each note on amazon or itunes.
If your son can play on 2 strings at once, play scales by fingering the notes, and at the same time playing the open string below. This is the same effect as the drone tone, but takes more skill to execute.

Good intonation is a constantly moving target. Your son might have good intonation for his age and experience, but still sound bad to a better trained ear. You get famous concert violinists who are playing perfectly in tune to an average person's ear who can still hear where they were a hair off on certain notes.
Comment: You are spot on about good intonation being a moving target. I found that my son can discern when the note is quite far off target, and self correct in those cases. I would expect that as he plays more violin and his ear becomes better attuned to differences in pitch, he will self-correct and get closer to the perfect pitches.
Answer: Usually you wouldn't want to remove the stickers until he is beginning to become more accurate on his own.  Removing them only helps if they are inhibiting his ability to learn the correct placements — so if he is all over the map, then he needs more experience learning the exact positions and not less!
His ear is also more likely to develop properly by becoming familiar with the correct notes.  If any note he plays can be sharp or flat and he doesn't hear the difference, it's just going to reinforce bad habits.  As the saying goes, practice doesn't make perfect — it makes permanent.  You have to practice it correctly in order to ingrain it correctly.
One great exercise to help with intonation is interval training, which is essentially hearing two notes played and identifying the interval between them.  It will help intonation by allowing him to recognize when a note does not form a valid interval with a previously-played note, and thus that the fingering or tuning needs correction.
Another trick is to have him take his left hand off the violin, close his eyes, and then attempt to play a note.  Then have him open his eyes and compare visually to the sticker to see how far he's off.  Repeat until he's getting that one accurately, then try a few more.  Come back the next day and try again.  Eventually the sense of distance should be much improved.  You can also have him play one note with eyes open, then move up/down to play another with eyes closed to ensure that the physical sense of the intervals is also learned.
Answer: Have him find his first note before starting to play his piece.  Finding the first note is best done with pizzicato.  You pluck the open string, then place the finger and pluck again.  It is fine for a student at this level for you to politely and gently indicate whether he is too high or too low if he isn't sure.
Do lots of singing.
Play duets together.
Go to concerts and recitals.
Make sure your child's teacher is not allowing poor position.  Technical problems can cause real problems with intonation.
One way to be sure about the technical grounding is by working with a certified Suzuki instructor.  It's not the only way, but if you're not sure what proper technique looks like, that's an easy way of being sure.
Answer: Pitch is really just a cultural convention.  The only important part in my musical opinion is the interval.  This is the distance between notes of a chord.
Even as an adult musician it has taken me a long time to truly begin to grasp the beauty of the octave.  The octave is a pattern that "sounds regular" and "repeats" but with "higher" and "lower" notes.  Really, every sound is different, but they exhibit a natural similarity to our ears so first you can train your child in identifying the equality of the octave.
<code>Play low A then high A
Play low E then high E

Play any sound (not necessarily a 12-semitone even tempered sound aka unconventional)
and play its one-octave up and one-octave down.
</code>
Take time to really listen to their "equality" .. what do they sound like when they line up best?  Is the effect more pronounced at lower or higher tones?
Getting your child to try to imagine what a string is actually doing (resonating very quickly) will begin to unlock the mysteries and magic of tempo.
I believe that it will take some time, so be patient.  Combine theory and practice with your child and have fun.
Answer: Here is what I have tried with my child.
Keep left hand fingers close to the fingerboard
My son tends to open up the fingers on his left hand
when he plays the open E or A string.
When I place my fingers near his left hand
to remind him to keep his fingers close to the fingerboard,
he is more consistent in where he places his left hand fingers down.
Listening to the song
We have a CD of the song played by a professional violinist.
The Suzuki method requires parents
to play the Suzuki CD for 20 minutes each day
to train the children to know how the song is supposed to sound.
Answer: This is a wide topic, but one of the often given advice is to do scales. While scales are useful for sound stability, they are not the faster nor the better way to develop intonation.
In contradiction with the answers here, the right way to develop intonation is by playing two sounds at a time (somewhat covered in Karen's answer, the drone tone section). That means, playing on two strings. Playing on two strings is not that hard, especially for the goal of exercise:
To develop intonation, one should play double stops, with one open string and one finger on the other string.

Play an open D string with a first finger on the A string (B note), adjusting the sixth
With an open A string, play a second finger on the D string (F note), adjusting the third.

Intonation is, by definiton, how a sound sounds in accordance with another sound. A sound by itself, without being in the context of a key, can't be out of tune, there are no tune to begin with. Doing scales will not practice how sounds are relating to other sounds, not unless you already have an advanced hearing for intonation.
One have to teach their own ear what is the correct relation between sounds for each intervals, then one can play in tune regardless of the context.
Comment: This does not answer the OP's concern about the child's fingers not landing in the correct position every time.
Comment: @AlJebr I believe it does, yes. Fixing the intonation implies the finger lands on the correct spot. Adjusting the ear adjusts where the finger lands, by definition.
Answer: Make sure that he is not touching the neighboring strings.  When one listens carefully, one can hear whether the fingered string is combining nicely with the unfingered strings or not.  Of course, that's best hearable when they are actually in unison.  Or if you just play along the neighboring string as a drone.
The problem is that this is a self-control device.  If your kid is not interested in it, you cannot really expect to make him.  If he is not bothered with intonation, you'll likely annoy him with stuff that feels totally academical to him and spoil the fun.
So his teacher is likely right: just give him time and grit your teeth.  At some time it might start bothering him that playing an empty string in some scale will totally disrupt it because it does not fit with the rest.


do two true statements always imply each other?

Question: If A is "1+1=2" and B is "apple starts with a", does $A\implies B$?
Comment: Does this answer your question? [Are all true statements equivalent?](https://math.stackexchange.com/questions/2570160/are-all-true-statements-equivalent)
Comment: In a logic system $A \implies B$ simply means $\lnot A \lor B$.   As the statement "Either $1 + 1 \ne 2$ or Apple starts with A" is certainly true (because apple *does* start with a) then, yes, the statement is true.
Answer: In a word, yes.
This is a language thing - the word "implies," in standard usage, usually means that the two are related causally.
But in mathematics "implies" is a funnier thing. $P\implies Q$ is true whenever $Q$ is true - you don't even need $P$ to be true.  It is also true if both $P$ and $Q$ is false.
The only time it is false is if $P$ is true and $Q$ is false.
Answer: In symbolic logic, if B is true then A-> B is true no matter whether A is true or false.  So if A and B are both true then A->B and B->A are both true.
Outside of symbolic logic we often take "A implies B" to mean "A causes B".  That's whole different matter! A and B can both be true without one "causing" the other.


XSLT 1.0 How to extend with fn (function namespace)

Question: I was wondering how I can possible extend XSLT 1.0 so that I can use functions from fn function namespace at http://www.w3schools.com/Xpath/xpath_functions.asp
I was just told that the system is using MSXML XSLT processor from now on. All my stylesheets were written in 2.0  ... So now I'm stack, nothing is working and don't know how I can use functions for example from fn namespace.
I was wondering whether it will be possible to extend XSLT 1.0 somehow, because I use lots of those functions. Or what do I do now? I'm absolutely lost and frustrated.
Would really appreciate any help!
Thanks a lot!
Comment: An XSLT 1.0 processor like MSXML supports the functions defined in XPath 1.0 http://www.w3.org/TR/xpath/#corelib and in XSLT 1.0 http://www.w3.org/TR/xslt#add-func. If you compare that with what w3schools publishes then you will see that the functions available in XPath 1.0 are a subset of those defined in XPath 2.0. So you can use some of the functions you find on w3schools with MSXML, but of course only those already defined in XPath 1.0, not those newly defined in XPath 2.0.
Basically if you want to work with an XSLT 1.0 processor then using w3schools as a reference is not a good idea.
Answer: If you are stuck with MSXML as your processor, I think your only is to go with option 2 in Obalix's answer, but you will probably have to write the extension functions yourself.
Here is an example of how you might do the Upper Case function. This uses javascript within the XSLT to do the function.
<code><?xml version='1.0'?>
<xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:msxsl="urn:schemas-microsoft-com:xslt"
      xmlns:user="http://mycompany.com/mynamespace">

<msxsl:script language="javascript" implements-prefix="user">
   function uppercase(textToConvert)
   {
      return textToConvert.toUpperCase();
   }
</msxsl:script>

<xsl:template match="text()">
   <xsl:value-of select="user:uppercase(string(.))"/>
</xsl:template>

</xsl:stylesheet>
</code>
What you could do, is put all the script functions in their own XSLT sheet, and include it in all your own XSLT stylesheets.
How complicated this turns out to be, depends on how many XPath2.0 functions you have used.
Comment: @Tim C thanks a lot. I've noticed you declared msxsl namespace (xmlns:msxsl="urn:schemas-microsoft-com:xslt"). I was wondering if you know a good place to read up on MSXML in general, so I can understand it and figure out what I can use... I would really appreciate it! Thanks!
Comment: I don't know how good it is, but you could try this link to it on MSDN - http://msdn.microsoft.com/en-us/library/ms759204(VS.85).aspx
Answer: Well, IMHO, you'r a bit stuck. MSXML, does not implement XSLT 2.0 and XPath 2.0. So basically you are left with three options:

Try to convince you supperiors that they should provide support for another XSLT processor like Saxon.NET.
Reimplement all the functions you need using microsoft's msxsl:script function. This should prove difficult and leaves you with a dependency with the Microsoft parser. Furthermore, it only convers the XPath functions - the XSLT 2.0 functionality is not considered here.
Reimplement your stylesheets using XSLT 1.0.

Personally, I guess that ony option 1 and 3 are feasible.
Comment: @Obalix Thank you. Unfortinately, they won't change the processor. I was just wondering if I can do anything at all so that I can use functions from http://www.w3schools.com/Xpath/xpath_functions.asp at all? Somehow extend MSXML? Sign. I think I'm in a big pickl.
Comment: Well you can look at http://www.exslt.org/ to see whether there is something you can use, however, unless MS decides to incorporate XSLT 2.0 into ther Processor, you are left alone. But, don't be to donwhearted, I've fallen ito the same trap a while ago.


"_blank" target attribute for links in views

Question: I have a custom view that lists a specific content type. I have fields output for each node and have set them to "Link to: Content".
Simply, is there a way to now set the target to "_blank"?
If you are "Rewriting Results" you have the option to specify the target attribute, however I am not rewriting the result (this requires a separate declaration of link path).
Answer:
this requires a separate declaration of link path

If you are talking about node title it doesn't require a declaration of link path. Just leave this field empty and link will be made with default link path (e.g. node/NID).
For other fields you need to override link path. The easiest way is to add nid field and exclude it from display. Then you can use node/[nid] as link path. In this case you need not use link formatter in field settings.
Comment: Hey @Xio tried this checking "Rewrite the output of this field" and "Output this field as a link" and defining "target", however it doesn't apply _blank.
Comment: What version of the Drupal are you using? It isn't required to check "Rewrite the output of this field" checkbox.
Comment: Hey @Xio, using 7. Thanks for your help. Am I looking in the wrong place? I've attached a screenshot of the area. Target option only becomes available when I check  "Output this field as a link" under rewrite results. Seems odd that I need to rewrite results when the field is already linked to Content. It also says "If checked, this field will be made into a link. The destination must be given below."
Comment: I was thinking you are asking about node title. For other fields "Link path" is really required. I've updated the answer.
Comment: Thanks @Xio. Might be worth adding to change dropdown "Link image to:" to "nothing". Else it appeared to interfere with the rewrite link.
Answer: I think more comfortable approach is the answer "target=_blank for links in view"

By using Linked Field module (or one other) and the teaser display in View (Show:Content | Teaser)

By using and configuring fields in View module (not any content's display).


Apagar dados duplicados mais antigos em MS SQL server

Question: Estou com um problema, em uma tabela que tem dados duplicados. Os dados duplicados é identificado através de um ID, em que cada linha tem o identificador e um data, como é que eu posso apagar todos os dados  com mais de 1 registo da na tabela, deixar apenas o registo mais recente?
A base de dados é um MS SQL SERVER, ou seja, o script dever fazer com que, na lista abaixo, elimina as 4 linhas mais antigas:
ID            DATA
17081618585 | 18.02.02 18:42:41
17081618585 | 18.02.02 19:30:41
17081618585 | 18.02.02 20:42:41
17081618585 | 18.02.02 20:42:41
17081618585 | 18.02.02 22:42:42

Comment: no caso iria ficar somente `17081618585 | 18.02.02 22:42:42`?
Answer: Uma abordagem simples é utilizar uma CTE (Common Table Expression) para selecionar os registros que você NÃO quer excluir. Depois disso, é só fazer um DELETE com join com a CTE criada para apagar os registros.
Veja o código abaixo:
with cte as (
    select id,max(data) max_data
    from #teste
    group by id
)
delete t
from #teste t
inner join cte
on  (t.id = cte.id)
and (t.data <> cte.max_data)

A CTE selecione a data máxima por ID. Depois disso, é feito um DELETE na tabela em questão e no join especifica-se que a data a ser deletada deve ser diferente da data da CTE.
Um detalhe: para que isso funcione o campo que armazena a data precisa, necessariamente, ser uma data no SQL Server, ou seja, um campo do tipo datetime ou afim. Se for um campo varchar então o max que está na CTE falhará.
Comment: Solução excelente! Depois disso seria bom criar uma constraint com PK no ID(por exemplo), pra evitar essa situação futuramente já que a tabela não deve ter ID's duplicados.


Highcharts Selection Event

Question: For some reason, I can't seem to get the selection event to work in Highcharts.  Some non-trivial googling/poking around isn't showing me a working sample (even the JSFiddle from them isn't working for me in Mac Chrome/Safari/Firefox).  Here's a quick fiddle to poke at...
http://jsfiddle.net/qwfZ9/3/
Thanks!
Answer: So, much later, I have stumbled across the answer.  Among other things...
Pie charts don't use selection events.  Certainly not the top level "events" selection, at least.  You have to use
<code>plotOptions: {
    pie: {
        events: {
            click: function (event) {
                alert("You clicked on the pie!");
            }
        }
    }
}
</code>
Working fiddle:
http://jsfiddle.net/vL7Q4/1/

Highcharts Selection Event


Code coloring in preformatted text

Question: When adding pre-formatted text in the Markdown editor on main, the text doesn't get coloured even when I explicitly tell it that it is PHP code like this example:
<code><!-- language: lang-php -->

    public function someFunction(){
        $variable = Mage::getModel('router/somemodel');
    }
</code>
Is this a bug? Or is code colouring only available on select SE websites?
I'm not sure what to tag this post with since it's probably by design and not a bug. So I tagged it with discussion.
Answer: IIRC this is a limitation when the site is a BETA.
Comment: I sure hope so!
Comment: I would definitely like to see code colouring even in Beta. I feel it devalues the site somewhat when you have a block of code that's borderline unreadable.
Comment: Me too, I vote for code coloring(for PHP/HTML, XML, JS & SQL) to be enabled asap.

Code coloring in preformatted text


Do posterior probability values from an MCMC analysis have any use?

Question: I need to estimate the Bayesian posterior of my model parameters ($\theta$) for some observed data ($D$), given a likelihood $P(\theta|D)$, and assumed priors $P(\theta)$:
$$P(\theta|D)= \frac{P(\theta|D)\; P(\theta)}{P(D)}$$
I use a MCMC algorithm which as far as I understand samples the unnormalized posterior (edit: I was wrong, the draws are taken from the full posterior).
After the MCMC is done, I can construct the probability density function for each $\theta_i$ in my set of parameters $\theta$ (from which I can obtain the necessary statistics: mean, median, confidence intervals, etc.) but I also have a rather large set of unnormalized posterior values.
As far as I understand, these values are not used at all in the analysis of the model parameters. Does this set of unnormalized posterior values have any use at all, or are they simply discarded?
Comment: The values drawn from posterior are not unnormalized. It is just that the algorothm does not need $P(D)$.This paper (http://www.tandfonline.com/doi/pdf/10.1080/00031305.1995.10476177) by Chib and Greenberg provides a good understanding of the algorithm.
Comment: Can you explain a little more what are the unnormalized values? They are not unnormalized values. These values have been extracted from $P(\theta|D)$ without knowing $P(D).$
Comment: Oh, I'm just learning about MCMC and it was my understanding that the values drawn from the posterior were unnormalized. Do you have any article/link where this is made clear?
Comment: Thank you @AbhinavGupta! My question (edited to reflect this correction) stills stands though. What do I do with the set of posterior probability values?
Comment: I have added a comment to Srikant's answer. Let me know if it is still not clear.
Answer: I have to disagree with the earlier answers that the values of the (unnormalised) posteriors at the MCMC simulations are not of any use. They actually provide a much more refined view of the posterior than an histogram, especially in multiple dimensions. One direct illustration is the construction of the HPD region: the easiest way to construct an HPD region at level $\alpha$ is to take the same percentage on the MCMC simulations with the largest [unnormalised] posterior values and to construct a convex envelope of these simulations.
Comment: I think you are right that the unnormalized posterior might be used for constructing HPD regions with more accuracy than from MCMC samples. But the question is do I really need it after MCMC sampling?
Comment: Now I'm confused. Are the posterior probability values normalized or not?
Comment: The exact values of the posterior density at the $\theta_i$'s are know up to a constant, the inverse of the marginal density at the observation(s) $D$, $m(D)$.
Comment: The probability density that you estimate from MCMC sample will be normalized. I have edited my answer to include Xi'an's point.
Comment: @AbhinavGupta: Can you propose an efficient way of computing an HPD without this trick? I'd be very interested in the alternative.
Comment: @AbhinavGupta: The probability density estimated from an MCMC sample is not the true posterior density, while the product prior x likelihood is, up to a constant. The estimated density reflects the outcome of the MCMC, including potential failure to visit some regions of the space and likely high correlation in the simulated values.
Comment: @ Xi'an No, I am not aware of any better way of doing it. Therefore, I have edited my answer.
Answer: The values obtained after MCMC is a sample from the posterior $P(\theta|D)$. You have to ensure that you draw a large enough sample so that the sample itself can be considered a population. Now assuming that the sample is indeed the population, you can do anything with it that you do with the probability density. For example, you can find out the credible-region by finding $2.5^{th}$ and $97.5^{th}$ percentile or you can compute the mean of $\theta|D$.
Now, you can use this sample from posterior to estimate the probability density $P(\theta|D)$ which is usefull in constructing High Posterior Density (HPD) region. I cannot think of any other application where you will need probability values themselves. It is redundant to have both the population and its probability distribution because they provide the same information.
For your doubt regarding the normalization, you can refer to the article by Chib and Greenberg: http://www.tandfonline.com/doi/pdf/10.1080/00031305.1995.10476177. This article helped me understand the MCMC very well.
Answer: The draws are from the normalized posterior density. The reason why we write the posterior as proportional to the unnormalized posterior density is that the normalizing constant does not matter and drops out of the computations. Thus, the draws from an MCMC sampler are from the normalized posterior density.
Comment: I've edited my question to remove the *unnormalized* part. The question is more about what to do with those values, rather than whether they are normalized or not.
Comment: Oh! If I understand your question right then the answer is no. I cannot think of any application where you will need probability values themselves. It is redundant to have both the population and its probability distribution because they provide the same information. Does this answer your question?
Comment: These values describe your posterior distribution. You can use these values for whatever you use posterior for. For example, you can get 95% credible-region by taking $2.5^{th}$ and $97.5^{th}$ percentile, you can get mean of $\theta|D$ by taking sample mean. .
Comment: But the statistics for the $\theta$ parameters are obtained from the histogram of the resulting parameter values (after the MCMC is finished), not from the posterior probability values themselves (to be clear: I'm talking about the *probability values*, not the *parameter* values). Perhaps I'm not understanding something here?
Comment: You use MCMC to get a large enough sample from posterior and then you treat this sample as if this is the whole population. Therefore, the histogram is the actual probability density function of $\theta|D.$
Comment: Yes, precisely. But these leaves me with a large set of *probability values* that I am not using. I'm only using the sampled *parameter values*, to construct its probability density function.
Comment: That's why it is crucial to get a large enough sample so that the sample is indeed the population.
Comment: I understand that @AbhinavGupta. The sampled *parameter values* are used to approximate the probability density function of said parameter. But the MCMC also gives you sampled *probability values*. My question is about whether these *probability values* are used for anything.
Comment: Would you like to turn your comment into an answer?


Why FIFA didn't prevent the potential cheating that may arise when the lasts of group matches are not played simultaneously?

Question: Referring to the question here, the first and second paragraph.

On Thursday at 2pm GMT, the football matches for group H of the World Cup 2018 will begin. By 4 pm GMT, the fate of that group will
  be decided.
Let us assume that Japan comes first and Colombia comes second (not an
  unlikely outcome, actually), both hence qualifying for the second
  round. Now, at 6pm GMT, the matches of group G begin. Belgium and
  England are already qualified for the next round, but they play
  against each other in order to decide who goes first, and thus, to
  decide whom are they to play in the next round.

The problem with this arrangement, as mentioned in the question, is that England and Belgium can be unsportsmanlike in order to receive a more favorable opponent in the next round.
I know that the teams involved in unsportsmanlike behavior can be investigated and punished, but still, why FIFA not just decided to start all four matches simultaneously? This would reduce the possibility of deliberate losing.
Another alternative solution is that FIFA can consider to let all the qualifying teams to draw the lots again after all group matches complete, so that no one can "choose the opponent", why this is not done?
Comment: Related: [Disgrace of Gijón](https://en.wikipedia.org/wiki/Disgrace_of_Gij%C3%B3n). This kind of unsportsmanlike play in the last game of the group match happened at the 1982 World Cup. They addressed it partially by at least playing the last matches in each group simultaneously. Taking it one step further and playing last matches of each group simultaneously would be a good idea, but there's the money vs fair play tradeoff.
Comment: Iceland were theoretically the preferred opponent for England at Euros 2016...
Answer:
why FIFA not just decided to start all four matches simultaneously?

Because that reduces the television audience. Having two matches at the same time is bad enough, four matches just makes it worse.
Also note that in this case, it's not the round of 16 game (which is group G vs group H) which is the issue, but the quarter-final. You'd have had to have played eight matches (everything from groups D, E, G and H) to avoid the issue.

FIFA can consider to let all the qualifying teams to draw the lots again after all group matches complete, so that no one can "choose the opponent", why this is not done?

Because it's awful for fans. As (say) an England fan, at the moment I know that England will play their round of 16 game in one of two locations, and the companies arranging travel / hotels are able to handle two possibilities for the match. With a random draw, England could end up in any of eight locations, which would make it much harder for fans and travel companies to arrange.
Answer:
Why FIFA not just decided to start all four matches simultaneously?

This one is easy as already answered in the other answer. By forcing 3rd round matches of the same group to be played simultaneously FIFA is already losing some revenue. This loss would be even greater if FIFA forced the matches across 2 groups to be played simultaneously.

FIFA can consider to let all the qualifying teams to draw the lots
  again after all group matches complete, so that no one can "choose the
  opponent", why this is not done?

The main reason for not doing that is the rest time. As a tournament, FIFA World Cup (which lasts only 32 days) doesn't have the same flexibility as other tournaments with similar format (e.g. UEFA Champions League which spans over 9 months).
The teams which qualify from groups A and B are expected to play their round of 16 games earlier than the ones from C and D, because teams from A and B finish their last group matches one day before than teams from C and D. The difference will become even more crucial if a team qualified from group A or B would be drawn against a team from G or H. Then the team from A or B would have had 3 rest days more than a team from G or H. In a tournament with such a busy schedule 3 rest days can be a decisive factor. This is the main reason why FIFA World Cup doesn't use drawing of lots during the tournament like UEFA Champions League and teams which finish their last group matches on the same day play against each other in the round of 16.
Answer: Bear in mind that the winner of group A plays the runner-up in group B and vice-versa.
It's unlikely that you'd prefer to play the group winner over the group runner-up (although I guess it's possible) - so you're unlikely to want to lose the match.
A draw might be enough to keep you at the top, and your opponent might decide to play for the draw also, keeping runner-up rather than risking a loss and not continuing - that's hardly cheating - although it'd make for a tedious game(*)
It's hard to think of a scenario where both teams get the best outcome for themselves with the same result
..and of course, money.
(*) For those who don't find all football tedious!
Comment: "It's unlikely that you'd prefer to play the group winner over the group runner-up (although I guess it's possible) - so you're unlikely to want to lose the match." While somewhat unlikely, this is *exactly* the situation being discussed here - and it's not the first time this has happened in various sports - see the badminton example from my answer.
Comment: *"It's unlikely that you'd prefer to play the group winner over the group runner-up (although I guess it's possible) - so you're unlikely to want to lose the match."* ... and that is exactly what happened in the England vs Belgium farce, where both sides sent their "B" teams and tried losing while pretending to win. The Japan vs Poland match was only slightly better.
Comment: ..it's a high stakes game though, losing so you play the team you think is weaker, despite their winning their group. The reason to send the B team is because the cost of losing is less than the benefit of resting, lower injury risk of the A team


CKEditor, TinyMCE or any Rich Text Editor in jQuery popup

Question: I am developing an ASP.NET web application in which I am going to use CKEditor or any other rich text editor in the jQuery pop up, but the problem is this, I don't know anything about the jQuery pop up. I have visited this link but can't understand.
Answer: You can use jQuery UI Dialog box. To do this, just include jQueryUI in your html.
<link type="text/css" href="css/ui-lightness/jquery-ui-1.8.17.custom.css" rel="stylesheet" />

You can then make the dialog using jQuery as follows:
var txt = '
 <textarea id="myTextField"/>
';

var $dialog = $(txt)
.dialog({
    modal: true,
    buttons: {
        "Add Annotation" : function() {
            // My function definition
            $( this ).dialog( "close" );
        },
        Cancel: function() {
            $( this ).dialog( "close" );
        }
    },
    close: function() {
        var editor = CKEDITOR.instances['myTextField'];
        if (editor) {
            editor.destroy(true);
        }
    }
});

$('#myTextField' ).ckeditor();

Answer: If you want use CKEditor for Asp.net follow http://ckeditor.com/blog/CKEditor.NET_released.


Is a parameter-independent support sufficient to belong to an exponential family?

Question: From Wikipedia (emphasis mine):

As a counterexample if these conditions are relaxed, the family of uniform distributions (either discrete or continuous, with either or both bounds unknown) has a sufficient statistic, namely the sample maximum, sample minimum, and sample size, but does not form an exponential family, as the domain varies with the parameters.

Does this mean that if the support (not domain) of a particular distribution does not vary with its parameters, then it is a member of an exponential family of distributions?
Comment: no this is not true, see the Student's t family.
Answer: NO
A $t_{\nu}$ distribution has support on all of $\mathbb R$, no matter $\nu$.
However, $t_{\nu}$ does not have a moment-generating function, which is a requirement to be an exponential family.


how to insert the See All link in a drupal view block

Question: i created a  News block that display only 3 lasted news, and i want create a button "See All News"
how i can do it ?
Comment: thanks an how i do the link "read more" for every news in block ?
Comment: i have 6 news , i created a view block called "News block view" , this bloock display 3 lasted news , i would create a link in the footer of the block called "See all news" this link redirect me in the view page of all news , i want create a link "read more" in every news in the block , you understand?
Comment: yes read more for every news in block
Answer: In the footer section of the view add a global text area with the link of the See all news.
STEP 1:

STEP 2:

STEP 3:

Once you are done adding a field in the footer, save the view and the See all news link would work as expected.
For creating the Read more link

Go to the body field of the news.
In the Rewrite Result, you have a checkbox "Trim this field to a maximum length".
Once you check the checkbox, you have the option to "Add a read-more link if output is trimmed.".
Add the Read more text and use the [path] token for getting the path of the node.
Save the view and the Read more link would be there for all the news that you have.

Adding an image to help you in a better way:
Comment: thank you bro , but i want also create a "Read more" link for every news
Comment: I have updated my answer.


Optimize code multiple if else statements

Question: I have a piece of code that looks pretty ugly. I'm trying to compare a single 12 bit data in hex to see if it is any of 0xff8 to 0xfff. The code returns true if it fits any of the numbers in the said range. Any suggestions? Thanks!
<code>/******************************************************************/
/* summary: Checks if the cluster is the last cluster in a file.  */
/* return: returns 1 if true and 0 if false                       */
/******************************************************************/
int lastCluster(unsigned int cluster){
    /*Compares the values of the cluster. The cluster is the last cluster in a
    file if the cluster has a value of 0xff8-0xfff.*/
    if(cluster == 0xff8){
       return (1);
    }
    else if(cluster == 0xff9){
        return (1);
    }
    else if(cluster == 0xffa){
        return (1);
    }
    else if(cluster == 0xffb){
        return (1);
    }
    else if(cluster == 0xffc){
        return (1);
    }
    else if(cluster == 0xffd){
        return (1);
    }
    else if(cluster == 0xffe){
        return (1);
    }
    else if(cluster == 0xfff){
        return (1);
    }
    else{
       return (0);
    }
}
</code>
Answer: You can combine these into a single test
<code>if (cluster>=0xff8 && cluster<=0xfff)
    return 1;
return 0;
</code>


drop independent random variables in conditional expectation expression

Question: Is the following true for discrete random variables $K,Y,X_1,...$ where $K$ is independent of $\sigma(Y,X_1,...)$?
$$E[\sum_{i=1}^K X_i | K,Y] = \sum_{i=1}^K E[X_i|K,Y] = \sum_{i=1}^K E[X_i|Y]$$
Intuitively it seems ok, but I am lacking the rigorous argument. We only know when to drop a condition in conditional probability expressions like $P[X_i|K,Y] = P[X_i|Y]$.
Thinking of independence as "$K$ doesn't tell us anything about $Y,X_1,...$" should then also allow to drop the condition in the conditional expectation. Is it also rigorously speaking true?

draft (author is unsure about the following try):
Let's consider the factorization $E[\sum_{i=1}^K X_i\ |\ K,Y] = \underbrace{E[\sum_{i=1}^K X_i\ |\ (K,Y) = (\cdot,\cdot)]}_{(1)} \circ (K,Y)$.
Where we obtain (1) by
$$E[\sum_{i=1}^K X_i | K=k,Y=y] = \sum_{i=1}^k E[X_i|K=k,Y=y] = \sum_{i=1}^k E[X_i|Y=y]$$
Taking together we have
$$E[\sum_{i=1}^K X_i\ |\ K,Y] = \sum_{i=1}^K E[X_i|Y]$$
Comment: Another related example: $E[f(X_n)|X_1,...,X_n] = E[f(X_n)|X_n]$ should just be covered by the Markov property for $(X_i)_{i \in \mathbb{N}}$. So here are conditions dropped. So the overall question is, under which circumstances conditions may be dropped..(I do not want to solely base it on my intuition.)
Answer: It might help to rewrite the random sum as
$$
S=\sum_{k=1}^\infty\mathbf 1_{K\geqslant k}\,X_k.
$$
Since every $\mathbf 1_{K\geqslant k}$ is measurable with respect to $\sigma(K,Y)$,
$$
E(S\mid K,Y)=\sum_{k=1}^\infty\mathbf 1_{K\geqslant k}\,E(X_k\mid K,Y)=\sum_{k=1}^KE(X_k\mid K,Y).
$$
This does not use the independence argument. All that is needed is that, for every $U$ measurable with respect to the sigma-algebra $\mathcal G$ and every $V$,
$$
E(UV\mid\mathcal G)=UE(V\mid\mathcal G).
$$
To go further, note that, for every sigma-algebras $\mathcal G$ and $\mathcal K$, if the sigma-algebras $\mathcal K$ and $\sigma(\sigma(X),\mathcal G)$ are independent, then $E(X\mid\mathcal G,\mathcal K)=E(X\mid\mathcal G)$.
Under the hypothesis that $K$ is independent of $(Y,(X_k)_{k\geqslant1})$, one can apply this general result to $X=X_k$, $\mathcal G=\sigma(Y)$ and $\mathcal K=\sigma(K)$, getting
$$E(X_k\mid K,Y)=E(X_k\mid Y),$$ for every $k$. Thus,
$$
E(S\mid K,Y)=\sum_{k=1}^KE(X_k\mid Y).
$$
As a final caveat, note that if the random variables $(X_k,Y)$ are identically distributed, then $E(X_k\mid Y)$ does not depend on $k$, for example $E(X_k\mid Y)=E(X_1\mid Y)$ for every $k$ hence $$E(S\mid K,Y)=K\,E(X_1\mid Y),$$ but that the hypothesis that the sequence $(X_k)_{k\geqslant1}$ is i.i.d. is not enough to guarantee this.
Comment: Thanks, that simply shows this step rigorously! I like that more than solely rely on my intuition. I still need to figure out the second part, i.e. under which circumstances conditions may be dropped (also with a non-intuitive reasoning).
Comment: The second part in my post? This is a basic property of conditional expectation.
Comment: Sorry, I was inprecise. I meant the second part in my post, where the condition is being dropped. I think under the conditions stated it should be correct to drop $K$. I wonder when this is rigorously justified and not solely by intuition (also note my comment on my question).
Comment: Finally got what you meant (sorry to have been slow), see Edit. You might want to turn intuition into rigor about conditioning matters, by reading the small and excellent book *Probability with martingales* by David Williams.
Comment: Not a problem at all. I should be sorry for being unclear! Thanks for both, the answer and the hint for the book! (Aside: is there something about my comment on my own question, i.e. Markov property? I think it might be better not to start another question on that penny.)
Comment: I fail to see a link with Markov property. Note that $f(X_n)$ is $(X_1,\ldots,X_n)$-measurable hence $E(f(X_n)\mid X_1,\ldots,X_n)=f(X_n)$ is obvious.
Comment: Oh, sorry, I meant: $E[f(X_{n+1})|X_1,...,X_n] = E[f(X_{n+1})|X_n]$ under Markov condition?
Answer: What is true (and it's basically nonsensical to give a 'proof' unless you have had the measure theoretic definition of conditional expectation) is that under your hypotheses, $E(X_i|K,Y) = E(X_i|Y)$, which your intuitive grasp of the concepts involved should 'justify'.
With this in hand, we can prove the following result, which is similar to the one above (but I will assume all the $X_i$'s are identically distributed to get the nice-looking result). I think this might interest you as it has a similar form to your conjecture above.
$E(\sum_{i=1}^K X_i | K,Y) = E(\sum_{k=1}^{\infty}1_{K=k}\sum_{i=1}^k  X_i |  K,Y)$
$= \sum_{k=1}^{\infty}E(1_{K=k}\sum_{i=1}^k  X_i |  K,Y)$
$= \sum_{k=1}^{\infty}E(1_{K=k}) \sum_{i=1}^k E(X_i |  K,Y)$
$= \sum_{k=1}^{\infty}P(K=k) \cdot  k \cdot E(X_i|Y)  $
$= \sum_{k=1}^{\infty}kP(K=k)E(X_1|Y) $
$=  E(X_1|Y) \sum_{k=1}^{\infty}kP(K=k)$
$= E(K)E(X_1|Y).$
In the first equality is just partition the sample space over possible values of $K$; in the second a take a deterministic sum outside the expectation (this would require some justification using dominated convergence); in the third I use the fact that the random variable $1_{K=k}$ is $K$-measurable (and I use a property of conditional expectation called 'taking out what is known'); in the fourth I rewrite the expectation of an indicator as a probability, and use the independence result mentioned above; in the fifth I use the identical distributions of the $X_i$; in the sixth I take out the constant factor $E(X_1)$; and in the sixth I use the definition of expectation for a random variable $K$ taking values in $\{1,2,3,...\}$.
Comment: My intuitive grasp does not justify $E(X_i|K,Y)=E(X_i)$. Again, consider $X_i = Y + N_i$ where $N_i$ are iid random variables. My intuitive grasp would justify to drop the condition on $K$ then $E(X_i|K,Y)=E(X_i|Y)$ like for coniditional probabilities $P(X_i|K,Y) = P(X_i|Y)$.
Comment: The step leading to the $P(K=k)$s is wrong.
Comment: Yes, thanks, you are right. @morningthought you are right, this is what I meant (and what I use now in the edited post).
Comment: @Frank Thanks, it seems the first step of my question can be made rigorous rather simply. I still need to figure out the part which is appealing to "intuition" but not yet rigorously clear to me..
Comment: By the way, the computation is still wrong.


Compound field that includes a file field

Question: I'm trying to figure out how to create a custom compound field, but I'm not quite sure how to add a file field to it.  There are plenty of tuts on creating compound fields that are comprised of text fields, but I can't find any that talk about combining text and file fields.  I guess the main problem is that I don't understand how the 'schema' function would work, since it refers to Drupal data types, but the data uploaded via the file field won't be stored in the Drupal database, but rather stored on disk, as any other uploaded file would be.
Can someone point me in the right direction?
Answer: A file field is an entity reference field pointing to the File entity (or in D8.4 to the Media entity). To build such a file field extend FileItem (which parent is EntityReferenceItem). An example for this would be the image field ImageItem, which is a compound field adding properties like title, alt, height and width:
ImageItem::propertyDefinitions()
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    unset($properties['display']);
    unset($properties['description']);

    $properties['alt'] = DataDefinition::create('string')
      ->setLabel(t('Alternative text'))
      ->setDescription(t("Alternative image text, for the image's 'alt' attribute."));

    $properties['title'] = DataDefinition::create('string')
      ->setLabel(t('Title'))
      ->setDescription(t("Image title text, for the image's 'title' attribute."));

    $properties['width'] = DataDefinition::create('integer')
      ->setLabel(t('Width'))
      ->setDescription(t('The width of the image in pixels.'));

    $properties['height'] = DataDefinition::create('integer')
      ->setLabel(t('Height'))
      ->setDescription(t('The height of the image in pixels.'));

    return $properties;
  }

The properties for the referencing part are inherited from the parent.


Ordering by taxonomy field ascending but leaving those node without taxonomy at the bottom

Question: I have a View of products (nodes). They have taxonomy associated, and I am displaying the taxonomy first and ordering by taxonomy ascending. However, I would like to have all with taxonomy ordered first, but I find that the View shows first those without taxonomy, and later those with taxonomy, in this case in the correct order. How could I indicate the View that it must reserve those without taxonomy for the last, i. e.
<code> A Taxonomy
   - Product 1
   - Product 2
 B Taxonomy
   - Product 3
   - Product 4
 ...
 Z Taxonomy
  - Product 5

  -- Products with No taxonomy -- (this message does not display, it is only for clarification here)
  - Product 6
  - Product 7
</code>
...
Answer: My suggestion is to modify your main view to list only Product nodes with a taxonomy term selected, then use an attachment to your main view that lists Product nodes with no taxonomy term. The attachment would be displayed after your main view.
Steps
1. Filter your main view to list only Product nodes with a taxonomy term value
In your main view's configuration, under Filter Criteria, add a filter for your taxonomy term field (choose either dropdown or autocomplete), and select "Is not empty (NOT NULL)".

2. Create the attachment that lists Product nodes with no taxonomy term value
Add an Attachment display to your view.

Under Attachment settings, set Attach to to your main view display (in this example the main view is Page), and set the Attachment position to After.

In the attachment display's Filter Criteria, change the taxonomy term filter to "Is empty (NULL)". Make sure to override this setting for the attachment display only or it will apply to the main view as well.

Note about the attachment header
Your attachment view will be displayed right after your main view, so you may want to add a Header to the attachment (make sure to override to the attachment display only).

In this example I used a Text area.

Alternatively, you could add a label to the taxonomy term field. Make sure to override this setting for the attachment display only or it will apply back to the main view.

Results
Your main view should now list your Product nodes by taxonomy term in ascending order, and your Product nodes with no value selected for the taxonomy at the bottom of the list.
Comment: Thank  you very much, this is way more elegant that the two ideas I had in mind: modifying the SQL query adding the NULL condition or creating a new vocabulary which would be opposite of the main taxonomy vocabulary, to group those without taxonomy and order by those two fields. Elegant solution, yours.
Comment: You're quite welcome! Modifying the SQL was a thought I had as well. Thank you for the kind words!


Android App Content Indexing

Question: I am confused a little bit about app indexing.
First of all there is ability for android app to handle link to your website to open inside app, called deep linking. Just describe correct intent filters in manifest and handle calls inside activity and it is all.
But there is ability to indexing app content by Googlebot. In this way we use site to specify what to index, and after all there will be app pages on google search.
My question is: it is enough just to specify association site with app on sitemap or in  tags on pages to show my app pages in google search, or it is strictly recommended to use FIrebase App Indexing for this.
And another one question is: documentation says
"Typically, you control how Googlebot crawls publicly accessible URLs on your site by using a robots.txt file. When Googlebot indexes your app content, your app might make HTTP requests as part of its normal operations. However, these requests will appear to your servers as originating from Googlebot. Therefore, you must configure your server's robots.txt file properly to allow these requests." (at the bottom of page https://developer.android.com/training/app-indexing/enabling-app-indexing.html#robots)
How does Googlebot indexing pages under the hood, why it tries to go to blabla/api (mb needed to my app implementation) if it just goes through the site and its association, of it launch my app and do something under the hood?
Answer: I haven't found information about how Google indexes the apps, but apparently it performs some checks on published APKs in Google Play while indexing.
In Google Search Console's "Fetch as Google" section for your app, where you can test your deep links, it displays the following message:

Fetch results don't reflect the following crawl errors: First click
  free violation, back button violation, or content mismatch violation.

So apparently Google checks your app while indexing it, to prevent developers tricks and ensure you use App Indexing as intended: to provide your website's content, but in your app.

Android App Content Indexing