Funny(?) Probability Problem

Question: So I ran accross the following problem today on a forum:

"In an attempt to reduce male birth rates, feminists have passed a law
  which forces families to stop having children after their first male
  child. After this law is passed, what is the expected ratio of male
  children to female children?"

It's unclear whether families are supposed to continue having children until their first male child or if they may stop at any earlier point, but let's assume the former. Let's also assume that everybody obeys the law, and that either sex has an equal chance of being born.
I thought I had a simple solution, because the problem is logically equivalent to the following process:

Generate N infinite random sequences of boys and girls
Cut each sequence after the first occurrence of a boy
Concatenate the results and measure the ratio of boys to girls

This is equivalent to generating a random sequence of boys and girls by stopping at each boy but then continuing again (up to N times), so the only difference from a normal random sequence is that this sequence always ends with a boy. However, if N grows to infinity, it seems like this last element (which can never be reached) becomes irrelevant, so the ratio of boys and girls should be 1:1 like in a normal infinite random sequence. This seems perfectly logical to me, but a few people kept insisting that it is wrong, ranting about "biased estimators" and claiming that the real ratio will be biased in favor of females.
Is my reasoning flawed? If so, why?
[EDIT]
Contrary to some suggestions, I don't think this question is a duplicate. It asks about the validity of a particular approach to solving the problem, not just for a solution.
Comment: I think this is an interesting question that would be better off without the portrayal of feminists as authoritarians who want a female dominated society. I don't want to start a debate on the merits of feminism, but the question as stated currently takes a political stance *against* feminism.
Comment: Can we take biology into account? Because if the probability of a boy being born for any father indeed is $0.5,$ your reasoning is correct. In reality, however, the chromosome passed by the father determines the gender of the child. In some cases, the father only passes the X chromosome, resulting in only female children being born. As soon as one boy is born (50% probability for a father able to pass both X and Y chromosomes), its father can no longer reproduce. This gives fathers passing only the X chromosome more chances to reproduce, hence resulting in more daughters being born.
Comment: Well, your approach actually doesn't back up your claim (because it leaves out most relevant details dealing with the probability distribution). It's more like an intuitive reasoning than a valid proof. That's why I deliberately didn't mention it in my first comment. (This isn't meant to be a criticism. It's fine to argue this way to get an intuition but it's far from a proof.)
Comment: "[..] because the problem is logically equivalent to [..]"
Comment: @ZachMcDargh: it also portrays feminists as incompetent and mathematically clueless, because I'm quite convinced the result is still a 1:1 ratio. Not every joke is a strong political statement.
Comment: Well, all of it. But you force me to make it sound like I take any issues with your outline - which I don't.
Comment: If you actually want to prove this you first have to establish a suitable probability space and then show that your claimed transformations (which do in fact work) actually work for this space. But, assuming that you have at some point taken a probability course, you already know that. So I really don't see the point in arguing with me here. The beauty of mathematics is that we have proofs and don't merely rely on opinions - stated on the internet or elsewhere.
Comment: Instead of "If this law is passed" it should say "If this law is obeyed". The rate of compliance with the one-child policy in China was fairly low, if I'm not mistaken. I've heard the Chinese census has a huge undercount because couples who violate the policy report falsely that they have only one child. (I seem to recall that it's been changed to a two-child policy.)
Comment: This same question appears on stats (dot) stackexchange (dot) com: https://stats.stackexchange.com/questions/93830/expected-number-of-ratio-of-girls-vs-boys-birth/93890#93890
Comment: Did you search for this?  It's been asked _many_ times before: https://math.stackexchange.com/questions/20426/ https://math.stackexchange.com/questions/116706 https://math.stackexchange.com/questions/218674
Comment: In both cases the rate of birth will be unaffected (unless like @jvdhooft we take into account that the relevant random variables in reality are not actually independent).
Comment: @Stefan: if my approach is correct, then almost any condition for cutting the sequences at step 2 would work, including "when the male:female ratio is greater than 1:100".
Comment: @Stefan: Why isn't it sufficient to show that the sequence generated with this approach is equivalent to a normal infinite random sequence of boys and girls?
Comment: Well, that's precisely what you want to show - but didn't do.
Comment: @Stefan: which part of my argument do you consider to be a non-sequitur?
Comment: @Stefan: Simply insisting that I haven't proven anything doesn't prove anything. What's the first leap that you consider unjustified?
Comment: @Stefan: Do you agree that "generate N infinite random sequences of boys and girls, cut each sequence after the first occurrence of a boy" is trivially equivalent to "take N families and have each one make children until the first boy is born"? Or does this need some further logical justification? Or is it not sufficiently clear that concatenating the sequences is logically equivalent to considering the children of all N families?
Comment: There is a small but positive probability of no female children whatsoever, in which case the ratio of male children to female children is infinite. Thus the expected ratio of male to female is infinite. Did you mean to ask about the expected proportion of children then are male? Or about the ratio (expected number of male children) / (expected number of female children)?
Comment: @JulianRosen: I didn't formulate the problem, but from what I understand, it's asking to find which number (expected number of male children) / (expected number of female children) approaches as the population grows.
Comment: Some of the answers (including mine, which I suspect is wrong) assume couples keep having children as long as the law allows them to. One should consider that the probability distribution of the number of children might differ from that.
Comment: @MichaelHardy: While it's unclear in the original problem statement, the question does state that you can assume couples keep having children until they have a boy.
Comment: Biology is dumb
Comment: @user3026691 I'm not sure how that's an argument that this joke is apolitical; you've just made it sound even more political, and pointed out that it relies on sexist stereotypes as well. If you consider that appropriate, by all means, leave the question as it is, but I have voted it down.
Comment: @ZachMcDargh: I didn't say the joke was apolitical. I said the joke is... you know... a joke. If you're so triggered by it that you have to vote the question down because you feel personally insulted by it, be my guest.
Answer:
families are supposed to continue having children until their first male child

Possible families
b (p = 0.5)
gb (p = 0.25)
ggb (p = 0.125)
gggb (p = 0.0625)
ggggb (p = 0.03125)
gg.... (p = 0.5^length)

So every family will always have exactly óne boy for sure (total_p=1). But let's prove that.
Girls
The amount of girls you have is basically:
0.5 * 0
0.25 * 1
0.125 * 2
0.0625 * 3
0...... * 4

The extra amount of girl per n is 0.5^(n+1) * n. Summing this formula:

Boys
The amount of boys you have is similar:
0.5 * 1
0.25 * 1
0.125 * 1
0.0625 * 1
0...... * 1

So the extra amount of boy per n is 0.5^(n+1). Summing this formula:

So the ratio is 1:1!
Comment: @D.F.F OP assumes "families are supposed to continue having children until their first male child"
Comment: the policy does not imply every family having one boy (they can stop before eg at: gg)
Comment: Oh you are right
Comment: Thanks for spelling it out; for some reason I thought they'd always have at least as many boys as girls
Answer: A birth is either a new male or a new female, each with probability $1/2$. This is clearly the case regardless of laws or policies, so by linearity of expectation the expected ratio of males to females in the population will remain $1:1$.

Edit:
If you disagree with the minor simplifying assumption that boys and girls are equally likely, just replace $1/2$ with some fixed $p$ and $1-p$, and $1:1$ with $p:(1-p)$.
Here is some JavaScript code to simulate this for $1$ million families:
var heads = 0;
var tails = 0;
for(var i=0; i<1E6; i++){
   var gotTails = false;
   while(!gotTails){
      if(Math.random() < 0.5){
         heads++
      }
      else{
         tails++;
         gotTails = true;
      }
   }
}
console.log(heads + "," + tails);

Comment: Is "got tails" a euphemism?...
Comment: Your code seems to match my argument about concatenating sub-sequences of random sequences, but I don't quite get the linearity of expectation part. Can you elaborate on that?
Comment: Indeed, assuming that every family includes a boy, this holds.
Comment: @user3026691 If we place a value of $1$ on heads and $0$ on tails, then each fair coin flip has expected value $0.5 = 0.5(1) + 0.5(0)$. The expected value of a sum of random variables is the sum of the expected values, always, so here the expected value of the sum is just $0.5$ times the number of flips. In the original example, this means that since each birth is equally likely to yield a boy or a girl, across all $N$ births we expect $N/2$ boys and $N/2$ girls.
Comment: @YvesDaoust That assumption isn't necessary
Comment: I'm going with this answer because your code illustrates very simply the point I was trying to make and confirms that the expected ratio is 1:1.
Answer: The law will change the sexual habits of people and the number of children born, but it will not change the laws of nature. In the assumed model these are as follows: The sex of a child is determined at the moment of conception, and if conception takes place the probability that the child is a boy is ${1\over2}$, independently of social circumstances.
Comment: This also shows that the reasoning used by OP is not flawed.
Answer: I understand the instinct to argue against you but you are right, the ratio should remain 1:1. For an intuitive reason why: consider the before and after for families with three children.
Options before

bbb
bbg , bgb, gbb
bgg , gbg, ggb
ggg

Total is 12 boys, 12 girls
Options after the law

b
b , b, gb
b , gb, ggb
ggg

Total is 7 girls, 7 boys.
Two children gives:

bb
bg, gb
gg

vs

b
b, gb
gg

We could continue this to all possible sets and the results would be the same.
However, this is ignoring the possibility that there may be some genetic component (none that I've heard of but possibly the case) which says some couples are more likely to produce a particular sex. This may be the bias people are talking about.
Comment: @FreeElk `ggg`, `gg` are not valid options... the sequence must always end with a boy if I read op's post correctly.
Comment: @YvesDaoust Would you like to point out why the options aren't equally likely? Sure the different bullet points are different likelihoods but as far as I'm aware each comma separated event is (and that is what I'm comparing).
Comment: @FreeElk the question clearly states that "families are supposed to continue having children until their first male child" is assumed
Comment: I understand the intuition, but it neither conclusively proves a 1:1 ratio nor points out a logical error with my argument.
Comment: @ThomasW As I read the question you aren't forced to continue having children if your child is a girl. You have to consider the actual scenario, not just the maths involved. I think a lot of the answers here consider some sort of logic forced pregnancy rather than applying maths to the model a scenario where people choose the number of children they might want.
Comment: @ThomasW Ah yes, I had been going off `passed a law which forces families to stop having children after their first male child` which gives no indication of a forced pregnancy law. But you're right, the asker assumes such a law is also implemented. I suppose this is where we start to detract from reality and incorrectly model the situation.
Answer: Since the probability of $k$ girls then $1$ male is $2^{-k-1}$, the expected number of $(\text{female},\text{male})$ births
$$
\sum_{k=0}^\infty(k,1)2^{-k-1}=\left(1,1\right)
$$
We are ignoring multiple births, or families that cannot have children. Esentially, we are assuming that all families have children and that they keep having children until they have a male.

Note that this is the same as answering the question "flip a fair coin until we get heads; how many heads and how many tails do we expect to see?"
Comment: What does the notation $(1,1)$ mean?
Comment: @AlgorithmsX $(1,1)$ is a tuple or vector in which the first entry tells you the number of females and the second entry tells you the number of males
Comment: Could you provide a little background to this? It isn't immediately obvious why this is the case.
Answer: So to take this to a mathematical model and ignore all biological facts, we have the probability space $\Omega = \{g,b\}^{\mathbb{N}}$ with the product sigmaalgebra of the components and product probability measure ($p_i = \frac{1}{2}$). An element of the probability space represents the sequence of children of a single family.
For example take a set $A = \{\alpha \in \Omega : \alpha_i = \beta_i \text{ for } i=1,\dots,n\}$ for a fixed values $\beta_i$ then the probability is $P(A) = \frac{1}{2^{n}}$.
We want a random variable $G_n :\Omega \to \mathbb{R}$ that tells us if the $n$-th child is a girl if there is a $n$-th child according to our rules. So $G_n$ is either $1$ or $0$.
\begin{align}
G_n(\alpha) = \begin{cases}1 & \text{if } \alpha_i = g \text{ for } i\leq n \\ 0 & \text{else.} \end{cases}
\end{align}
The expected value of $G_n$ can be calculated by $P(G_n=1) = \frac{1}{2^n}$.
The number of girls in a family is represented by the random variable $G = \sum_{n=1}^\infty G_n$. So we want the expected value of $G$:
\begin{align}
\mathbb{E}(G) = \mathbb{E}\Big(\sum_{n=1}^\infty G_n\Big) = \sum_{n=1}^\infty \mathbb{E}(G_n) = \sum_{n=1}^\infty \frac{1}{2^n} = 1
\end{align}
Since the $G_n$ are highly dependent it is easy to verify the swap of integral and sum or just use fubini for positive functions.
Now to the boys: Let $B_n$ be the random variable that tells us if the $n$-th child is a boy
\begin{align}
B_n(\alpha) = \begin{cases}1 & \text{if } \alpha_n = b \text{ and }\alpha_i = g \text{ for } i<n \\ 0 & \text{else.} \end{cases}
\end{align}
The expected value of $B_n$ is again $P(B_n=1) = \frac{1}{2^n}$. Hence the same game again: the number of boys in a family is $B = \sum_{n=1}^\infty B_n$.
\begin{align}
\mathbb{E}(B) = \mathbb{E}\Big(\sum_{n=1}^\infty B_n\Big) = \sum_{n=1}^\infty \mathbb{E}(B_n) = \sum_{n=1}^\infty \frac{1}{2^n} = 1
\end{align}
By the way we also showed that the expected number of children is $2$ with this rule.
However we do have more than one family. So we have to multiply the whole result with the number of families but this doesn't change the ratio.
Answer: Consider a slightly different law, which allows families to have as many children as they want, but in which all children with an older brother are sent away.
This law is equivalent to the one proposed, because in each family only the children up to the first boy remain.
Of all the children born, the proportion of girls is $\frac12$.
Of all the children sent away, the proportion of girls is $\frac12$. (Children born in families in which already one boy has been born are from both sexes with equal probabilities.)
In conclusion, the proportion of girls in the remaining population must also be $\frac12$.
Answer: Here's an answer that assumes couples continued having children until they're no longer allowed to:
$$
\begin{array}{ccccccc|c}
& & & & & & & \text{probability} & \%\text{ male}/100 \\
\hline
m & & & & & & & 1/2 & 1 \\
f & m & & & & & & 1/4 & 1/2 \\
f & f & m & & & & & 1/8 & 1/3 \\
f & f & f & m & & & & 1/16 & 1/4 \\
f & f & f & f & m & & & 1/32 & 1/5 \\
\vdots & \vdots & \vdots & \vdots & \vdots & \ddots & & \vdots & \vdots
\end{array}
$$
The expected proportion of male children in a family is therefore
\begin{align}
& \sum_{n=1}^\infty \frac 1 n \left(\frac 1 2 \right)^n = \sum_{n=1}^\infty \frac {x^n} n = \sum_{n=1}^\infty \int_0^x u^{n-1} \, du \\[10pt]
= {} & \int_0^x \sum_{n=1}^\infty u^{n-1} \, du = \int_0^x \frac 1 {1-u}  \, du = \int_{1/2}^1 \frac1u\, du \\[10pt]
= {} & \log(1)-\log \left(\frac12\right) = \log(2) \approx 0.69 \quad \text{(where $\log(\cdot)$ means $\log_e(\cdot)$)}
\end{align}
The interchange of the integral and the sum is justified because the function is everywhere positive. (It is only when the positive and negative parts both diverge to infinity that one can get two different answers by changing the order.)
However (as pointed out below by "Paul") the fact that the average family has $69\%$ boys doesn't mean $69\%$ of all births will be boys because families with more girls than boys will be larger. If all couples get equal weight then the average is $69\%$ but if all babies get equal weight then it's $50\%$.
Comment: This computes the expected proportion of male children in a family, right? I read the question as asking about the ratio of male to female in the society as a whole.
Comment: @JulianRosen Exactly, families have on average 69% boys, but if you combine all families you get 50% because the families with more girls are bigger.
Comment: I understand the purpose of the table and the sum, but unfortunately I don't know enough to tell if the rest is correct or not.
Comment: Without adapting the argument to address what the question is actually asking about, i.e. the _overall_ proportion of boys and girls (not within a single family), I don't think this answer is particularly useful for this question.
Answer: This is a geometric distribution, with $p=0.5$. Let's call $X$ the number of children a family has.
The answer is going to be $\frac{1}{\mathbb{E}(X)-1}= \frac{1}{\frac{1}{0.5}-1}.$
For a proof of why $\mathbb{E}(X)=\frac{1}{p}$, see https://en.wikipedia.org/wiki/Geometric_distribution#Moments_and_cumulants
Answer: I like to model such problems as a finite state machine.  Just for fun I'll generalize by making the sex ratio at birth variable; let's call the probability of a daughter $r$.  Also, let's not assume that every couple keeps on making babies until they have a son; let $q$ be the probability of stopping after a daughter.
A couple begin in state $A$ (fertile), and with each child —

with probability $rq$, they have a daughter and move to state $B$ (infertile).
with probability $r(1-q)$, they have a daughter and remain in state $A$.
with probability $1-r$, they have a son and move to state $B$.

In state $B$ the expected number of future daughters ($d_B$) or sons ($s_B$) is obviously zero.
In state $A$, the expected number of future daughters is
$$d_A = r(1-q)(1+d_A) + rq(1+d_B) + (1-r)(0+d_B)$$
because in returning to state $A$ you add one to your daughters.  Simplifying,
$$d_A = r+rd_A-rqd_A $$
$$(1-r+rq)d_A = r$$
$$d_A = r/(1-r+rq)$$
The expected number of future sons in state $A$ is
$$s_A = r(1-q)(0+s_A) + rq(0+s_B) + (1-r)(1+s_B)$$
$$s_A = r(1-q)s_A + 1-r $$
$$s_A(1-r+rq) = 1-r$$
$$s_A = (1-r)/(1-r+rq)$$
So the sex ratio is $r : 1-r$, independent of $q$ (to my mild surprise; intuitively I expected fewer boys when $q>0$).
Answer: Here is another way to think about it - although you have already had a lot of ways.
First observe that the average size of a family is 2. Hopefully this is obvious, it follows from the rule that you have to wait an average of 1/pattempts to succeed where probability is p.
Second observe that all families will have exactly one boy.
Hence the average number of girls must also be one.
Answer: Lets rearrange the problem as a coin toss game.
For the purposes of visualisation, there is just one coin.
Each family gets a turn tossing the coin.
As long as they toss a head, they can keep playing and toss the coin again.
When they toss a tail, they have to hand the coin on to the next family.
The family can also choose to stop playing at any point and hand the coin on.
Since we are now simply talking about a long series of coin tosses, it becomes obvious that the ratio of heads:tails will be approximately 1:1
It doesn't matter if there is only one coin that is handed one from one family to the next, or every family has their own coin that they toss, the final ratio will be the same.

Funny(?) Probability Problem


Best method to learn all chords on piano

Question: I have struggled to find a system to learn all chords .With maj, min, 7th. maj7th , 6ths and all the rest and then inversions of all these chords ,I have given up time and time again but I want to play what I like before I leave this planet (I am retired)
Is there a method as there seems to be endless chords ? and I want to use both hands . I can read music up to about 3rd grade and can play most scales. I know the theory re formation of chords but the task seem impossible
Comment: Try using them in progressions/improv/. Notice when you're playing it in a piece. Using them can reinforce your learning.
Comment: Have you searched on line for piano chord charts?  I know they sell them in music stores but I would bet you can download some for free from the internet.
Comment: A chord is simply multiple notes.  So yes, there is effectively more combinations than you can learn.  Why learn chords devoid of context?
Comment: Go through the circle of fifths. Teach the chords that are in that key.
Answer: Learn them (and their inversions) as you play songs that contain them. Over time you'll learn them all, and better than just rote memorization since you're playing them in context. One at a time, you'll get them all.
To add, also study the structure of chords, like you said - a major chord is made of a root, major 3rd and a perfect fifth - so you should be able to figure out any major chord knowing this (and their inversions) - learn the rules for what other chords are defined as, and you'll also pick them up much more quickly.
One by one you'll get them all - it gets easier over time. I've only been learning chords for 2 years, and I feel pretty comfortable forming a whole lot of them reading off a chord chart on the fly.
Answer: It does seem to be a daunting task, looking at all the different varieties of chord. However, chipping away a bit a t a time is the way to go. Knowing scales is a good way to make inroads. If you are technically minded, this idea might help: There is a formula for the major scale notes - TTSTTTS. Taking the first (root) note of any scale, move up a tone (T) finds you on the next note used from that scale. Up another T finds the next note, etc.On piano, it's pretty clear, and it doesn't really matter which octave you play in, although the middle of the keyboard will sound clearer.
The next step is to realise the formulae that make up the different chords.Basic ones are 135 (maj), 1357 (maj7), 135b7 (dom7), 1b35 (min) and 1b35b7 (min7).
Each formula relates back to the major scale/set of notes in a key.With some chords, an extra note is added, with others, a note is swapped for a different one.
Don't worry about inversions, as, though they can appear complicating, they merely use the same notes that you play for a chord, "but not necessarily in the same order"
After getting this lot under your belt, it's straightforward to sort out 6ths, sus 4s, 9ths and so on, as they follow the same ideas.
One problem with all this is that each and every chord on keys has a different pattern,so it's daunting. However, there are several that fall into the same patterns, which can be handy for someone trying to make sense of it. In C major, the 3 main chords happen to comprise of white keys: C=CEG, F=FAC and G=GBD. they often go together to accompany songs. The same idea happens in Amaj. White/black/white translates to AC#E for A, DF#A for D and EG#B for E, so your fingers only change position, but not shape.
Try to stick to chords in one key when studying, rather than go through all the majors, then minors and so on.That way it'll make more sense, musically.
Sorry, couldn't condense this any more! But bit by bit, it'll work.
Comment: @FrankDodd you can start with the key of C. Then choose the 3 main chords that Tim mentioned above: C, F and G. With these 3 chords you can play almost every song. Once you master them, you can also use the A minor chord (still in the key of C). For using both hands... A shortcut is to play the chord with your left hand and the melody with your right. Don't worry if the progress seems slow - i took 6 months to master the key of C, but now can play comfortably in 5 keys. Good luck☺
Comment: "...stick to chords in one key when studying..." I gave the opposite advice in my answer (for different reasons) but this I agree this is good to do especially with keys giving one trouble (Bbm and Bm for me.)
Answer: Others note that you should learn chords in a musical context. That's true, but I think the crux of your question is getting over the feeling of bewilderment over too many chords. I think you want to "woodshed" on keyboard chord shapes to breakthrough that problem.
Time to set constraints and look for patterns...
First, be mindful of chord symbol redundancies. add6 chords for example. C6 is an inverted Am7 and Cm6 is an inverted Am7b5. All those symbols may obscure the fact there is a small set of basic chord types.
Start with a reasonable set of basic chords:
Triads

major
minor
diminished

IMO skip augmented. It's certainly rare. And, there is some theoretical debate if it's a true tonal chord.
Seventh Chords

Major seventh
Minor seventh
Dominant seventh
Diminished seventh
Half-diminished seventh

There are other seventh chord types, but those above are the commonest.
Find patterns and reduce.
There are six keyboard shapes for the major triads and another six for the minor triads. The roots of those major triads are F ascending to Bb, and the minor roots are from Bb ascending to Eb. Chords on the other roots are duplicates in shape. So, the "shape" of the C major triad (all white keys) is the same for F major and G major. Skip the duplicates in the beginning. When you get comfortable with the reduced set advance to the whole set of 12 chromatic roots.
Every major seventh and dominant seventh chord contains the set of major triads, and likewise for the minor sevenths and minor triads. That means 3/5 of the set of seventh chords can be conceived of as the triads you already know with the addition of only two more intervals a major seventh and a minor seventh above the chord root.
If memory servers, there are 8 shapes each for the major, minor, and dominant seventh chords. So there is some reduction to exploit with that too.
Regarding my idea of reduce and skip, you could do it literally, and it might be helpful at the very beginning to save time and hand fatigue, but it's better to think of it as mental reduction. Be aware when practicing that Cm, Fm, and Gm are the same shape and so on. It's not exactly 12 totally different minor triads, it's 6 with duplication.
Half-diminished chords are the same as a minor seventh chord with the chord fifth lowered. Yes, it's a different chord. Yes, it has a different harmonic function in a key, but in terms of keyboard fingering technique it's only a half-step alteration of the minor seventh.
Full diminished seventh chords. When inversions are accounted for, there are only three kinds of diminished seventh chords! So, Bb diminished seventh is the same group of notes as D diminished seventh. They are inversion of the same chord.
If you total all of those shape types - and exclude the duplicated triads - you get about 35 unique shapes. The basic triads and seventh chords are not endless and you can manage them when you constrain and reduce.
But, how to handle all the inversions?!
The first part is mental. Realize inverted chords are all alterations of the basic root position chord. Don't let that mentally psyche you out as 4 times more stuff to memorize. Think of it as modifications of what you already know.
The second part is the actual practicing of the inversions.
First, play the root position chords until they become familiar.
Next, incorporate the inversion into repetitions of practice drills. Instead of playing pattern X three or four times, move through the various inversions for each repetition.
When practicing these chord forms move through the root chromatically - ascending and descending - rather than the circle of fifth. Yes, a circle of fifth pattern will better reflect harmonic function, but I think you are trying to deal with the keyboard fingering challenge. When fingering is the main concern, I think the chromatic progression is more beneficial. In the beginning it will be challenging. Your fingers will get all mixed up. But when you finally overcome that challenge your command of the keyboard and control of your hands will be greatly improved.
Another practice pattern that seems to help me is repeating pattern x over three octaves without loosing a steady beat. Don't keep repeating stuff with your hands locked into a position. If you're having finger independence trouble, that's another story, and you may need to stay in a position for a while. Otherwise, don't get stuck in one place. Move up and down to the next octave for each repeat. If it's difficult, slow down the tempo. I have found repetitions in this manner are a great exercise of keyboard harmony.
Consult some classical piano methods for ideas of the actual patterns to practice. But, just hitting the 'block chords' is a simple and quick way to get started now.
If you devote about 30 minutes to an hour each day concentrated practice for 6 months, I'm sure you will overcome this problem!

...before I leave this planet...

Because we are determined in our goal, I thought I should add something about the harmony foundations of jazz and classical styles. After getting the fingerings under control these are the important harmonic patterns.

jazz major iim7-V7-I6
jazz minor iim7b5-V7b9-im
jazz an alternative substitutions for the V chord... major iim7-bII7b5-I6 and minor iim7-bII7-im
classical cadences: perfect, half, deceptive, phrygian, Neapolitan sixth, and augemented sixth (consult a harmony textbook for examples.)
classical rule of the octave - major and minor.
classical circle of fifth - simple triads and seventh chord suspensions - 3rd example, bottom of this page.

All the above patterns should be played in all major and minor keys.
Answer: Don't try and just memorise the chords, learn the relationship between each note, in semitones, so you can work out any chord when you don't remember it (by counting up from the root in semitones).
In fact, you don't even need to memorise that pattern: you probably already know one example of every chord.  So if you forget how many semitones there are between each note of a given chord, just look at an example and count.
If every time you don't know a chord, you work it out using logic instead of looking it up and just hoping to remember, pretty quickly you'll find you know all the chords.
By analogy, it's like the difference between learning times tables with, and without being able to multiply.  You could sit down and just memorise all the random numbers, sure, but if every time you forget, you do the math instead of just looking up the answer, pretty soon you're just gonna realise you know them all.
Answer: Just as a contrast to other comments about learning the theory (which I completely agree with), if you DO want to memorize them and/or just quiz yourself, try this method:
Start with A chords

A major
A minor
A5
A6
A7
A9
A augmented
A diminished

Now take that list (which is not all of them but you get the point) and practice for at least 5 min at a time switching between all of them in a single spot on the piano.
Once you get that solid, where you can switch quickly without hesitation or missing notes, then move to another spot on the piano and do the same.
Then, once you've got that down, practice switching between positions during the 5 min exercise realtime.
Repeat this for all of the musical notes and flats.
The key to this is to make a plan, use discipline to keep going even after it's boring or tedious and track your progress.  You can do it!
Answer: Well, get a chromatic button accordion keyboard.  Then there are only three possible variations of each chord type (1st, 2nd, 3rd row) instead of 12, for a 75% saving of learning effort.  And if you have a 5-row keyboard, you can, in a pinch, replace the 2nd and 3rd row variations with just a displacement of the 1st row pattern.
For pianos, there are Jankó keyboards.  Instead of 12 basic patterns, you then only have 2 basic patterns, and those are expected to be shifted since you have even more repetition rows.
History has been more favorable to the CBA keyboards than to Jankó.


consul proxy socket connection failed

Question: agent: Check "service:socat-proxy" socket connection failed: dial tcp 127.0.0.1:20108: connect: connection refused
It works in <code>-dev</code> mode but in normal server mode I get the above error? No clue where to start. Everything else seem to be working except proxy?
<code>{
  "connect": {
    "enabled": true
  },
  "service": {
    "name": "socat",
    "tags": [],
    "port": 8181,
    "connect": {
      "proxy": {
        "config": {
          "bind_address": "127.0.0.1"
        }
      }
    }
  }
}
</code>
Answer: You will have to explicitly turn on gRPC in normal server mode. In the dev mode, gRPC is enabled by default. Simply add a config of ports and define the gRPC port.

consul proxy socket connection failed


Objc save a file to the tmp/ with URL it is not working

Question: if i do the following it works fine
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[response suggestedFilename]];

But if i try to save it using the URL (although it returns the correct path) it does not save it.
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[response URL] absoluteString]];

Any ideas?
Answer: For a system file path don't use
[[response URL] absoluteString]

because the string starts with the scheme file://
use
[[response URL] path]

instead, which starts with the /
But I doubt that appending the full path to the temporary directory is what you want.
Comment: thank you for the fast reply. you are right i am trying to save 2 files in the tmp directory and because [response suggestedFilename] is the same one overrides the other so i need a better way to do this and i thought with the URL this could be achieved. I will try it with the path but i doubt i can create directories there.


Net areas of definite integral

Question: Given
$$
\int_{-4}^{2} f(x) dx = 5\\
\int_{-4}^{-2} f(x) dx = A\\
\int_{-2}^0 f(x) dx = B\\
\int_{0}^{2} f(x) dx = C
$$
$A$ and $C$ are areas below the $x$-axis. By interpreting definite integrals as net areas, how do I find the value of $\int_{-4}^{2} (f(x) - 2x - 3) dx$?
I tried making $-2x - 3 = g(x)$, then finding the net area of $g(x)$ from $2$ to $-4$ (which is $18.5$) then adding them together. So my final answer is $5+18.5$ units. I am not sure if I am doing it right because they have different regions above and below the $x$-axis.
Comment: Keep in mind that the two extra terms in the problem integral are inserting trapezoids and rectangles under the $  \ x-$ axis, the areas of which can be evaluated separately and then added to the integral for $ \ f(x) \ . $
Answer: Your method is correct but your interpretation and computation of the integral seems to be wrong. Also it looks like there's more information available than you need which may be confusing. Given the problem just use what you need from what's available (a general approach).
Splitting the integral as you did, $$\int_{-4}^2f(x)-\int_{-4}^{2}(2x+3)dx=5-\left[x^2+3x\right]_{-4}^2=5-\left((4+6)-(16-12)\right)=-1.$$
From how you asked your question, make sure you read your integrals correctly, e.g. $\int_{-4}^2$ is the integral from $-4$ to $2$, so $$\int_{-4}^2f(x)dx=[F(x)]_{-4}^2=F(2)-F(-4).$$ This is probably where your misunderstanding lies.
Comment: @chocopie I just had a read online and "net area" allows for negative values so the answer should be right. In every day life we only think of area as a positive value since we would not fit $-5m$ of carpet into a room. But since functions can go above and below the $x$-axis (positive and negative values), the "area" can sometimes come out as a negative. The idea of "net area" allows for this, whereas "area" does not.
Comment: i would assume that net area would mean |A| + |B| + |C| = $ \int_{-4}^{2} f(x) dx = 5\\ $, since its given that A and C are areas below the x-axis, am i overthinking it?

Net areas of definite integral


Accessing HTML inside XML using SimpleXML in PHP

Question: I'm having a problem with SimpleXML. When I'm using the children() method to get the contents of an XML element, with elements that contain HTML, it will parse the HTML contents as XML. How would I make it so that it won't parse HTML?
Answer: did you try to use CDATA ?
<xml>
    <node>
        <![CDATA[

        ]]>
    </node>
</xml>

Answer: The example you posted is valid XML, but the
 and -tags are part of the XML document.
Basically, you have to use CDATA (see natriums answer), or escape the HTML entities in the XML.
Answer: CDATA worked with me! =D
<?xml version="1.0" encoding="UTF-8"?>
<destaques>
    <destaque imagem="cartoes.jpg">
        <![CDATA[
            Text with some HTML.

        ]]>
    </destaque>
    <destaque imagem="banner2.jpg" />
    <destaque imagem="delivery.jpg" />
</destaques>


I cannot call a function in another JavaScript file

Question: I have two JavaScript files on my custom theme. One file has functions that need to be used on the other file. What I have below doesn't work. This is the error I get.

Uncaught ReferenceError: test is not defined.

jQuery will be used on both files.
file1.js
/**
 * @file
 * UI behaviors
 */

(function ($, Drupal) {

 'use strict';

  $(document).ready(function () {
    function test(){
     console.log('hello'):
    }
  });

})(jQuery, Drupal);

file2.js
/**
 * @file
 * UI behaviors
 */

(function ($, Drupal) {

  'use strict';

  $(document).ready(function () {
     test();
  });

})(jQuery, Drupal);

customtheme.libraries.yml
scripts:
  js:
    js/file1.js: {}
    js/file2.js: {}

customtheme.info.yml
libraries:
 - 'customtheme/scripts'

Answer: This is because test() is wrapped in an anonymous function, making it not available outside of that function.
I would add it to the Drupal object:
File 1:
(function($, Drupal) {
  Drupal.myFunction = function() {
    // Do something.
  }
}(jQuery, Drupal));

File 2:
(function($, Drupal) {
  Drupal.myFunction();
});

Also, as a side note, $(document).ready() is not used in Drupal. In Drupal Drupal.behaviors is used instead: https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview


Accurate computation of log error function difference

Question: For information-theoretic purposes I am interested in computing $f(a, b)=-\log_2\left(\text{erf}(b) - \text{erf}(a)\right)$ where $b > a$ and $\text{erf}$ is the error function.
Out-of-the box approximations (e.g scipy.special.erf) fail because $\text{erf}$ rapidly approaches $\pm 1$ so that catastrophic cancellation occurs inside the logarithm while $f$ itself is actually really well-behaved. Does there exist a reasonably accurate and efficient approximation of $f$ directly?
To make the question even more elementary, we can also approximate
$$g(a, b) = \ln\int_a^b e^{-t^2}\mathrm{d}t$$
and find $f = cg + d$ for some $c,d \in \mathbb{R}$.
Comment: You can use the complementary error function and write $erf(b)-erf(a)=erfc(a)-erfc(b)$.  In the regime you are interested in, $erfc$ is small and the cancellation disappears.
Comment: How accurate you want the result? Like an error bound.
Comment: @Sonal_sqrt I'd say within 0.1 or 0.01 bits (that is, absolute error of $f$) is accurate enough.
Comment: @RossMillikan That is definitely a better approximation given floating point's density around $0$, but will still fail for relatively small inputs, e.g. $f(200-0.1, 200+0.1)$ fails on my machine with $\text{erfc}$ when it should output somewhere around $\approx 32500$.
Comment: Your problem there is that your numeric representation will not deal with $2^{32500}$  If you want to work with arguments that large you need you need something that handles large numbers.  [Alpha](https://www.wolframalpha.com/input/?i=erfc%28200.1%29-erfc%28199.9%29) is quite happy computing the value before you take the $\log_2$ and gets about $10^{-17357}$
Comment: @RossMillikan That's why I'm asking if there's an efficient, *direct*, approximation. The function itself is well-behaved, it's only that its definition involves a microscopic number followed by a logarithm. That does not mean every approximation also has to use that.
Answer: You can write $f(a,b)=-\log_2(\operatorname{erfc}(a)-\operatorname{erfc}(b))$.  That will eliminate the catastrophic cancellation.  If you want to use large arguments for $a,b$ you can use the expansion of $\operatorname{erfc}$ near $\infty$, which is
$$\operatorname{erfc}(x)\approx e^{-x^2}\pi^{-1/2}\left(\frac 1x-\frac 1{2x^3}+\frac 3{4x^5}+O(x^{-6})\right)$$
Let $c$ be the midpoint of your interval, so $c=\frac {a+b}2$ and pull out the factor $e^{-c^2}$.  You can take its logarithm analytically, getting $\log_2(e^{-c^2})=-\frac {c^2}{\log(2)}$ and none of the rest will overflow.
Putting it all together, we have
$$c=\frac {a+b}2\\
f(a,b)=-\log_2(\operatorname{erfc}(a)-\operatorname{erfc}(b))\\
\approx -\log_2\left(e^{-a^2}\pi^{-1/2}\left(\frac 1a-\frac 1{2a^3}+\frac 3{4a^5}\right)-e^{-b^2}\pi^{-1/2}\left(\frac 1b-\frac 1{2b^3}+\frac 3{4b^5}\right)\right)\\
=\frac {c^2}{\log(2)}-\log_2\left(e^{-a^2+c^2}\pi^{-1/2}\left(\frac 1a-\frac 1{2a^3}+\frac 3{4a^5}\right)-e^{-b^2+c^2}\pi^{-1/2}\left(\frac 1b-\frac 1{2b^3}+\frac 3{4b^5}\right)\right)$$


SQL-Case / Cannot perform an aggregate function on an expression containing an aggregate or a subquery

Question: Here's my code, which I'm trying to get working:
DECLARE @DATE AS SMALLDATETIME ,
    @BasTar DATE ,
    @Bittar DATE

SET @DATE = GETDATE() - 1
SET @BasTar = GETDATE() - 1
SET @Bittar = GETDATE() - 1

SELECT  ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 0, 1, 3, 4, 5 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                        THEN ( TS.DEFAULT_RETURN_PRICE )
                   END), 0) AS SATIST ,
        ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 0, 1, 3, 4, 5 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                        THEN ( TS.VAT_TOTAL )
                   END), 0) AS SATISIV ,
        ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 2, 6 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                        THEN ( TS.DEFAULT_RETURN_PRICE )
                   END), 0) AS IADET ,
        ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 2, 6 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                        THEN ( TS.VAT_TOTAL )
                   END), 0) AS IADEIV ,
        ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 0, 1, 3, 4, 5 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                             AND TH.STATUS = 0 THEN TS.AMOUNT
                   END), 0) AS SATISMIK ,
        ISNULL(SUM(CASE WHEN TH.PTYPE IN ( 2, 6 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                             AND TH.STATUS = 0 THEN TS.AMOUNT
                   END), 0) AS IADEMIK
FROM    TRANSACTION_HEADER TH WITH ( NOLOCK )
        INNER JOIN TRANSACTION_SALE TS WITH ( NOLOCK ) ON TS.FK_TRANSACTION_HEADER = TH.ID
        INNER JOIN STORE ST WITH ( NOLOCK ) ON ST.ID = TH.FK_STORE
                                               AND ST.NUM BETWEEN '3999' AND '9999'
WHERE   TH.STATUS = 0
        AND ST.DESCRIPTION NOT LIKE 'POL_%'
        AND ST.DESCRIPTION NOT LIKE 'SIS%'
        AND CONVERT(CHAR(11), TH.TRANS_DATE, 103) BETWEEN @BasTar
                                                  AND     @Bittar

So because I use ST.ID IN(SELECT ID FROM FLO_AA_MAGAZALAR) in the case statement, it gives me that error for each sum(case) statement.

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
Comment: The problem is you have a subquery inside a SUM (this is the aggregate mentioned) which is prevented as part of the SQL specification, so this won't work. Not sure what you're trying to achieve though so difficult to suggest an alternative..
Answer: I'm not completely sure what you're trying to do, and I don't have your schema so I can't test this, but you might be able to move the SUMming out of the main query, here's an example using a CTE;
DECLARE @DATE AS SMALLDATETIME ,
    @BasTar DATE ,
    @Bittar DATE

SET @DATE = GETDATE() - 1
SET @BasTar = GETDATE() - 1
SET @Bittar = GETDATE() - 1

; WITH CTE AS (
SELECT  ISNULL(CASE WHEN TH.PTYPE IN ( 0, 1, 3, 4, 5 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                        THEN ( TS.DEFAULT_RETURN_PRICE )
                   END, 0) AS SATIST ,
        ISNULL(CASE WHEN TH.PTYPE IN ( 0, 1, 3, 4, 5 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                        THEN ( TS.VAT_TOTAL )
                   END, 0) AS SATISIV ,
        ISNULL(CASE WHEN TH.PTYPE IN ( 2, 6 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                        THEN ( TS.DEFAULT_RETURN_PRICE )
                   END, 0) AS IADET ,
        ISNULL(CASE WHEN TH.PTYPE IN ( 2, 6 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                        THEN ( TS.VAT_TOTAL )
                   END, 0) AS IADEIV ,
        ISNULL(CASE WHEN TH.PTYPE IN ( 0, 1, 3, 4, 5 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                             AND TH.STATUS = 0 THEN TS.AMOUNT
                   END, 0) AS SATISMIK ,
        ISNULL(CASE WHEN TH.PTYPE IN ( 2, 6 )
                             AND ST.ID IN ( SELECT  ID
                                            FROM    FLO_AA_MAGAZALAR )
                             AND TH.STATUS = 0 THEN TS.AMOUNT
                   END, 0) AS IADEMIK
FROM    TRANSACTION_HEADER TH WITH ( NOLOCK )
        INNER JOIN TRANSACTION_SALE TS WITH ( NOLOCK ) ON TS.FK_TRANSACTION_HEADER = TH.ID
        INNER JOIN STORE ST WITH ( NOLOCK ) ON ST.ID = TH.FK_STORE
                                               AND ST.NUM BETWEEN '3999' AND '9999'
WHERE   TH.STATUS = 0
        AND ST.DESCRIPTION NOT LIKE 'POL_%'
        AND ST.DESCRIPTION NOT LIKE 'SIS%'
        AND CONVERT(CHAR(11), TH.TRANS_DATE, 103) BETWEEN @BasTar
                                                  AND     @Bittar
)
SELECT
    SUM(SATIST) AS SATIST,
    SUM(SATISIV) AS SATISIV,
    SUM(IADET) AS IADET,
    SUM(IADEIV) AS IADEIV,
    SUM(SATISMIK) AS SATISMIK,
    SUM(IADEMIK) AS IADEMIK
FROM
    CTE


Standard and/or advanced curriculum preparing for a grad school in Applied Math

Question: I was wondering what would be a list of Applied Math courses (sort of like a road-map for an Applied Math student interested in a Applied Math PhD) which preferably contains absolutely essential courses, heavily suggested courses, and useful/nice miscellaneous ones from either Math or Stats or CS departments?
Also, I was wondering about how much Applied Math grad schools value more pure math undergrad courses as opposed to more applied ones... Supposing I have covered all of my basics such as real analysis, algebra, topology, complex analysis, linear algebra, ode, pde, probability, numerical analysis. Would they prefer me taking Stochastic Processes and, say, Scientific Computing to two graduate Differential Geometry courses or would they not care as much?
Thanks!
Answer: I have a masters degree in Applied Math with a bachelors in Actuarial Science, so hopefully I can share some good insights with you.
To answer your first question; you have to decide which track you're interested in:
1. Do you want to eventually pursue a PhD?
2. Do you want to pursue a career in industry that does not heavily rely on computer science?
3. Do you want to pursue Math in the Computer Science field; may be end-up working as a data scientist?
For question 1: I will advice you to take advanced classes for Numerical Analysis, Statistics, Differential Equations and Topology.
As for 2: Focus heavily on Numerical Analysis, Statistics, Probability, Advanced Calculus and may be if you're interested; Advanced differential equations.
As for 3: Take CS classes such as Design and Analysis of Algorithms, Computation Theory, Operating Systems and Computer Architecture, Advanced Calculus, Numerical Analysis, Statistics and Probability.
I did the courses in 2 and 3. Currently working as an Actuarial Analyst/Data Scientist in Health Care. Hopefully this helped a bit. Good luck!


Sobreposição da legenda das retas estimadas usando a função stat_poly_eq

Question: Ajustei diferentes modelos considerando a variável de resposta (massaseca) em função do (tempo) para cada nível de tratamento (teor) usando o pacote ggplot2 combinada com a função stat_poly_eq.

Porém, como pode ser visto no gráfico a seguir, as legendas das retas estimadas estão sobrepostas. Eu gostaria que eles fossem empilhados no canto esquerdo separadamente. Ao usar a função stat_regline_equation (label.y = 380, label.x = 1000) é possível mover a legenda, no entanto, eles ainda estão sobrepostos.
dados: https://drive.google.com/file/d/1Y-GsNNcYINqtO-hcJfNRgaj545JZXZIS/view?usp=sharing
library(ggplot2)
library(ggpubr)
library(ggpmisc)

my.formula <- y ~ x
ggplot(dadosnew, aes(x = Tempo, y = massaseca, group = interaction(Fator,Trat),
                     color=interaction(Fator,Trat))) +
  stat_summary(geom = "point", fun = mean) +
  stat_smooth(method = "lm", se=FALSE,  formula=y ~ poly(x, 1, raw=TRUE)) +
  stat_poly_eq(formula = my.formula,eq.with.lhs = "As-italic(hat(y))~`=`~",
               aes(label = paste(..eq.label.., ..rr.label.., sep = "*plain(\",\")~")),
               parse = TRUE, size = 5, label.y = 35)+
  labs(title = "",
       x = "Time (Minutes)",
       y = "Weight (mg)") + theme_bw() +
  theme(axis.title = element_text(size = 23,color="black"),
        axis.text = element_text(size = 18,color="black"),
        text = element_text(size = 20,color="black")) + facet_wrap(~Fator)

Comment: Eu estou votando para fechar esta pergunta porque ela depende de links externos.
Answer: O método para não sobrepor as equações é usar os argumentos

label.x.npc para o alinhamento no eixo dos x;
label.y.npc para o alinhamento no eixo dos y.

Este último é o que precisa de ser visto com cuidado. Após várias tentativas, encontram-se os valores seguintes:

ylim_sup quanto é preciso aumentar o eixo dos y;
xlim_sup quanto é preciso aumentar o eixo dos x;
label_y_npc a distância entre as equações.

E o código final é então o seguinte.
my.formula <- y ~ x
ylim_sup <- 1.1 * max(dadosnew$massaseca)
ylim_inf <- min(dadosnew$massaseca)

label_y_npc <- rep(seq(0.99, by = -0.05, length.out = 5), 2)

dadosnew %>%
  group_by(Tempo, Fator, Trat) %>%
  summarise(massaseca = mean(massaseca, na.rm = TRUE), .groups = 'drop') %>%
  ggplot(aes(x = Tempo, y = massaseca, color = Trat, group = Trat)) +
  geom_point() +
  stat_smooth(method = "lm", se = FALSE,  formula = y ~ poly(x, 1, raw=TRUE)) +
  stat_poly_eq(formula = my.formula,
               eq.with.lhs = "italic(hat(y))~`=`~",
               aes(label = paste(..eq.label.., ..rr.label.., sep = "*plain(\", \")~")),
               label.x.npc = "left",
               label.y.npc = label_y_npc,
               parse = TRUE) +
  ylim(ylim_inf, ylim_sup) +
  labs(title = "",
       x = "Time (Minutes)",
       y = "Weight (mg)",
       color = "Trat") +
  theme_bw() +
  theme(axis.title = element_text(size = 23,color="black"),
        axis.text = element_text(size = 18,color="black"),
        text = element_text(size = 20,color="black")) +
  facet_wrap(~Fator)

Comment: Obrigado @RuiBarradas!!!


Problems with nesting proof predicates in first order logic.

Question: Whenever I start nesting proof predicates, I always seems to run into these bizarre situations.  I was wondering if anyone knows about this and could shed some light on it or provide me with some references.  Thank you!
----Definition----
Let's define a set S as follows.
$$
 S :=
  \begin{cases}
      \mathtt{ZF} & \text{ if $\mathtt{Con}(\mathtt{ZF})$} \\
      \emptyset & \text{ otherwise}
  \end{cases}
$$
Although we can't determine whether S is $\mathtt{ZF}$ or S is $\emptyset$, we can still define $S$.
Consider the predicate $\phi_S(x)$ which abbreviates: $\mathtt{Con}(\mathtt{ZF}) \rightarrow x=\mathtt{ZF} \wedge \neg \; \mathtt{Con}(\mathtt{ZF}) \rightarrow x=\emptyset$.
The predicate $\phi_S(x)$ acts as a definition for S and we have $\mathtt{ZF} \vdash \exists! x \; \phi_S(x).$
----Proof Predicates----
For any set X of Godel numbers for first order formulas, in a standard manner, one can formally define a proof predicate $\mathtt{Pf}_{X}$.  (I can elaborate if necessary.)
We will consider both $\mathtt{Pf}_{\mathtt{ZF}}$ and $\mathtt{Pf}_{S}$.
It seems reasonable that we can nest $\mathtt{Pf}_{\mathtt{ZF}}$, but how do we nest $\mathtt{Pf}_{S}$?
To do so, $\mathtt{Pf}_{S}(\mathtt{Pf}_{S}(\ulcorner \psi \urcorner))$ will abbreviate $\exists x \; \phi_S(x) \wedge \mathtt{Pf}_{x}(\ulcorner \exists x \; \phi_S(x) \wedge \mathtt{Pf}_{x}(\ulcorner \psi \urcorner)\urcorner)$.
In other words, we include $S$'s definition each time we nest to a lower level.
Note: $\mathtt{Con}(X)$ will just abbreviate $\exists \ulcorner \psi \urcorner \; \neg \; \mathtt{Pf}_X(\ulcorner \psi \urcorner)$.
----Proofs----
1) First, I notice that $\mathtt{ZF} \vdash \mathtt{Con}(\mathtt{ZF}) \rightarrow S=\mathtt{ZF} \wedge \mathtt{Con}(S)$.
2) And, $\mathtt{ZF} \vdash \neg \; \mathtt{Con}(\mathtt{ZF}) \rightarrow S=\emptyset \wedge \mathtt{Con}(S)$.
3) From these two, we get: $\mathtt{ZF} \vdash \mathtt{Con}(S)$.
4) Further, we get: $\mathtt{ZF} \vdash \mathtt{Pf}_{\mathtt{ZF}}(\ulcorner \mathtt{Con}(S) \urcorner)$.
(I can elaborate on the standard properties of these proof predicates if necessary.)
Consider $\mathtt{Pf}_{S}(\ulcorner \mathtt{Con}(S) \urcorner)$.  This could not happen if $S = \emptyset$.  Also, it does happen if $S = \mathtt{ZF}$ as we just showed.
5) Therefore, $\mathtt{ZF} \vdash \mathtt{Con}(\mathtt{ZF}) \leftrightarrow \mathtt{Pf}_{S}(\ulcorner \mathtt{Con}(S) \urcorner)$.
For any $\ulcorner \psi \urcorner$, consider $\mathtt{Pf}_{S}(\mathtt{Pf}_{S}(\ulcorner \psi \urcorner))$.  This implies that $S = \mathtt{ZF}$ and $\mathtt{Con}(\mathtt{ZF})$ because otherwise we have the empty set which can't prove anything.
6) $\mathtt{ZF} \vdash \mathtt{Pf}_{S}(\mathtt{Pf}_{S}(\ulcorner \psi \urcorner)) \rightarrow \mathtt{Con}(\mathtt{ZF})$.
So we have $\mathtt{Pf}_{\mathtt{ZF}}(\mathtt{Pf}_{S}(\ulcorner \psi \urcorner))$.  For the same reasons, at the lower level we have $S = \mathtt{ZF}$ and $\mathtt{Con}(\mathtt{ZF})$ i.e. $\mathtt{Pf}_{\mathtt{ZF}}(\ulcorner S = \mathtt{ZF} \urcorner)$ and $\mathtt{Pf}_{\mathtt{ZF}}(\ulcorner \mathtt{Con}(\mathtt{ZF}) \urcorner)$.
However, $\mathtt{Pf}_{\mathtt{ZF}}(\ulcorner \mathtt{Con}(\mathtt{ZF}) \urcorner)$ is equivalent to $\neg \; \mathtt{Con}(\mathtt{ZF})$.
7) Therefore, $\mathtt{ZF} \vdash \mathtt{Pf}_{S}(\mathtt{Pf}_{S}(\ulcorner \psi \urcorner)) \rightarrow \neg \; \mathtt{Con}(\mathtt{ZF})$.
Combining both 6) and 7), we get:
8) $\mathtt{ZF} \vdash \neg \; \mathtt{Pf}_{S}(\mathtt{Pf}_{S}(\ulcorner \psi \urcorner))$.
If we picked $\ulcorner \psi \urcorner$ to be $\ulcorner \mathtt{Con}(S) \urcorner$, then we would have:
9) $\mathtt{ZF} \vdash \neg \; \mathtt{Pf}_{S}(\mathtt{Pf}_{S}(\ulcorner \mathtt{Con}(S) \urcorner))$.
----Conclusion----
In the end, this is a bizarre situation because we have both of the following:
$\mathtt{ZF} \vdash \mathtt{Con}(\mathtt{ZF}) \leftrightarrow \mathtt{Pf}_{S}(\ulcorner \mathtt{Con}(S) \urcorner)$, and
$\mathtt{ZF} \vdash \neg \; \mathtt{Pf}_{S}(\mathtt{Pf}_{S}(\ulcorner \mathtt{Con}(S) \urcorner))$.
How can the proof predicates $\mathtt{Pf}_{S}$ and $\mathtt{Pf}_{S}\mathtt{Pf}_{S}$ say the opposite of each other?
Comment: Are you sure that the formula Con(ZF)→x=ZF∧¬Con(ZF)→x=∅ is "meaningful", i.e. well-formed ? From x=∅, it seems that the variable $x$ range over set; if so, what is ZF ?
Comment: ┌ψ┐ is a number, nit a variable. Thus, how you can quantify it into ; ∃┌ψ┐ ?
Comment: I haven't thought this through carefully, but I'm suspicious about how much of the standard machinery you can salvage for your $\texttt{Pf}_S$. Unlike in Gödel's proof, your $S$ is not recursive (the $\texttt{Con}$ used in its definition is $\Pi_1$), and you won't be able to refer to $\Sigma_1$ completeness, which seems a key ingredient.
Comment: @MichaelWehar: I'm not totally sure how relevant this is, but I had in the back of my mind the (standard?) proof of Gödel's 2nd incompleteness theorem through the Bernays-Lob derivability conditions (in a Peano arithmetic setting perhaps). The 3rd condition is usually obtained from the fact that PA (and hence ZFC as well) proves all true $\Sigma_1$ sentences, and perhaps this is where things go wrong in your setting.
Comment: @MichaelWehar: My "3rd" condition is in fact the 2nd condition at the link you gave.
Comment: First response: As a formal object of our system, ZF is the set of Godel numbers for the axioms of ZF Set Theory.  One would need to go down the list of axiom schema and basically code up a set of Godel numbers for each axiom schema and then union them together to get the set ZF.  However, when I write "ZF $\vdash$" this is an informal expression which we interpret in English to be "I could write down a proof of the following formula using the system of ZF set theory in first order logic".  This is a convention that is used in the appendices of Kunen's book on Set Theory.
Comment: Second response: From my potentially limited experiences, it is not uncommon to use the following abbreviation: "$\exists \ulcorner\psi\urcorner$" abbreviates "$\exists x \in \mathtt{G}$" where $\mathtt{G} := \{ n \in \mathbb{N} \; | \; \text{$n$ is a Godel number} \}$.
Comment: Thank you very much for your quick response.  I appreciate it.  I'm thinking that you may also want to see how to formally define the "standard" proof predicate.  Would you like for me to explain this?
Comment: If X is computably enumerable, then we will have $Pf_X(\ulcorner \psi \urcorner)$ implies $Pf_X(Pf_X(\ulcorner \psi \urcorner))$.  However, since S is defined in a $\Pi_1$ manner (i.e. S is the complement of a computably enumerable set), this property does not hold.  Besides that, the proof predicate should satisfy all of the normal properties.  What exactly do you mean by $\Sigma_1$ complete?  I want to make sure that we are on the same page.  I would really appreciate it if you could think through it carefully.  Thank you!
Comment: Hi Christian, thank you for this remark.  What is the 3rd condition?  I claim that the third condition here is in fact satisfied: http://en.wikipedia.org/wiki/Hilbert%E2%80%93Bernays_provability_conditions
Comment: Oh, ok.  Yep, that one is not satisfied.  Thanks for clarifying.  :)
Answer: I think it might be helpful to get clear on exactly what $Pr_S(\ulcorner\phi\urcorner)$ says. In ZF it is provably equivalent to saying the following informal thing:

Either ZF is consistent and $\ulcorner\phi\urcorner$ is provable in ZF, or ZF isn't consistent and $\ulcorner\phi\urcorner$ is provable from nothing.

And since the second disjunct is provably false in ZF it just says: ZF is consistent and $\ulcorner\phi\urcorner$ is provable in ZF. In other words, $Pr_S(\ulcorner\phi\urcorner)$ is provably equivalent in ZF to $Con(ZF)\wedge Pr_{ZF}(\ulcorner\phi\urcorner)$.
(I assume $Pr_{\emptyset}$ means "provable from nothing", and not "provable from nothing apart from the axioms of first order logic"? At one point you said "the empty set can't prove anything". A similar diagnosis goes through on the other interpretation though.)
So I think the issue is, once you've spelt out the definition explicitly the result doesn't bear any straightforward resemblance to a provability predicate. It's also pretty clear why we get that $Pr_S(\ulcorner\phi\urcorner)$ and $Pr_S(Pr_S(\ulcorner\phi\urcorner))$ say different things, according to ZF.
$Pr_S(\ulcorner\phi\urcorner)$ says:

ZF is consistent and ZF proves $\ulcorner\phi\urcorner$

Which is true of many $\ulcorner\phi\urcorner$, assuming ZF is consistent. $Pr_S(Pr_S(\ulcorner\phi\urcorner))$ just says the following:

ZF is consistent and ZF proves that "ZF is consistent and ZF proves $\ulcorner\phi\urcorner$"

Which is, of course, is true of no $\ulcorner\phi\urcorner$, assuming ZF is consistent.
(Note that technically $Pr_S(Pr_S(\ulcorner\phi\urcorner))$ says: ZF is consistent and ZF proves $Pr_S(\ulcorner\phi\urcorner)$. However I noted above that $Pr_S(\ulcorner\phi\urcorner)$ is provably equivalent in ZF to $Con(ZF)\wedge Pr_{ZF}(\ulcorner\phi\urcorner)$.)
Comment: Certainly.

You may already know this, but there is some work on non-standard provability predicates that seems related. For example there is a formula in the language of arithmetic which is true of the Godel number of a sentence in the standard model if and only if the sentence is provable in PA, but such that the claim corresponding to Con(PA) using that formula is provable in PA. (See for example http://matwbn.icm.edu.pl/ksiazki/fm/fm49/fm4915.pdf)
Comment: I think this is a pretty good response!  Formally, for any set $X$ of Godel numbers, I would define $Th(X)$ recursively where $Th(X)$ is the minimum set of Godel numbers for formulas that includes $X$ and is closed under the inference rules applied to the Godel numbers.  Then, $\mathtt{Pf}_X(\ulcorner \psi \urcorner)$ will just mean $\ulcorner \psi \urcorner \in Th(X)$.  Now, what you are saying is that from this definition, you can prove that $\mathtt{Pf}_S(\ulcorner \psi \urcorner)$ is equivalent to $\mathtt{Con}(\mathtt{ZF}) \wedge \mathtt{Pf}_{\mathtt{ZF}}(\ulcorner \psi \urcorner)$.
Comment: I think your response is a great explanation for what is going on here, but I still feel uneasy and am confused on how we can define sets like S and on how statements like $\mathtt{Pf}_S(\mathtt{Pf}_S(\ulcorner \psi \urcorner))$ don't mean what we might think they mean.  Would you be willing to talk further about this?  I have another example that I'm trying to understand and I think your input would be quite helpful.  Thank you!  :)
Comment: Great!  Thank you for the reference.  I will contact you.  :)


Netbenas X-Debug socket exception

Question: I'am trying to debug my php files via x-debug and Netbeans
I'am using
Netbeans 8.0,
PHP version  5.5.11,
Xampp 1.8.3,
xdebug:2.2.5(latest version when i check it from wizard),
OS:Windows 7
xdebug php.ini configuration
[XDebug]
zend_extension = "C:\xampp\php\ext\php_xdebug-2.2.5-5.5-vc11.dll"
xdebug.remote_enable=1
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000

With this system and configuration when i try to debug my php file i'am getting socket exception on Netbeans 8.0. I have read and tried almost all solutions on web but couldn't fix it.
What can be the reason of this problem ? Any help would be appriciated.
Comment: can you try it with one of the following files [xdebug-2.2.5-5.5-vc11-nts](http://xdebug.org/files/php_xdebug-2.2.5-5.5-vc11-nts.dll) and [xdebug-2.2.5-5.5-vc11-TS](http://xdebug.org/files/php_xdebug-2.2.5-5.5-vc11.dll)
Comment: @moskito-x it doesn't work.
Answer: php_xdebug-2.2.5-5.5-vc11-nts.dll needs
MSVCR110.DLL I'm not sure if this file is located on your computer
and look for Php5.dll and put php_xdebug-2.2.5-5.5-vc11-nts.dll into the same folder.
Mostly in the C:\xampp\php\ folder not C:\xampp\php\ext\
Comment: Do i need put the `php_xdebug-2.2.5-5.5-vc11-nts.dll` file to C:\xampp\php\ext\ ? Because it is defaultly placed on there.
Comment: @Tartar : It should be in the folder where Php5.dll is.

Netbenas X-Debug socket exception


Query com coluna dinâmica spring data

Question: Preciso realizar um select usando o @Query do spring data, porém preciso passar o nome da coluna por parâmetro
Exemplo:
<code>@Query("SELECT g FROM Grupo g where g.? = ?")
Page<Grupo> findTeste(String campo, String valor);
</code>
Para chamar método eu queria passar o nome da coluna como a seguir:
<code>//Pseudo code
page = grupoService.findTeste("id", "1");
page = grupoService.findTeste("nome", "asdf");
</code>
É possível construir algum método assim no spring data?
Comment: Desta forma não tem como - não sem mudar o core do framework -, o *lookup* de queries no spring data é no startup. O que você pode ter é um repositório customizado, usar *specifications*, construir as queries dinamicamente, usar algo como querydsl, etc. Se não for mandatório ter que usar `@Query` depois posto uma resposta pra ti.
Comment: Não é obrigatório usar o @Query, vou estudar **specifications** e os **querydsl** se puder mandar um código eu agradeço.
Answer: Na propria documentação você tem exemplo de @Query com NamedParameters:
--

5.3.6. Using named parameters
By default Spring Data JPA will use position based parameter binding
  as described in all the samples above. This makes query methods a
  little error prone to refactoring regarding the parameter position. To
  solve this issue you can use @Param annotation to give a method
  parameter a concrete name and bind the name in the query. Example 52.
  Using named parameters

<code>public interface UserRepository extends JpaRepository<User, Long> {

  @Query("select u from User u where u.firstname = :firstname or u.lastname = :lastname")
  User findByLastnameOrFirstname(@Param("lastname") String lastname,
                                 @Param("firstname") String firstname);
}
</code>

Note that the method parameters are switched according to the
  occurrence in the query defined.

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.named-parameters
Comment: acho que não entendestes, eu queria passar o nome da coluna, por exemplo:

`page = grupoService.findTeste("id", "1");
page = grupoService.findTeste("nome", "asdf");`
Comment: Ele não entendeu mesmo, a resposta dele aplicada a coluna nem compila...O spring verifica se a query é valida para compilar..
Answer: Acredito que nesse caso não tem como fazer isso usando Spring Data.
Mas você pode criar uma classe por exemplo: CustomRepository
Nessa classe você pode utilizar o EntityManager e executar a query conforme você quer, exemplo:
<code>@PersistenceContext
protected EntityManager manager;

public Grupo findTeste(String campo, String valor) {
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT g FROM Grupo g where g.").append(campo).append(" = :").append(valor);
    String query = sb.toString();
    return manager.createQuery(query, Grupo.class).getSingleResult();
}
</code>
Comment: Hehe, essa era a resposta que ninguém queria acreditar ser a unica solução. Muito estranho não ter essa opção no Spring Data. O Spring traz tantas vantagens e desse jeito não tem como aproveitá-las, como aproveitar o Pageable por exemplo e ter que ficar fazendo limit e offset na mão.

Query com coluna dinâmica spring data


Example of a set $S$ that is countable, but the set of limit points is uncountable

Question: What would be an example of a set $S$ so that $S$ is countable. However $S'$ is uncountable. In this $S'$ is the set of all the limit points of $S$.
Comment: $\mathbb Q$ in $\mathbb R$?
Comment: What is the biggest countable set (of real numbers) you know of? Why not try that one and see if it works?
Comment: @bof there is no "biggest" countable subset of the reals :)
Comment: @user251257: Nothing like taking a rational approach to the problem!
Answer: Consider the set of all rationals $$\mathbb Q$$
Answer: Rationals! In fact on a more general note, if $R$ is some uncountable compact subset, and is of a metric space then, $\forall n \in \mathbb{N}$, there is a finite subset $S_n$ of $R$ such that every element of $R$ is within $n^{-1}$ of an element of $S_n$. Then
$$S=\bigcup_{n\in\mathbb{N}}S_n$$
which is a countable subset of $R$ whose closure is $R$.
Comment: I think this is an explicit example of your general statement: $\{\sin(n):n\in\mathbb{N}\}$ is clearly a countable set, but its set of limit points is $[-1,1]$.


Guitar pedal sounds broken / off - troubleshooting

Question: My guitar sounds pretty good just plugged in to the amp, but unfortunately my new pedal is starting to sound off; it sounds really strained and the effect is barely audible. It's less than a week old and sounded perfect out of the box when I first hooked it up. However, yesterday when I tried to play it again, dials and everything still in same place, it was almost as if it wasn't hooked up at all. Just have this sinking feeling that it's broken.
The only thing I can think of that I might have done wrong was hook it up to an external generator since I'm still waiting for my ISO bric to arrive; I wanted to play out in the summer a bit. At first glance it doesn't seem like a bad thing, the power generator is for general outdoor use and matches exactly my wall socket specs in terms of polarity, voltage and current -- erego I can't see how it would be mechanically any different than just playing in my bedroom.
Question
Given my pedal's issues of sounding weak and totally unlike when I first plugged it in, what would be a likely explanation and/or the worst case scenario? I'm wondering if it's possible to underpower a pedal and if so, I guess it's just scrap metal now? Not sure what I should do if that's the case.
Note:

Working with EHX Mainframe
I realize this pedal sounds glitchy to begin with, but there truly is
a big difference from when I unboxed it. Fairly scientific about
concluding something seems wrong
I have reached out to the vendor, not resolved yet, but I think I'm
within my rights. Either way, I want to learn more about these kind
of pitfalls just in case
No battery slot

Edit
I returned it to the vendor. Then I noticed another pedal I bought last year seems to be off. But I took it to a guitar shop and it played just fine on their amp. So the joke's on my amp; never would have thought. Systems built on systems....
Thanks to all who gave input; helped greatly.
Comment: A lot of pedals can work with batteries. Have you tried that?
Comment: Troubleshooting analogic pedals and digital pedals (like this one) is a complete different ballpark: if an IC is dead it is fairly hard to find which and even harder to find the part and replace it
Comment: Have you tried to restore it to factory settings?
Comment: Can you add an audio file for how it sounds now? Also, have you tried different cables?
Comment: It's not clear how you powered it up the first time. Could you be more clear?
Answer: I don't understand "..hook it up to an external generator since I'm still waiting for my ISO bric to arrive..."
The Mainframe manual states that a power supply - presumably a 'wall-wart' type - is included.  So I HOPE that's what you were using!
"WARNING: Your Mainframe comes equipped with an Electro-Harmonix 9.6DC-200BI power supply. The Mainframe requires 90mA at 9VDC with a center negative plug. Use of the wrong adapter or a plug with the wrong polarity may damage your Mainframe and void the warranty. Do not exceed 10.5VDC on the power plug. Power supplies rated for less than 90mA will cause the Mainframe to act unreliably."
If your generator DID damage anything, with any luck it was just the power supply.
Comment: I thought that having a power supply is preferred to wall adapters. ISO brick is compatible with 9v pedals as far as I know. But will have to inspect to see if it comes with 90mA 9VDC cables as you point out
Comment: 9V DC at 90ma is a very standard requirement.   OK, there are some really cheap, unregulated wall-warts out there, but I'm sure the one supplied with the pedal is just fine!    If you find yourself using too many wall-warts, the ISO brick is a tidy alternative.
Answer: The Mainframe is such an odd effect, most folks reckon that if you change some settings it is almost impossible to get back to the sound you had before.
That said, your outdoor power generator may not be well regulated, and it could have produced current spikes that could destroy circuitry.
The usual troubleshooting guidance applies - can you compare with someone else's pedal? But without an audio file, or more usefully a video file showing what settings you are using while playing through it, there is not much we can do from here. It sounds like getting EHX to look at it is the best course of action.


Verificar checkbox apenas quando estiver marcado

Question: Estou fazendo uma verificação de um check box para saber se tem um type="radio" selecionado.
O problema que o check está executando o calculo mesmo quando eu desmarco o check box.
Fiz o seguinte teste para ver o que estava acontecendo.
console.log($("input[type='checkbox'][id='SavePaper']").is(':checked') );

O resultado do teste foi:
true
false
false
true
true
false
Segue a imagem

Porque isso acontece e como resolver?
Atualização: código do checkbox

     <input type="checkbox" id="SavePaper" name="SavePaper" class="md-radiobtn">

Comment: Não tem a ver diretamente com a tua questão, mas tendo em conta que os id's devem ser unicos no DOM (página) porque não fazes simplesmente: `$('#SavePaper').is(':checked');`. Pensando um pouco melhor o teu problema pode vir daí. Os dois botões apesar de terem o mesmo `type`, não podem ter id's iguais. corrige isso e vê se o problema se mantém
Comment: deu exatamente mesma coisa
Comment: vou colocar codigo do checkbox...
Comment: Atualizei o comentário acima. Eu não disse que resolveria o problema, só disse que ficaria melhor
Comment: Eles não estão com ids iguais
Comment: O checkbox está com um e o radio está com outro
Comment: Deves colocar o código que tens (de preferência funcional, em snipet) para que seja mais facil ajudar-te
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/63797/discussion-between-gabrielfalieri-and-miguel).
Answer: $("#SavePaper").click(function(e) {
     if($(this).is(':checked')){
         if ( $("input[type='radio'][name='Licenciamentodeusuários']").is(':checked') ){
             valor = $('input:radio[name=Licenciamentodeusuários]:checked').val();

             if(valor == "Até") {

                 if ($("#Ate-Comercial").val() != undefined) {
                     qtdUsuarios = $("#Até-Comercial").val();
                     vlrFinal = qtdUsuarios * 0.99;
                     console.log(vlrFinal);
                 }
                 if ($("#Até-Educacional").val() != undefined) {
                     qtdUsuarios = $("#Até-Educacional").val();
                     vlrFinal = qtdUsuarios * 0.99;
                     console.log(vlrFinal);
                 }
                 if ($("#Até-Profissional").val() != undefined) {
                     qtdUsuarios = $("#Até-Profissional").val();
                     vlrFinal = qtdUsuarios * 0.99;
                     console.log(vlrFinal);
                 }
             }else{

                 valor = valor.replace(/\s{2,}/g, ' ');
                 valor = valor.split(" ");

                 vlrFinal = valor[2] * 0.99;
                 console.log(vlrFinal);

             }
         }

     }

 });

Resolvido.
Comment: Poderia acrescentar uma explicação do que foi feito para corrigir o erro


Change multiple elements using fadeIn(1000) but without waiting for another element to end fading

Question: How to change color of one element using fadeIn(1000) and background of the another element using the same fadeIn(1000) but at the same time?
Comment: put elements in the same class and call fadeIn on that class
Answer: Select them all together and just use one fadein ... Show some code
Comment: This is more suitable as a comment than an answer.
Answer: To animate the colors, you also need the jQuery UI plugin to provide color animation.
<code>$('#itemOne').animate({color:'#0ff'}, 1000);
$('#itemTwo').animate({backgroundColor:'#0ff'}, 1000);
</code>
For documentation at http://api.jquery.com/animate/ and http://jqueryui.com/animate/
Comment: Hmm. The question does say "How to change the color of one element...".
Comment: This question is nothing to do with colours; `opacity` can be animated by plain jQuery
Comment: Yeah this is what he needs.  And fadeIn() doesn't prove very effective for this situation.  Closed my jfiddle but there's no fade at all just instant color changes.
Comment: Maybe you're right; the question is too ambiguous. I take it to mean fading two elements above some existing ones (hence the use of fadein), which happens to change the colour because the new elements are a different colour.


Presentation of a group: Show that $\langle a|a^2\rangle =\{1,a\}$.

Question: Example: $\langle a|a^2\rangle=\{1,a\}$.
After reading the definition of presentation of a group, I find myself cannot understand the above example given. I don't know which part of the definition I have misunderstood, so please show the above statement step by step. Thank you.
Edit:
My interpretation: Let $G=\{a\},\ \langle G\rangle=\{1,a,a^{-1},a^2,{a^{-2}},\ldots\},\ R=\{a^2\}$. $N$ is the smallest normal subgroup of $\langle G\rangle$ which contains $a^2$. Then $\langle a|a^2 \rangle=G/N$. Can you please give more details?
Comment: It might be easier to help if you wrote down your definition of a group presentation.
Comment: That doesn't look quite right. It's better to write $X = \{a \}$, since that is a generating set, not a group. Then $F = \{1,a,a^{-1},a^2,\ldots \}$ is the free group with the single generator $a$. Define $N$ to be the smallest normal subgroup of $F$ that contains $a^2$. Then $\langle a \mid a^2 \rangle = F/N$. Note that $F$ is just the infinite cyclic group with generator $a$, and $N$ is its subgroup generated by $a^2$ (which is normal), so $F/N$ has order $2$. Strictly speaking $\langle a \mid a^2 \rangle = \{N, Na \}$ rather than $\{ 1,a\}$, but that is standard abuse of notation.
Comment: So $N=\{1,a^{\pm 2},a^{\pm 4},...\}$?
Comment: $\{N,Na\}=F$?????
Comment: Yes, $N = \{1, a^{\pm 2}, a^{\pm 4}, \ldots, \}$, and $\{N,Na \} = F/N$.
Comment: So what exactly $\{N,Na\}$ is? Is it $\{\{1,a^{\pm2},a^{\pm4},...\},\{a^{\pm1},a^{\pm3},a^{\pm5},..\}\}$?
Comment: Yes that's right. But frankly you cannot hope to understand the theory of group presentations if you are uncertain about what subgroups and cosets are.
Comment: Ya, I will work hard, thanks for your help.
Answer: The notation $\langle a\mid a^2\rangle$ denotes the group that consists of finite-length words on the alphabet $\{a,a^{-1}\}$ under the smallest equivalence relation that contains $aa\sim \epsilon$ and which is compatible with the law of composition, which is the concatenation of words.
You can use induction to prove that $a^{2n+b}\sim a^b$, where $b\in\{0,1\}$, $n\in\mathbb Z$. Thus the group has at most $2$ elements: the equivalence class of $a^1$, and that of $a^2$ (which is also the equivalence class of $\epsilon$).
To prove that the equivalence class of $a$ and that of $\epsilon$ are distinct, note that $\sim$ is defined as the smallest congruence that makes $aa\sim\epsilon$ valid. If we had $a\sim\epsilon$, the $\sim$ relation would identify all the elements, and would not be the smallest relation.
Comment: There are several things wrong with your definition. The smallest equivalence relation in which $aa \sim \epsilon$ has all of its equivalence classes except $\{ aa, \epsilon \}$ of size $1$, and they do not form a group. You need a *congruence*, which has extra conditions. Also, you need strings on the alphabet $\{a.a^{-1}\}$ rather than just $\{ a \}$.
Comment: @DerekHolt: Thank you for pointing this out. Cheers!


AsanaConnect oAuth Redirect URL with custom scheme

Question: The account settings page for registering an app accepts just valid http:// url schemes. We would require a custom url scheme in order to redirect back to our iOS app. Is there currently a way to provide a custom url scheme or if not, would it be possible to allow custom URL schemes from your side?
Answer: (I work at Asana.) We agree those would be useful. There is currently no way to use non-http schemes but we will look into adding them soon. Stay tuned!
Comment: "Useful" is an understatement :-). Without a custom scheme it's not possible to use Asana Connect with Android apps, because any http url would be redirected in the browser as is, instead of redirecting to the app. Accepting non-http schemes in the "register app" settings would be the preferred way to fix that but allowing a redirect url that's different from the one in the settings (twitter does that), would also work.
Comment: Just noticed this, and it's huge. I'm not writing a mobile app, but a desktop app with a WebView to do the OAuth authentication. I don't have a valid redirect_uri within a desktop app, so anything other than a valid HTTP URI would work to allow me to grab the token out of the hash.
Comment: Or even having something like Salesforce has with a "success" url after login that could be my redirect_uri... https://login.salesforce.com/services/oauth2/success
Comment: We still don't support non-http schemes (sorry, this hasn't been high on our priority list) but we DO support the standard "native" URIs for redirect: `urn:ietf:wg:oauth:2.0:oob` and `urn:ietf:wg:oauth:2.0:oob:auto`. These will actually redirect to an Asana-hosted page which puts the code in the window title for the hosting app to pull out. The first one displays a code for the user to copy, while the latter expects the app to auto-close the window.


Product of fundamental matrices $G(x)^{-1} H(x)$ does not depend on $x$

Question: Recently I posted a book exercises about fundamental matrices I managed to solve. The following one is a little harder imo:

Let $G(x)$ and $H(x)$ be fundamental matrices of the homogeneous linear system of equations
$$
y^{\prime}=A(x) y.
$$
Show: $G(x)^{-1} H(x)$ does not depend on $x$.

I played a little bit around with the equations:
If $G(x)$ and $H(x)$ are fundamental matrices, then
$$
G^\prime(x)=A(x)G(x)
$$
and
$$
H^\prime(x)=A(x)H(x).
$$
Then
$$
G^\prime(x)G(x)^{-1}=A(x)=H^\prime(x)H(x)^{-1}
$$
and
$$
G(x)^{-1}H(x)=A(x)H(x)G^\prime(x)^{-1}=H^\prime(x)G^\prime(x)^{-1}.
$$
But it got me nowhere and I wanted to ask for some help. Thanks in advance for any kind of hint or help.
Comment: if the matrix is independent of x then its derivative is zero and vis versa
Comment: vis versa $\to$ vice versa...
Answer: Take the derivative with respect to x
$f(x)=G(x)^{-1}H(x) \Rightarrow f'(x)=\frac{d~(G(x)^{-1})}{dx}H(x)+G(x)^{-1}H'(x)$
$\frac{d~(G(x)^{-1})}{dx}=-G(x)^{-1}G'(x)G(x)^{-1}$
$\Rightarrow f'(x)=-G(x)^{-1}G'(x)G(x)^{-1}H(x)+G(x)^{-1}H'(x) = -G(x)^{-1}A(x)H(x)+G(x)^{-1}H'(x) = -G(x)^{-1}H'(x)+G(x)^{-1}H'(x)=0 \Rightarrow f(x)=constant$


Why $ \int_{0}^{\infty} \lfloor x \rfloor x dx= \sum_{0}^{\infty}n\int_{n}^{n+1}xdx $

Question: I am trying to learn how to work with the floor function, and I would really appreciate if someone can explain me the reason behind:
$ \int_{0}^{\infty} \lfloor x \rfloor x dx= \sum_{0}^{\infty}n\int_{n}^{n+1}xdx $
It sort of makes sense in my head, but I am confused - how can I simply change the integral in that way? since when (kidding) separating a product of two functions is even legal?
I guess it has something to do with the fact that $\lfloor x \rfloor$ is constant for every $n\leq x \leq n+1$ and n is natural, but I can't justify that with real rigorous claims.
Thanks.
Comment: @KaviRamaMurthy not so much, but actually the above was an example, I am mostly interested in the moving from the left integral to the right one, I don't mind if they converge or not
Comment: Both sides are equal to $\infty$. Are you familiar with basic concepts of measure theory?
Answer: For each $n\in \mathbb{N}$, define a function $$f_n(x)= \begin{cases}nx & \mbox{ if }x\in [n,n+1), \\
0& \mbox{ else.}\end{cases}.$$
Show that $\lfloor x \rfloor x=\sum_{n\in \mathbb{N}}f_n(x)$ for all $x\geq 0$. The result follows.
P.S. There are minor issues with defining an infinite sum of functions, however in this particular case everything is fine as $f_n(x)$ is zero except on the interval $[n,n+1)$ and $f_n(x)=f_m(x)\neq 0$ implies that $n=m$.
Answer: For $x \in [n,n+1)$ we have $\lfloor x \rfloor x=nx$. Hence $n\int_{n}^{n+1}xdx=\int_{n}^{n+1}\lfloor x \rfloor x dx$.
As mentioned in the comment: $\int_{0}^{\infty} \lfloor x \rfloor x dx= \infty =\sum_{0}^{\infty}n\int_{n}^{n+1}xdx$


Hundred-Digit Challenge - problem 2 - math's idea of solution

Question: For you who don't know what 100 digits challenge is...
The hundred-dollar, hundred-digits challenge problems are a set of ten problems in numerical analysis published in the January/February 2002 issue of SIAM News (http://www.siam.org/siamnews/01-02/challenge.pdf). Nick Trefethen, the proposer of the problems, offered a 100 dollars prize to the person or group obtaining the largest number of correct digits (up to a maximum of 10) for these problems by May 20, 2002. Trefethen underestimated the ingenuity of problem solvers, and 20 independent teams obtained 10 correct digits for all 10 problems. After an anonymous donor stepped in to help defray the larger than anticipated payoffs, prize checks went out to all winners by December 2002.

Second problem :  A photon moving at speed 1 in the $xy$ plane starts at $t=0$ at $(x,y)=(0.5,0.1)$ heading due east. Around every integer lattice point $(i,j)$ in the plane, a circular mirror of radius $\frac{1}{3}$ has been erected. How far from the origin is the photon at $t=10$?
My question is how to solve this without using computer simulation(just pure math).
Answer: A complete, purely mathematical approach  would imply a high number of tedious passages and calculations (the solution to this problem is known to require $14$ reflections before reaching $t=10$). However, if I interpret correctly the question, it asks for a simple general idea of solution.
If this is the case, we could choose different  methods (e.g. using vectors, analytic geometry, trigonometry). The analytic geometry approach might be rather intuitive. We have to consider a sequence of successive segments on a Cartesian plane, each characterized by a starting point, a running line (the line actually followed by the photon in its path), a collision point (identified by determining the first crossing point  between the running line and a circle), and a reflection line (whose angle is determined by the slope of the tangent to the circle in the collision point). Once completed a step, the collision point and the reflection line become the starting point and the running line of the successive step. Since for each segment of the path we can calculate the distance covered by the photon (or equivalently the time needed to run this distance), we can continue our step-by-step calculations until we reach $t=10$ and look at the point where we have arrived. In this way, the problem reduces to find the way of determining, from a starting point and a running line of a generic step, the corresponding collision point and the reflection line, so that iterating our calculations we can arrive to the solution.
The general approach to each step may be as follows. If $(x_n,y_n) $ is the starting point at the $n^{th} $ step and  $a_n x+b_n $ is the equation of the corresponding running line, we have to begin by finding the collision point, i.e. the first crossing point  with a circle. The circle can be firstly identified by visual examination of the graph (although we have then to  confirm that the line actually crosses the circle and that the identified circle provides the minimal distance between the starting and collision point). Because all circles correspond to a translation of the circle $x^2 + y^2=\frac {1}{9} \,\,\,$ over an integer lattice, we can consider the  equation $(x-j_n)^2 + (y-k_n)^2=\frac {1}{9} \,\,\, $, where $(j_n,k_n) \,\,$ are the integers expressing the coordinates of the centre of the circle on which the $n^{th} $  reflection occurs. Solving the system
$$\begin {cases}
y=a_n x+b_n \\
(x-j_n)^2 + (y-k_n)^2=\frac {1}{9} \end {cases} $$
to find the crossing point between the circle and the running line  gives the coordinates of the collision point:
$$  x_{n+1}=\frac{m^2 \pm \sqrt {m^2-(b_n-k_n)^2-j_n^2  +1/9  }}{  a_n^2+1 }$$
and
$$y_{n+1}= a_n x_{n+1} +b_n$$
where $$m=a_n k_n +j_n-a_n b_n $$ and where we have to choose, among the two solutions, the case that corresponds to the lower distance between the starting and the collision point. This distance $d_n$ can be obtained using the standard formula, knowing that it is calculated between the points $(x_n,y_n) \,\,\,   $ and $(x_{n+1},y_{n+1}) \,\,\,   $.
Now we have to find the slope of the tangent to the circle in $x_{n+1},y_{n+1} \,\,\,$ to calculate the reflection line. Using the derivative of the circle equation, we obtain that the slope $t_n $ of the tangent at the $n^{th} $ reflection is
$$t_n=\pm \frac {(j _n - x_{n+1})}{\sqrt{1/9 - (j_n - x_{n+1})^2}}$$
where again we have to choose, among the two solutions, the appropriate one, looking at our graph to check the sign of the searched tangent. To calculate the slope of the reflection line, we can remind that if a line with angle $\alpha$ with respect to the $x $-axis is reflected on a line with angle $\beta $, the angle of the resulting reflected line is given by $2\beta-\alpha$. In this case we have $$\alpha=\arctan {a_n}  \\  \beta=\arctan {t_n}  $$ so the slope of our reflection line is $$\tan ( 2 \arctan {t_n}  -   \arctan {a_n} ) \,\,\, $$ Because it passes through $x_{n+1},y_{n+1} \, $, its equation is
$$\small {y= \tan ( 2 \arctan {t_n}  -   \arctan {a_n} ) x \\ + y_{n+1} - \tan ( 2 \arctan {t_n}  -   \arctan {a_n} ) x_{n+1} }$$
In this way, based on a starting point with coordinates $(x_n,y_n ) $ and a running line $a_n x+b_n $ that characterize the $n^{th} $ step, we have determined the collision point $(x_{n+1},y_{n+1}) \,\,$, the distance covered between these two points, and the reflection line. Setting the collision point and the reflection line as the starting point and the running line of the successive step, we can repeat several times the whole procedure, until the sum of the distances covered in each step achieves $10$.
To make a practical example, we can apply these calculations to the first step of the problem. We start from the point $(x_1,y_1)=(0.5,0.1) \,\,\,\,$ and the running line is $y=0.1$. The first circle to be crossed is that with centre in $(1,0)$, which has equation $(x-1)^2 +y^2=\frac {1}{9} \,\,\, $. Applying the equations above with $a_1=0 \,$, $b_1=0.1\,$, $j_1=1 \,$, and $k_1=0 \,$, we get $m=1\,$, so that the coordinates of the collision point $(x_2,y_2) \,$ (knowing that we must choose, among the two solutions, that nearer to the starting point) reduce to
$$ x_{2}=1 - \sqrt {1-0.1^2-1    +1/9     } = 1 - \frac {\sqrt {0.91}}{3} \approx 0.682 \\ y_{2}=0 \cdot x_2+0.1=0.1
$$
Using the derivative of the circle equation, we obtain that the slope $t_1 $ of the tangent at the first reflection is
$$t_1= \frac{1 - ( 1 - \sqrt {0.91}/3) }{\sqrt{1/9 - [(1-   (1 - 0.91/3)]^2   }}   \\ =     \frac {\sqrt{0.91}/3 }{\sqrt{1/9 - 0.91/9  }} = \sqrt {91}/3 \approx 3.1798   $$
Lastly, the equation of the reflected line is
$${y=\tan \left ( 2 \arctan {   \sqrt {91}/3    }   \right) x \\ + 0.1 - \tan \left ( 2 \arctan { \sqrt {91}/3    }   \right) \cdot (1 -  \sqrt {0.91}/3 )}$$
$$y=- \frac {3 \sqrt {91}}{41} x + 0.1 + \frac {3 \sqrt {91}}{41} -  \frac {91}{410} $$
which in numbers is approximately
$$y=-0.6980 x +0.5761$$
So we have determined the collision point and the reflection line of the first step. As explained above, these become the starting point and the running line of the second step, allowing to repeat the procedure.


Detect if user opens link in new tab and redirect to new url

Question: I am trying to do something that I'm not sure is possible or not?
The user opens the website. If they try to reopen the link in a new tab I need to redirect them to another page.
I've tried using c# to see if I can detect a page reload. This works, but if I put my code in the page load event for some reason it runs twice, and it redirects them no matter if it's the first time they opened or if they are opening in a new tab. I need to only happen if they open a new tab.
My Code:
bool IsPageRefresh = false;
if (!IsPostBack)
{
  ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
  Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
  if (ViewState["ViewStateId"].ToString() != Session["SessionID"].ToString()) ;
  {
    IsPageRefresh = true;
    if (IsPageRefresh == true)
    {
      Response.Redirect("~/Pages/EstimateList.aspx", true);
    }
  }
  Session["SessionId"] = System.Guid.NewGuid().ToString();
  ViewState["ViewStateId"] = Session["SessionId"].ToString();
}

Do I need to use Javascript or jQuery to do this? I'm really new to Javascript and jQuery.
Comment: While you may be able to hack something together to do this, all you are probably going to do is irritate the user by doing something they are not expecting.
Comment: I doubt you can do this. Certainly not server side and I'd imagine the JS will restrict this functionality in the browser as it's annoying and can be abused
Comment: I didn't get what you want. Does it matter if the user type again in the address bar or you just don't want to have 2 tabs of the same page to be open?
Comment: Ashkan, I just don't want to allow them to open it in a new tab.
Comment: You realise what a horrible user experience that is right?
Comment: @Liam If it can't be done it can't be done.  I just needed to check if it was possible.  Thank you.
Comment: @DavidG Yes I do.  Lol.  They want to do it this way though.
Answer: You can use cookies. When the user first open the page you send a cookie to the computer saying PageOpened=true , when the user opens it in the new tab check if there is a cookie with PageOpened=true, if there is, open your other link in the browser.
You can give your cookies a time limit or destroy them when the first site is closed or when the user opens the new tab etc..
I can't provide you the code as I never worked with c# on web but this should give you an idea on possible routes to the solution.
P.S.: I would also find it irritating as a user but that is your call.
Comment: Can it be done in Javascript?
Comment: [w3schools](http://www.w3schools.com/js/js_cookies.asp) and  [stackoverflow](http://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie) on cookies with javascript
Answer: you can try this
if(Request.Cookies["isPageRefresh"] == null)
{
   Response.Cookies["isPageRefresh"].Value = "true";
   Response.Cookies["isPageRefresh"].Expires = DateTime.Now.AddDays(1);

}
if (!IsPostBack)
{
 if (Server.HtmlEncode(Request.Cookies["isPageRefresh"].Value== "false")
 {
   Response.Redirect("~/Pages/EstimateList.aspx", true);
 }
 //enter some code
}
  Response.Cookies["isPageRefresh"].Value = "false";
  //enter some code

because on each new tab click asp understand it as a new request. you should use cookies for checking isPageRefresh if false redirect or use global variable that doesn't have redirect effect like cache variable  value
Comment: Hi Syuash, IsPageRefresh = true; is inside of if (!IsPostBack).
Comment: Yes and use  bool IsPageRefresh = false; not in load_page method
Comment: Suyash, I don't understand?  Where do I need to put if if not in page load?
Comment: isPageRefresh=true;
if (!IsPostBack)
        {
              if (IsPageRefresh == true)
                {
                    Response.Redirect("~/Pages/EstimateList.aspx", true);
                }
        }
        else
        {

                IsPageRefresh = false;

            }
because on each new tab click asp understand it as a new request if you should use cookies too for checking isPageRefresh
        }
Comment: Why not just edit your answer? The above is basically unreadable