A chord with only the root note

Question: I have this strange thought over which I argue with people. If a chord is a set of distinct tones sounding simultaneously (or one after another like in arpeggios) then for instance a root C in the bass together with a few more C's on other octaves should also be called a chord. For instance we have four notes which are C on the piano in different octaves - they are all distinct tones. Not the same note in terms of hertz and position (unlike on the guitar where we can have two or more same notes in an octave but they would sound different). Yet, in musical theory the most simple chord should consist of a root, a third, and a fifth. However, a two note chord with only the root and the fifth is called a power chord (C5 for instance), but we don't have a chord for only the root and the third, whether it be the minor or the major third. But then how do we identify the chord if it does not have a minor or a major third?
So in terms of piano keys what is a chord?
Comment: A chord is essentially notes which produce harmony together. Can't hear any harmony in a number of different octave C notes played together. Power chord may well be a misnomer.
Comment: @piiperiReinstateMonica Described in the question, reedited!
Comment: @SovereignSun Just for fun, on any physical instrument a single note has already harmonic information, given by its overtone series, which includes the octave, perfect fifth, etc. This is in part what allows us to identify the very specific signature of a tone on each instrument, so its definitely information our brain percieves. Would you call a single note a chord based on this?
Comment: @hirschme Probably, if the harmony says so.
Answer:
what is a chord?

In other words, what does a chord do. If you encounter something that doesn't do those things, then you shouldn't call it a chord in that sense. (The "is" word is called a copula https://en.wikipedia.org/wiki/Copula_(linguistics) and your question is basically a general request for explanations about the problem domain where the word "chord" is used - and the answers better be focused around sentences about doing, not other copulas)
What does a chord do?
Chords explicate, bring out several features about the harmonic context at the same time. Chords are capable of explicating more features per time unit than a single-voice melody line, so they have more harmonic expressive power. Chords are harmonic bulldozers compared to single-note shovels.
When you listen to music, your ear constantly tries to keep track of a few important things:

(1) what is the home note, i.e. tonic. That's the home position.
(2) what is the expected harmony, i.e. set of intervals around the home note. This is the home shape.
(3) are we at home now, i.e. is the harmonic position and shape of the set of currently sounding notes sitting on the tonic and in the home shape, or is it away from the tonic in some way, or in a non-home shape.

The harmonic context around the tonic is defined in a space of one single octave. A single note, say, C, can only explicate "C". It doesn't say which octave, because there are no octaves in the harmonic context. The set of octaves and that kind of spacing has more to do with timbre than harmony. If you have a chord C, E, G, you can voice it in many ways by spreading the notes in different octaves, and it will create a different sound, but harmonically it still only does the same thing any C major triad does. It says three things: (1) there is a C, (2) there is an E, and (3) there is a G. (plus, the lowest note is an extra feature, but IMO that's not relevant for the chord vs non-chord question)
When you have one or two or three or a thousand different sounding C notes, even the whole mass of them only says "there is a C", that's all. That's a very weak harmonic device! Definitely not a bulldozer. The so-called "power chord" is actually a weak harmonic device, not harmonically powerful at all. It is powerful in terms of timbre and for putting more weight to its root note.
If you hear an F major chord as the set of currently sounding notes, but in your mind you've established C major as the tonic position and shape, then you feel that you're not at home. You want to hear a C major to make yourself feel that you returned home. Or at least a plain C note that leaves room for imagining the C major around it. If you only hear a single F note, it doesn't leave room for imagining this - you are not at home with any stretch of imagination ... unless you keep playing the F note for so long that in your mind you move your bed and fridge there. This usually happens in about a minute.
"Is this a ... "
Language is always used in a context. What is your context? When is it justifiable to call something a chord? Will doing that labeling be good or bad for your intentions?
Is this a chord? Is it major, minor or suspended? Cluster chord? If you heard that played, would you say you heard a chord? Did you hear one pitch or multiple pitches? Regardless of instrument? If you sample this, can you play melodies with it? Can you play other chords with it?

How about this one, is it a chord?

Is the following a chord? The two half-notes in the first bar are most definitely chords, but would you say it ends on a non-chord?

Consider your context and make up your own mind. :)
Comment: @SovereignSun As piiperi wrote, you should ask whether it _functions_ as a chord, not whether it _is_ a chord. The latter just becomes a question about definitions, which isn't useful in itself.
Comment: So is it or is it not a chord?
Comment: @SovereignSun if you can't tell from reading this answer, then I can't help. Sorry. Maximal effort has been given.
Comment: I can, but you didn't give the straight answer, which I would appreciate if you did.
Comment: What if you take sound synthesised sound that dropped out of normal notation and has polyphony, won't one key make a chord then?
Comment: @SovereignSun Haha, you are reaching the edge case! For example, do you know the sampler? It is an electronic device or software that can make all the notes out of any sound, just by shifting its pitch. Then what about you sample the sound of a [C E G] chord playing on, say, a piano? Then if you play a note using this sample, is it a note or a chord? Both!!
Answer: The standard concept of chords is stacked thirds. That is, given a scale, start at some point and take every third note.
For example, given the scale C D E F G A C etc. you take C E G, D F A, etc.
If you take three notes in this way, the chords are called triads.
If you take 4 notes at a time, they are called "seventh" chords, e.g. C E G B, D F A C, etc.
Now, in case of power chords, you are already stretching the concept to some extent, and indeed some theorists would say that two notes do not a chord make.
In case of a two-note chord made of a root and a third, personally, I would still call it a major or minor chord. Indeed, removing the fifth from a chord is less extreme than removing the third. In other words, to my mind and to my ear, C-E (C major without a fifth) sounds more like a chord than C-G (C5 or C power chord).
But when you take it to the extreme of having just one note, even if at different octaves, I think that's stretching the concept of chord one step too far -- you've just got one note.
Comment: Stacked thirds are not "the" standard concept to chords, they are _one approach_ to how to construct chords by default, which is standard in _some_ genres.
Comment: To ponder upon - play notes E and G. Now, are they root and m3 of Em, or M3 and 5 of C major, or 5 and m7 of A7..?
Comment: @Tim Which comes first, the E or the G?
Comment: @Tim If there's nothing else going on, I definitely hear E and G as an Em, especially if the E and G are near each other. I find that any m3/M3 interval alone is already extremely suggestive of the corresponding chord with the lower note as the root. Of course, that depends on my Western musical background, but then again, the fact that we (Western world) ended up naming chords and scales primarily based on this m3/M3 interval is not completely arbitrary or accidental -- there is quite a strong natural and instinctive attracting force in them. How do you feel it?
Comment: I tend to hear it as A7. But when it's G under, close position, it becomes a C major. Probably hearing the lower note as a root is part of our conditioning - as a bassist it's part of my remit..!
Comment: @SovereignSun - moot point. That in itself may change the perception. Maybe we're programmed to provide a 'third note' in our mind's ear. And i context or out, the answer may well be a different chord is heard. That's my point. That E+G could also be, even with a B note, the upper part of Cmaj7.
Comment: @MMazzon the reason Power Chords work especially in a rock environment is the distortion provides other notes, so while the root and 5th may be insufficient to be a "proper" chord, the end result is a chord.
Comment: @DoktorMayhem - I'd have thought slightly differently - taking out the 3rd, thus its harmonics, results in a tidier sound. True it probably ends up as a 'chord' - be interested to know what 'chord' it could be - and it's got to be the same for all 'power chords' - hasn't it?
Comment: Well, the distortion adds harmonics back in, and depending on the type of distortion, or the discussion interval, I can get different harmonics.
Answer: There are various definitions of 'chord'.  Some say two distinct tones are sufficient.  Some insist on a minimum of three.  But there's general agreement that 'distinct tones' means 'distinct pitch classes'.  The same note in another octave counts as one.
Now, is ANY group of tones a 'chord'?  Is it still a chord if it can't usefully be given a name?
Is the dyad C,E sufficient to be defined as C major?   (Remember Harmony 101 where we're taught that in Bach-style 4-part writing 'the 5th may be omitted'?)
What about the 'power chord' C,G ?  We've latterly given it a name, 'C5'.   We can count that as a chord, can't we?
How about a cluster.  C, C♯,D, D♯ ? Probably pointless to attempt naming it, but is it a 'chord'?
We're now in the territory of 'Topic For Discussion' rather than 'Question With a Definite Answer'.
Comment: A cluster is definitely a chord for me, take C, D, E, F for instance. That could be anything, but it's a chord, and even two notes appart like C, G# is a chord, we just don't know what chord it is. It could be anything either.
Answer: It's definitely a chord, though it is very poor in harmonic information.
It does not provide any definitive clue on the tonality or the role inside the tonality, etc.
However, as it very strongly sets the note that it is stacking up, chances are high that it is the tonic (1st note of the tonality, e.g. C in C Major). Or maybe, next likely, the dominant (5th note, e.g. G in C Major).
Comment: Practically every instrument's sound has harmonic overtones, which means that pitches are sounding in many octaves. So, any note played on any instrument is a chord?
Comment: No, a chord is a concept stemming from polyphony, or the fact that the player is uttering several notes at the same time. The concept of note itself is related to the atomic event producing the simplest sound on the instrument. So for example, on a viola d'amore, even if each time a string is excited it makes resonate the corresponding sympathetic string, it is still only one note.
Comment: Note, chord, are concepts completely linked to music execution, the succession of actions made by the player. They are not directly linked to the result, to the physical nature of the sound produced. A chord means playing several notes at the same time.
Comment: @piiperiReinstateMonica Not one sound.
Comment: So, In key C major, ending someting with several octaves of B notes, what chord will that B be?
Comment: @Tim, if you end your musical piece, and assuming your are in tonal music, it would be an evocation of a natural 7th (frequent in jazz). But if your music is modal instead of tonal, it could be that you are ending with a B mode melody.
Comment: I don't believe that. It's more likely to feel like an imperfect cadence - listening to the M3 of the dominant. true, we use maj7 in jazz a lot, but they need their root to sound convincing. Only considering tonal stuff - modal is muddying the water.
Comment: Then it could be just an unfinished piece! Or an atonal one. Or anything. You are free to play what you want, it does not have to be meaningful to be a chord. In jazz a lot of pieces end with 7th (by the soloist), and even a capella it sounds convincing. Not the melody proper though, but its embellification.
Answer: Depends on context.
The conductor of a symphony orchestra, during rehearsal, would probably refer to that as unison doubled at the octave.
A music theory student would be chastised for calling it a chord. A chord must have three or more notes, by definition. However, it could be called an implied chord if the context justified it.
An atonal composer would refer to it as a simultaneity composed of a several pitches but only one pitch class.
A musician in a rock band trying to teach his group a song would probably not refer to it as a chord as that wouldn't really accurately tell them what to play. They would probably call it a note," e.g. a "A major chord, then E minor chord, then a C note."
A guitarist might call it a partial chord.
A computer programmer writing, say, an Ableton plugin, might call it a special case of a chord, and it would be reasonable for a chord generator to allow for chords composer only of a single note at various octaves.
Answer: In mathematics, basically everything has an identity operator that changes nothing. For instance, x + 0 = x and y * 1 = y. So, even when you add zero, nothing changes but it still counts as addition and when you multiply by one nothing changes but it is still multiplication.
If you look at it that way, the unison chord is the identity operator of the chord construction operation. You add no extra harmonics to the root note, but you could still see it as a chord.

A chord with only the root note


Independent and dependent variables in Repeated Measures ANOVA

Question: I am working on a study where I have a sample of 86 students. I have tests for 5th grade, 6th grade, 7th grade, and 8th grade. I think I can run a Repeated Measures ANOVA since I have observations for 4 different occasions.
However, I am unsure what my independent and dependent variables are in this set up.
Comment: Could you tell us what your variables are? I could probably help you sort out which are independent and dependent!
Answer: I guess you are having a hard time due to your data structure. Based on your description i think you have data in the "wide" format, like this:

Student-ID  5th     6th     7th     8th      Sex
1           result1 result2 result3 result4  male
2           result5 result6 ...              female

(result1, result2,... being the test scores)
Your dependent and independent variables will become clear if you restructure your data to "long" format:

Student-ID Sex    Grade TestResult
1          male   5th   result1
1          male   6th   result2
1          male   7th   result3
1          male   8th   result4
2          female 5th   result5
2          female 6th   result6
...

Now the dependent variable is the TestResults, while the independent variables (in my example) are sex and grade.
If thats not clarifying your problem, do as Kyle says.
Comment: I think you forgot to add the Grade variable as IV
Comment: Thank you, I edited my answer. Of course **grade** might be an IV or a random effect, too. Think it depends on the aim of the study.


eigenvalue question

Question: I think this question isn't that hard, but I am a bit confused.
Define the linear operator $T_k:H\mapsto H$ by
\begin{align}
T_ku=\sum^\infty_{n=1}\frac{1}{n^3}\langle u,e_n\rangle e_n+k\langle u,z\rangle z,
\end{align}
where $z=\sqrt{6/\pi^2}\sum^\infty_{n=1}e_n/n$. For negative $k$, show $T_k$ has at most one negative eigenvalue.
Comment: Please use $\langle, \rangle$ (`\langle, \rangle`)
Answer:
A computation shows that $T_k$ is self-adjoint if $k$ is a real number (as a sum of such operators), so if $\lambda$ and $\mu$ are two different eigenvalues of $T_k$, the associated eigenvectors for these eigenvalues are orthogonal.
If $u$ is an eigenvector for $\lambda<0$, then for each $j\geqslant 1$,
$$\langle u,e_j\rangle+kj^2|z|^{-1}\langle u,z\rangle=\lambda j^3\langle u,e_j\rangle,$$
hence,
$$\langle u,e_j\rangle=-\frac{kj^2}{1-\lambda j^3},$$
as we can assume $\langle u,z\rangle =1$ and $\lambda\neq j^{-3}$.
Now we conclude. Let $\lambda$ and $\mu$ two distinct eigenvalues of $T_k$ and $u,v$ associated eigenvectors. Then
$$0=\langle u,v\rangle =\sum_{j\geq 1}\frac{kj^2}{1-\lambda j^3}\frac{kj^2}{1-\mu j^3},$$
a contradiction.
Even if it's not required in the question but in the comments, $A_k$ is a compact operator for each $k$. Let $$T_N:=\sum_{j=1}^N\frac 1{j^3}\langle u,e_j\rangle e_j+k\sum_{j=1}^N\frac 1{j}\langle u,e_j\rangle \frac 1{\lVert z\rVert}z.$$
It's a finite ranked operator, and $\lVert T-T_N\rVert\to 0$.
Comment: I've added the conclusion.
Comment: @anegligibleperson I've added it.
Comment: So why cant there be more than one negative eigenvalue?
Comment: Also, how does one show $T_k$ is compact?

eigenvalue question


Check cells in column C against column J to generate email

Question: I need to check cells in column C against column J (which is my minimum stock quantity).
If column C is less than or equal to column J, I need Excel to generate and send an email (Outlook) to alert our purchasing department that specific items are running low.
The code is not triggering the email.
<code>Dim xRg As Range

'Update by Extendoffice 2018/3/7
Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    'If Target.Cells.Count > 1 Then Exit Sub
    Set xRg = Intersect(Range("J2:j2000"), Target)
    If xRg Is Nothing Then Exit Sub
    If xRg < Target.Value Then
        Call Mail_small_Text_Outlook
    End If
End Sub

Sub Mail_small_Text_Outlook()
    Dim xOutApp As Object
    Dim xOutMail As Object
    Dim xMailBody As String
    Set xOutApp = CreateObject("Outlook.Application")
    Set xOutMail = xOutApp.CreateItem(0)
    xMailBody = "Hi there" & vbNewLine & vbNewLine & _
      "This is line 1" & vbNewLine & _
      "This is line 2"
    On Error Resume Next
    With xOutMail
        .To = "Email Address"
        .CC = ""
        .BCC = ""
        .Subject = "send by cell value test"

        .Body = xMailBody
        .Display   'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
End Sub
</code>
Comment: `On Error Resume Next` is dodgy in this often seen email code. Here it has the potential of silently emptying the stockroom. Always remove when you see it just before `With xOutmail`.
Answer: You don't check correctly the actual stock quantity against the minimum value.
Try something like this:
<code>  Set xRg = Intersect(Range("C2:C2000"), Target)
    If xRg Is Nothing Then Exit Sub
    If xRg <= xRg.Offset(0,7) Then

</code>
this is only for comparing the values, not checked the send of email.


Return an array of compared char pointers in C++

Question: I'm at college and we're learning pointers. Our job was to input a char, compare it to an array and return a pointer to the first reference of that char in the array. But, as I don't like easy things, I've asked my teacher what about having that char more than once in the array.
That's where my headache begins.
So I have this code. The idea is: create a function that compares the input char to the entire array, get the pointers of the references and save them in an array and return that array.
Unfortunately it's not working as I wish :(
What can be wrong?
#include<iostream>
#include<cstdlib>
using namespace std;
char list [10];
int main()
{
    initialize();
    show();
    cout<<search('1');
}
void initialize()
{
    int i;
    for(i=0; i<10;i++)
    {
        list[i]='1';
    }
}
void show()
{
    int i;
    for(i=0; i<10;i++)
    {
        cout<<list[i];
    }
}
int* search(char* input)
{
    int* result[10];
    int i;
    char *temp;
    for (i=0; i<10; i++)
    {
        *temp=list[i];
        if(strcmp(temp, input) != NULL)
        {
            result[i]=i;
        }
    }
    return result[];
}

Comment: are you comparing the first 10 characters from the two strings?
Comment: int *result[10] is an array of integer pointers. 'i' is an integer. result[i] = i; is assigning an integer to an integer pointer. This compiles because of C's slipperyness, but is probably not what you want. If you compiler has a strict option, use it and learn from it.
Answer: I'm on a mobile device so I can't go into huge detail unfortunately, but you are returning a pointer to an array that you create in the function which goes out of scope at the end of the function.
My massive edit:
As everyone has already stated, a C++ array is actually only a pointer to the first element in the array. As a result, if you return a pointer to an array created in the scope of the function, you are returning a pointer to garbage. If I were doing this I would use a vector, but if I were to be forced into using an array, I would use something like the code below. Hope this helps!
#include <iostream>
#include <cstdlib>

void initialize(char* list) {
    for(int i = 0; i < 10; ++i) {
        if(i < 4) {
            list[i] = '2';
        } else {
            list[i] = '1';
        }
    }
}

void show(char *list) {
    for(int i = 0; i < 10; ++i) {
        std::cout << list[i] << ' ';
    }
    std::cout << std::endl;
}

// Note the function requires an additional argument that is a pointer
// this is how you can avoid returning a pointer
int search(char input, char* list, char* result) {
    int j = 0;
    for(int i = 0; i < 10; ++i) {

        // comparing characters can be done via ==

        if(input == list[i]) {

            *(result + j) = list[i];

            // You could use result[j], but I used this to show that
            // result really is just a pointer to the first element
            // of the array. As a result saying result[j] is the same
            // as saying I want to deference j elements past the first
            // element or *(result + j)

            ++j; // increment j
        }
    }
    // return how many elements matched
    return(j);
}

int main(int argc, char *argv[]) {
    char list[10];
    char temp[10];

    initialize(list);
    show(list);
    int size = search('1', list, temp);

    // create a dynamically sized array containing space for each match
    // because we don't know the size at compile time we must use
    // a library type or a dynamically sized array
    char *result = new char[size];

    for(int i = 0; i < size; ++i) {
        result[i] = temp[i];
        // again you could use result[i]
        std::cout << *(result + i) << std::endl;
    }
    delete[] result; // otherwise you'll get a memory leak
    return(0);
}


Drupal 8 dropping session variables on password reset. Gives 403 Access Denied

Question: I have a fresh install of Drupal 8.6.13, default everything with no custom themes or modules. It was created via:
drupal-composer/drupal-project:8.x-dev with the drupal site:new command.
When I use a one time login link I get a 403 access denied error because the session data (timestamp and hash) gets lost on the redirect from UserController::resetPass to UserController::getResetPassForm.
Here is the source code for reference: https://api.drupal.org/api/drupal/core%21modules%21user%21src%21Controller%21UserController.php/8.6.x
When I log the session variables when they are created in resetPass they are stored and show correctly.
When I then log the session variables on getResetPassForm they are no longer there. This causes the following code to execute which returns the 403:
if (!$hash || !$timestamp) {
  throw new AccessDeniedHttpException();
}

I'm not sure if this is a Drupal problem or Symfony problem or what.
Everything has worked fine on previous versions of Drupal 8.6.x. I noticed the issue when upgrading from 8.6.8 to 8.6.13. I have now tested with just a fresh install of 8.6.13 and am seeing this issue.
Server is Nginx.
Any ideas?
Comment: It's probably something server-/environment- specific, I've done hundreds of D8 installs from 8.0 up to 8.6.13 all over the place and I've never seen that particular error. Have you tried running anything other than Drupal on that PHP instance to make sure PHP sessions are working in general?
Answer: This is an issue with symfony/http-foundation v3.4.24. See https://www.drupal.org/project/drupal/issues/3045844.
Comment: A temporary fix is `composer require symfony/http-foundation:3.4.23`


Trocar linhas de uma matriz

Question: Abaixo está o meu código. Preciso trocar a linha 1 com a 3 e a 2 com a 4.
O problema é que a terceira linha não está trocando e não acho o problema.
    int matriz[TAM][TAM], n = 0, x = 0, y = 0, aux = 0, aux2 = 0, aux3 = 0;

    printf("Informe um tamanho par para sua matriz:  \n");
    scanf("%d", &n);

    for(x = 0; x < n; x++){
        for(y = 0; y < n; y++){

            printf("Preencha a matriz: \n");
            scanf("%d", &aux2);

            matriz[x][y]=aux2;

       }
    }

    for(x = 0; x < n; x++){
        for(y = 0; y < n; y++){
                if (x<=(n/2)){

                aux = matriz[x][y];
                matriz[x][y] = matriz[x+2][y];
                matriz[x+2][y] = aux;
                printf("%d ", matriz[x][y]);
                }

                if ( x==3 ||(x>(n/2)))
                {
                aux3 = matriz[x][y];
                matriz[x][y] = matriz[x-2][y];
                matriz[x-2][y] = aux3;
                printf("%d ", matriz[x-2][y]);
                }

        }

    printf("\n");
    }
   }

Answer: Ao invés de x + 2 e x - 2 que só vai funcionar se for informado 4 para n, use x + n / 2 e x - n / 2.
Aquilo que há de repetido dentro dos dois ifs pode ser movido para antes ou depois deles.
Lembre que o primeiro índice é zero. Isso significa que o seu if (x<=(n/2)), em uma matriz de quatro linhas, irá até a terceira linha, e não até a segunda. O que você queria era usar o < ao invés do <=.
Ao invés de usar if ( x==3 ||(x>(n/2))), bastava usar else. Além disso, devido ao item anterior, deveria ser >= ao invés de >, o que eliminaria a necessidade desse x==3.
No printf do primeiro if, você usa matriz[x][y], mas no do segundo usa matriz[x-2][y].
Você também não precisa de um monte de variáveis aux, apenas um é necessário.
Eis como fica o seu código com essas correções:
int matriz[TAM][TAM], n = 0, x = 0, y = 0;

printf("Informe um tamanho par para sua matriz:  \n");
scanf("%d", &n);

for (x = 0; x < n; x++) {
    for (y = 0; y < n; y++) {
        printf("Preencha a matriz: \n");
        scanf("%d", &matriz[x][y]);
   }
}

for (x = 0; x < n; x++) {
    for (y = 0; y < n; y++) {
        int aux = matriz[x][y];
        if (x < n / 2) {
            matriz[x][y] = matriz[x + n / 2][y];
            matriz[x + n / 2][y] = aux;
        } else {
            matriz[x][y] = matriz[x - n / 2][y];
            matriz[x - n / 2][y] = aux;
        }
        printf("%d ", matriz[x][y]);
    }

    printf("\n");
}

É possível simplificar o seu código um pouco mais e unificar o if e o else ao verificar que a posição da linha que você quer trocar (vamos chamar de nx) pode ser calculada a partir do x assim:
int nx = (x + n / 2) % n;

Para ver como isso funciona, veja que sendo n igual a 4, teremos que:

Se x for 0, nx será 2.
Se x for 1, nx será 3.
Se x for 2, nx será 0.
Se x for 3, nx será 1.

Isso funcionará para qualquer outro valor par de n.
Desta forma, o seu código fica assim:
int matriz[TAM][TAM], n = 0, x = 0, y = 0;

printf("Informe um tamanho par para sua matriz:  \n");
scanf("%d", &n);

for (x = 0; x < n; x++) {
    for (y = 0; y < n; y++) {
        printf("Preencha a matriz: \n");
        scanf("%d", &matriz[x][y]);
   }
}

for (x = 0; x < n; x++) {
    for (y = 0; y < n; y++) {
        int nx = (x + n / 2) % n;
        int aux = matriz[x][y];
        matriz[x][y] = matriz[nx][y];
        matriz[nx][y] = aux;
        printf("%d ", matriz[x][y]);
    }

    printf("\n");
}

Comment: Entendi perfeitamente. Obrigada pela grande ajuda!

Trocar linhas de uma matriz


Inverter uma pilha usando uma pilha adicional e algumas variaveis

Question: Estou precisando inverter uma pilha A utilizando outra pilha adicional B e algumas variáveis em pseudo-codigo. Para que a pilha A seja invertido ao fim do algoritmo. Alguém pode ajudar?
Comment: A pilha B é obrigatóra? Usando [Bubble Sort](https://pt.wikipedia.org/wiki/Bubble_sort) nem chega a ser necessário outra pilha.
Comment: Sim Diego, é obrigatório o uso de uma pilha B e apos inverter na pilha B, utilizar variáveis para retornar os elementos para a pilha A.
Answer: Ao empilhar, o último elemento a entrar torna-se o primeiro a sair.
Sabendo disso, basta remover os elementos da pilha ao mesmo tempo que o adiciona em outra.
Pilha A = 5, 4, 3, 2, 1 (Top)
Pilha B;
Pilha A = 5, 4, 3, 2 (Top)
Pilha B = 1;
Pilha A = 5, 4, 3 (Top)
Pilha B = 1, 2;
etc.
Comment: R.Carvalho, eu preciso inverter pra de A para B, porem eu preciso passar invertido para A de maneira que seja invertido de A inicialmente. Ou seja, eu preciso que a pilha A seja invertida utilizando a B e algumas variaveis para que quando ela voltar pra A esteja totalmente invertida
Comment: No fim desse exemplo, voce vai ter a pilha B invertida a A, agora é preciso passar B para A usando variaveis, a ponto que A seja exatamente como B esta agora, invertida.


Failed to find provider info for browser

Question: I'm on a MOOC in Coursera, and I'm trying to run an application which reads bookmarks and display them.
To do so, I need to set a Permission in the AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="course.labs.permissionslab"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ActivityLoaderActivity"
            android:label="@string/title_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".BookmarksActivity"
            android:label="@string/title_permissions" >
        </activity>
        <activity
            android:name=".GoToDangerousActivity"
            android:label="@string/title_activity_customization" >
        </activity>
    </application>

</manifest>

That prevents to get a SecurityException, However, when I try to run my application on my Android device, I get the following Error in LogCat:
03-02 02:58:13.579: I/Lab-Permissions(15438): Entered loadBookmarks()
03-02 02:58:13.589: W/dalvikvm(15438): threadid=1: thread exiting with uncaught exception (group=0x4166d498)
03-02 02:58:13.589: E/ActivityThread(15438): Failed to find provider info for browser
03-02 02:58:13.589: E/test(15438): Exception
03-02 02:58:13.609: E/AndroidRuntime(15438): FATAL EXCEPTION: main
03-02 02:58:13.609: E/AndroidRuntime(15438): java.lang.NullPointerException
03-02 02:58:13.609: E/AndroidRuntime(15438):    at course.labs.permissionslab.BookmarksActivity.loadBookmarks(BookmarksActivity.java:59)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at course.labs.permissionslab.BookmarksActivity.access$0(BookmarksActivity.java:50)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at course.labs.permissionslab.BookmarksActivity$1.onClick(BookmarksActivity.java:32)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at android.view.View.performClick(View.java:4106)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at android.view.View$PerformClick.run(View.java:17150)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at android.os.Handler.handleCallback(Handler.java:615)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at android.os.Handler.dispatchMessage(Handler.java:92)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at android.os.Looper.loop(Looper.java:137)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at android.app.ActivityThread.main(ActivityThread.java:4792)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at java.lang.reflect.Method.invokeNative(Native Method)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at java.lang.reflect.Method.invoke(Method.java:511)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)
03-02 02:58:13.609: E/AndroidRuntime(15438):    at dalvik.system.NativeStart.main(Native Method)

I don't what's going on, it seems that it doesn't find a provider, but I have two browsers so i don't get it.
This is my BookmarksActivy code, please ignore the "Dangerous Activity" which invokes another stuff.
package course.labs.permissionslab;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Browser;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class BookmarksActivity extends Activity {

    private static final String TAG = "Lab-Permissions";

    static final String[] projection = { Browser.BookmarkColumns.TITLE,
            Browser.BookmarkColumns.URL };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bookmarks_activity);

        Button getBookmarksButton = (Button) findViewById(R.id.get_bookmarks_button);
        getBookmarksButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                loadBookmarks();

            }
        });

        Button goToDangerousActivityButton = (Button) findViewById(R.id.go_to_dangerous_activity_button);
        goToDangerousActivityButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                startGoToDangerousActivity();

            }
        });

    }

    private void loadBookmarks() {

        Log.i(TAG, "Entered loadBookmarks()");

        String text = "";

        Cursor query = getContentResolver().query(Browser.BOOKMARKS_URI,
                projection, null, null, null);

        query.moveToFirst();
        while (query.moveToNext()) {

            text += query.getString(query
                    .getColumnIndex(Browser.BookmarkColumns.TITLE));
            text += "\n";
            text += query.getString(query
                    .getColumnIndex(Browser.BookmarkColumns.URL));
            text += "\n\n";

        }

        TextView box = (TextView) findViewById(R.id.text);
        box.setText(text);

        Log.i(TAG, "Bookmarks loaded");
    }

    private void startGoToDangerousActivity() {

        Log.i(TAG, "Entered startGoToDangerousActivity()");

        Intent dangerous = new Intent(BookmarksActivity.this,GoToDangerousActivity.class);
            startActivity(dangerous);
    }

}

Comment: I have tried by copying and pasting your code, that works fine on my side, no `Exception` no any `Logcat`, then why this does not work for you??
Comment: I met the same too, do you solve this? How?I think this may vary on devices.
Answer: Potentially, your device runs Chrome, rather than the AOSP browser. If so, instead of Browser.BOOKMARKS_URI, use:
Uri.parse("content://com.android.chrome.browser/bookmarks")

i.e.,
Cursor query = getContentResolver().query(Uri.parse("content://com.android.chrome.browser/bookmarks"),
                projection, null, null, null);

Answer: I wonder if browser settings have anything to do with your issue. Go to the "App info" screen for the preferred browser on your device. In the "Launch By Default" tap the "Clear defaults" button and then see what happens.
Answer: download aosp installer from google play store and install browser . your device may not have default browser that comes with Rom.


is_home não funciona dentro de wp_enqueue_scripts

Question: Estou criando um tema e quero especificar quais folhas de estilo serão importadas ao carregar o site, para isso estou usando o hook wp_enqueue_scripts. Dentro dessa action eu faço uma verificação para saber se está na página inicial, se é um single ou se é um archive, ou seja, faço um if(is_home()) com suas variações. Contudo a função is_home está retornando false, embora esteja na página inicial. Já usei wp_reset_query(), mas não resolveu o problema.
Answer: Provavelmente não está funcionando pq vc definiu uma página principal nas configurações do wordpress, no lugar do is_home(), coloque: is_front_page()


Calculate the limit $\lim_{x\to0^+}\frac{\sqrt{\cos(2x)}-\sqrt{1+x\sin(x)}}{\tan^2\frac x2}$

Question: $$\lim_{x\to0^+}\frac{\sqrt{\cos(2x)}-\sqrt{1+x\sin(x)}}{\tan^2\frac x2}$$
I need to calculate this limit  but I don't know what to do for to get out this indeterminate.
I make:

$\sqrt{\cos(2x)}-\sqrt{1+x\sin(x)} = \sqrt{\cos(2*0)}-\sqrt{1+0\sin(0)} = \sqrt{\cos(0)}-\sqrt{1+x\sin(0)} = \sqrt{1}-\sqrt{1} = 0
$
$\tan^2\frac{x}{2} = \frac{0}{2} = 0$

then, $\frac{0}{0}$
I want to get out the $tan^2\frac{x}{2}$.
Comment: Please, write your function using MathJax formatting and show us what you've tried to solve this problem. However today I felt kind enough to write the function in place. Correct it if it doesn't reflect what you meant.
Comment: I not knew to use the MathJax, but I made what I can.
Comment: @Juliana You can't evaluate limits by simply plugging in $0$ to the formula because $0/0$ is undefined. You have to manipulate the function so you can see what the limit would be as you approach $0$.
Answer: $$
\lim_{x\to 0^+}\frac{\sqrt{\cos(2x)}-\sqrt{1+x\sin(x)}}{\tan^2\frac x2}\\[2em]
= \lim_{x\to 0^+}\frac{\sqrt{\cos(2x)}-\sqrt{1+x\sin(x)}}{\tan^2\frac x2} \frac{\sqrt{\cos(2x)}+\sqrt{1+x\sin(x)}}{\sqrt{\cos(2x)}+\sqrt{1+x\sin(x)}}\\[2em]
=\lim_{x\to 0^+}
\frac{1}{\sqrt{\cos(2x)}+\sqrt{1+x\sin(x)}}\
\lim_{x\to 0^+}\frac{\cos(2x)-1-x\sin(x)}{\tan^2\frac x2}\\[2em]
=\frac{1}{2}\
\lim_{x\to 0^+}\frac{\cos(2x)-1-x\sin(x)}{\tan^2\frac x2}
$$
provided the remaining limit exists, but it can be handled using l'hopital or $\frac{\sin x}{x} \to 1$.
Comment: Thank you a lot !!


Angular animate if condition is met

Question: I have an animation in an angular application
@Component({
  selector: 'app-portfolio',
  templateUrl: 'portfolio.page.html',
  styleUrls: ['portfolio.page.scss'],
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({transform: 'translateY(-100%)'}),
        animate('200ms ease-in', style({transform: 'translateY(0%)'}))
      ]),
      transition(':leave', [
        animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
      ])
    ])
  ]
})

However there are two elements in the same position that use it, and they can't be on the screen at the same time. So if I select to show the one element, then the other element will automatically hide. The problem is I just want the element to animate out if the other element isnt being animated in. Is there a way to only show the animation if a condition has been met? Something like this?
  <ion-item color="primary" (element2open === false)=[@slideInOut] *ngIf="openElement1" lines="none">
  </ion-item>
  <ion-item color="primary" (element1open === false)=[@slideInOut] *ngIf="openElement2" lines="none">
  </ion-item>

Comment: Can you set up a stackblitz and set your codes real quick?
Answer: Solution 1:
You can disable animations using:
  @HostBinding('@.disabled')
  public animationsDisabled = false;

This set to your component the css class: ng-animate-disabled
See an example here toggling the checkbox "Toggle All Animations"
Solution 2:
To avoid animations in and out at the same time, you can use sequence() to run animations in given order.
trigger('slideInOut', [
  transition('* => *', [
    sequence([
      query(':enter', [
        style({transform: 'translateY(-100%)'}),
        animate('200ms ease-in', style({transform: 'translateY(0%)'}))
      ], {optional: true}),
      query(':leave', [
        animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
      ], {optional: true})
    ])
  ])
])

This will run first animations enter and second animations leave. Change the order in the array if you want the other way round sequence.
Make sure you annotate the parent with @slideInOut, not the item element.
<parent @slideInOut>
  <ion-item color="primary"  *ngIf="openElement1" lines="none">
  </ion-item>
  <ion-item color="primary" *ngIf="openElement2" lines="none">
  </ion-item>
</parent>

Comment: @MichaelRennison I've added some extra info

Angular animate if condition is met


Where & what I need to change in a file '/etc/php5/apache2/php.ini' to display errors, warnings, exceptions? How should I save the changes I made?

Question: I'm having:

Ubuntu Linux 12.04 LTS
Apache Web Server(Apache httpd 2.4.16)
PHP 5.5.29

Now, whenever something goes wrong in code I always see a white screen in my browser window with no output at all. So, I googled for the solution and come to know that I have to turn the error reporting on in order to get the detailed errors/exceptions/warnings/etc.
And for this I come to know that I need to change php.ini file which Apache web server is making use of.
I opened up the file '/etc/php5/apache2/php.ini' by selecting it with my mouse, right click on the file '/etc/php5/apache2/php.ini', selected the option 'Open With Sublime Text2' and open up the file in  Sublime Text Editor.
I did one small change on line no.466 of '/etc/php5/apache2/php.ini' file as follows :
display_errors = Off //Old code present on line no.466 of php.ini
display_errors = On  //New code changed by me on line no.466 of php.ini

I am not sure is this the only change I need to make to '/etc/php5/apache2/php.ini' file to get errors/warnings/exceptions/etc. Please guide me in detail regarding the changes I need to make to the file '/etc/php5/apache2/php.ini' to get all the possible errors/warnings/exceptions/etc.
Now when I tried to save this file I got a pop-up saying 'Unable to save /etc/php5/apache2/php.ini'.
I'm the owner of my laptop, the system is mine, I am the administrator of my system and still I can't make any change to the file. This is really an un-understandable, useless and strange stuff for me. Previously when I was using PHP on my windows machine such weird things and headache never happened.
Please someone take me out of this bloody mess by giving descriptive and step by step answer.
Few people are saying I have to open up the terminal and type commands there. But I'm not getting What is terminal? Where it is? How to open it? What is root user and what is sudo user? What does each of the users do? What's the difference in between them? The purpose of graphical text editor is to manipulate files and this Ubuntu is preventing me from doing it.
Everything is strange here with Ubuntu Linux. What's the use of it? etc.
Comment: edit the file as root by launching your editor with `sudo`
Comment: Windows has a similar feature called User Account Control
Comment: @Joe : I simply right clicked the file with my mouse and selected the option 'Open With Sublime Text 2' just I do on Windows. Now I'm not getting you what are you saying by means of 'edit the file as root by launching the editor with sudo'. How should I launch the Sublime editor with sudo while I right click to open up the file? Tell me clearly.
Comment: @Joe: I never faced such kind of time consuming and useless issues on Windows OS.
Comment: Did you ever read the error log of your apache web server?
Comment: @user2839497: Did you checked my solution?
Answer:
What is terminal?

Terminal is an interface where you execute your commands. More details here. Its like cmd in windows.

Where it is? How to open it?

Open the Dash (Dash is similar to the Start button in windows)

and type terminal.

The black board like icon with >_ is your terminal, click on it.

This is what a terminal looks like.

What is root user and what is sudo user?  What does each of the users
  do? What's the difference in between them?

Quoted from Ubuntu docs
In Linux (and Unix in general), there is a SuperUser named root. The Windows equivalent of root is the Administrators group. The SuperUser can do anything and everything, and thus doing daily work as the SuperUser can be dangerous. You could type a command incorrectly and destroy the system. Ideally, you run as a user that has only the privileges needed for the task at hand. In some cases, this is necessarily root, but most of the time it is a regular user.
By default, the root account password is locked in Ubuntu. This means that you cannot login as root directly or use the su command to become the root user. However, since the root account physically exists it is still possible to run programs with root-level privileges. This is where sudo comes in - it allows authorized users to run certain programs as root without having to know the root password.
Editing the php.ini file:
Now that you know what terminal is, open the terminal and type:
sudo vi /etc/php5/apache2/php.ini

Note: There are various other editors, like nano, gedit etc.
You'll be prompted to enter the password:
[sudo] password for user:

Just type in the password and hit enter. You'll see the contents of php.ini in the terminal. Now, scroll and search for the line Display_errors =off. You will have to change this to Display_errors =on, to do this change press i, make your changes, press esc, press shift+q type wq! and hit enter.
Now, you will have to restart apache to have the changes take effect. So, type:
sudo service apache2 restart

and hit enter. Thats it. Hope that gives you an idea :)
Answer: Regarding php.ini
You can do runtime change in all settings of your php.ini or by editing php.ini.
You should keep error_reporting false by default. And in development you can make reporting on runtime.
error_reporting(E_ALL);
ini_set("display_errors", 1);

Do this only if you are in development mode to see all fatal/parse errors or set error_log to your desired file to log errors instead of display_errors in production (this requires log_errors to be turned on).
Regarding file changes
php.ini needs to be edited by root user.
So you can edit by terminal:

Open terminal
Switch user as root
Edit php.ini by vi editor and do changes.
Restart apache server

Or If you still want to edit by sublime

Open php.ini by sublime with root access
You need do required changes in php.ini
Restart apache server
Answer: Terminal
The terminal is an interface in which you can type and execute text based commands.
Think of it like cmd in windows.
How to run it:
Open the Dash (Super/window Key) or Applications and type terminal, or use the keyboard shortcut by pressing Ctrl+Alt+T.
As this is to broad, and you actualy don't need terminal for your problem; for a great explanation of terminal please see: What is a terminal and how do I open and use it?.
Display error settings in php.ini
There are 2 settings you must edit:

error_reporting = E_ALL
Make sure it only have the value E_ALL.
E_ALL = Show all errors, warnings and notices including coding standards.
E_NOTICE = Show notices
E_STRICT = Show coding standard warnings
if you put ~ in-front it, it means Except.
display_errors = On

Unix-like OS file permissions

In unix-like OSes, files and directories are owned by a user and distinct permissions (read, write, run) apply to the owner.

These are very simplified explanation:
The '/etc/php5/apache2/php.ini' file is owned by root and with write permission only for root, so you can't edit it unless you are the user root itself.
But there is a way for you to edit files owned by another user, and that is with a command: sudo (superuser do ...), or gksu/gksudo for graphical interfaces software.
You may think that your username is another administrator/SuperUser, so why can't you just edit and save the file? Well, in actual you are not. Your user is just a regular user, but with permission to do SuperUser task. In other word you are just a sudo user (sudoers).

So the only way for you to save the changes you made, is to run Sublime Text using root privilege.
This can be achieved from the terminal by executing it via command: sudo sublime or gksu sublime.
Or without terminal:
via Dash (press super/window key), just type gksu sublime and press enter (you will be asked for your password).
This makes you run sublime text editor as root user, so now you can open the '/etc/php5/apache2/php.ini' file and edit it and save it.
(If you don't have gksu, install it via Ubuntu Software Installer.)
Answer: I use gksudo and gedit to do the job.
gksudo makes it possible to open a graphical interface. Gedit is the default text editor for GNOME. If you have KDE, then will you use kedit.
First I find the correct location of the used configuration file. You can find it easily making a php file calling the function php_info.
The content of the php file is a call to one function:
  phpinfo();

That is it. I always have a file info.php in the documentroot of apache (in Ubuntu /var/www. Then I make a call to that file with:
http://localhost/info.php

and a document containing a lot of information will be returned. In it, you have a configuration value:
    Loaded Configuration File
The value on that line is the php file that is used by the apache server. You should edit that file in order to see errors displayed. Lets call that value %phpini-file%.
Next I open a terminal
(see https://help.ubuntu.com/community/UsingTheTerminal)
 and type
gksudo gedit %phpini-file%

and I do traverse the file until I see error handling and logging.
After that you will find the variables that you would like to be changed.
On a development machine I set the variable error_reporting to:
error_reporting = E_ALL

The documentation in the file gives you good suggestions.
Underneath that variable you have the variables display_errors, display_startup_errors and log_errors. I always give those variables the values On on my development machine.
Some lines below that you have the variable track_errors. I put it to On.
After making those changes will you have to restart apache.
The way I do it is:
sudo /etc/init.d/apache2 restart

It is equivalent to
sudo service apache2 restart

but it is how I have remembered it.
Instead of a terminal you can type ALT + F2 and you will see a command line appear in the midst of your screen. Next you type your command and the action will be performed.
Root is the user that has all privileges on an unix based system. Sudo is an abbreviation of super user do and makes it possible to execute commands as if someone is root. The whole root concept makes it safe that not any user can do anything on the system. You must be root or otherwise get sudo privileges in order to make changes on the system.
Answer: You just need to press

Ctrl + Alt + T

and you'll see a window appearing, which is nothing but the Terminal.
There you just need to type :
sudo gedit /etc/php5/apache2/php.ini

[Gedit is nothing but the default linuk editor]
After that you'll be asked to enter the password, where you need to enter your system's password.
The file will open in the editor, just find Display_Errors in that page and replace off with on, so it will be :

Display_Errors=on

After the changes save and close that file.
And just restart your apache by typing this command on the TERMINAL again :
sudo /etc/init.d/apache2 restart


Select MySQL results, ignoring fields that have a count greater than X

Question: I have the following MySQL table setup that logs site visits:
id   timestamp   ip   tracking

id = auto generated
timestamp = standard datetime
ip = users ip address
tracking = a tracking code that is passed via the URL

The purpose of this tracking is various forwarded domains are sent to this one site with this script running.  The script logs the ip and timestamp, and grabs the tracking code from the URL.
What we are tying to do is have a rollup count of all tracking codes used, however, there are a LOT of spam requests (bots) hitting the site.  I'm trying to figure out the best way to filter out results that I think are bots, I don't want them counted in the final results.
My initial thought was to first filter out all ips that occur more than once.  My problem is, how do I then use the results of that query to go back and count the tracking codes?
My code to filter ips that only show once is:
SELECT tracking, ip, COUNT( * )
FROM tracking
GROUP BY ip
HAVING COUNT( * ) =1
ORDER BY COUNT( * ) DESC

How do I then take those results and run another query to then count and sum up the tracking codes?
-Kevin
EDIT:
Sorry, first post here and I rushed a little.  In the end, what I'm looking for is to get the count of all the tracking codes used.
Let's assume I have the following table data:
id       timestamp               ip             tracking
--       ---------               --             --------
1        2014-01-10 23:43:10     192.168.1.1    100
2        2014-01-10 23:43:10     192.168.1.1    200
3        2014-01-10 23:43:10     192.168.1.2    100
4        2014-01-10 23:43:10     192.168.1.1    999
5        2014-01-10 23:43:10     192.168.1.1    100
6        2014-01-12 23:43:10     192.168.1.1    100
7        2014-01-12 23:43:10     192.168.1.3    100
8        2014-01-12 23:43:10     192.168.1.4    100
9        2014-01-12 23:43:10     192.168.1.5    600
10       2014-01-12 23:43:10     192.168.1.1    888
11       2014-01-12 23:43:10     192.168.1.1    888
12       2014-01-12 23:43:10     192.168.1.8    200
13       2014-01-12 23:43:10     192.168.1.9    300
14       2014-01-12 23:43:10     192.168.1.10   100
15       2014-01-12 23:43:10     192.168.1.11   400
16       2014-01-12 23:43:10     192.168.1.1    888
17       2014-01-12 23:43:10     192.168.1.12   200
18       2014-01-12 23:43:10     192.168.1.2    777
19       2014-01-12 23:43:10     192.168.1.2    100
20       2014-01-12 23:43:10     192.168.1.1    200
21       2014-01-12 23:43:10     192.168.1.4    789

In the end I want to display a count of all tracking codes used, but to ignore any rows where an ip address looks to be from a bot.  Because of the nature of this setup, we kind of assume that ip addresses would only hit the site once, maybe twice.  So I figure, if I can get the count of tracking codes, excluding any row where the ip address is greater than 1 (or maybe 2).
So the final result from that data set would be
tracking  count
--------  -----
100         3
200         2
300         1
400         1
600         1
789         1

Basically from the results we are not counting anything from 192.168.1.1 and 192.168.1.2 because those ips visited more than 1 time.
EDIT  - I added a row #21 to have one of the IPs visit twice, therefore both of their visits should count if we are using <3 in the query.  It looks like the below answer isn't working correctly.  When I add the row #21, the code 789 doesn't get counted
Hope this helps understand it better?
I know how to get the overall count of either ips or tracking, but I can't figure out how to put the two together in one query.
-Kevin
EDIT 2/4/14 - So I what I think is happening is the query below is only counting the tracking code of the first instance of the IP.  So in the case let's change the table to have a better set of data
id       timestamp               ip             tracking
--       ---------               --             --------
1        2014-01-10 23:43:10     192.168.1.1    100
2        2014-01-10 23:43:10     192.168.1.222  100
3        2014-01-10 23:43:10     192.168.1.1    200
4        2014-01-10 23:43:10     192.168.1.2    100
5        2014-01-10 23:43:10     192.168.1.1    999
6        2014-01-12 23:43:10     192.168.1.1    100
7        2014-01-12 23:43:10     192.168.1.2    100
8        2014-01-12 23:43:10     192.168.1.3    100
9        2014-01-12 23:43:10     192.168.1.4    100
10       2014-01-12 23:43:10     192.168.1.5    600
11       2014-01-12 23:43:10     192.168.1.1    888
12       2014-01-12 23:43:10     192.168.1.1    888
13       2014-01-12 23:43:10     192.168.1.8    200
14       2014-01-12 23:43:10     192.168.1.9    300
15       2014-01-12 23:43:10     192.168.1.10   100
16       2014-01-12 23:43:10     192.168.1.11   400
17       2014-01-12 23:43:10     192.168.1.1    888
18       2014-01-12 23:43:10     192.168.1.12   200
19       2014-01-12 23:43:10     192.168.1.222  777
20       2014-01-12 23:43:10     192.168.1.2    100
21       2014-01-12 23:43:10     192.168.1.1    200
22       2014-01-12 23:43:10     192.168.1.4    789

In this case, I would want the query to be where any IP appears 2 or less times.  So the results SHOULD be:
tracking  count
--------  -----
100         4
200         2
300         1
400         1
600         1
777         1
789         1

Basically, 192.168.1.1 and .2 are the only ones that appear more than 2 times, so they should be excluded.  Some IPs, like .4 and .222 appear twice, which is fine, but each time they use a different code.
Using the query below:
select xyz.tracking,count(xyz.tracking) as `count` from (select ip,count(ip),tracking from tracking group by ip having count(ip)<3) xyz group by xyz.tracking;

I seems to only pick up the code for the first instance of each IP.  So the results I get are:
tracking  count
--------  -----
100         4
200         2
300         1
400         1
600         1

So in this case it's picking up the code 100 for IP .222 but not the code 777 for IP .222
It's picking up code 100 for IP .4 but not the code 789 for IP .4.
Anyone have any ideas how to resolve this?
EDIT: So I think I have a solution. It's returning the correct values.  Can someone verify?
SELECT t.tracking, count(t.tracking) as COUNT FROM tracking t
JOIN (
    SELECT s.ip, count(s.ip) FROM tracking s GROUP BY s.ip HAVING COUNT(s.ip)<=2) d
ON d.ip = t.ip
GROUP BY t.tracking

Comment: If you want to be ANSI standard, enable `ONLY_FULL_GROUP_BY`.
Comment: Sorry about that.....I have edited the post and given some example data and what the end result should be.  Hopefully this helps explain it.
Comment: Everybody visited at exactly the same time? Also, this seems like a crude way of eliminating bots - in fact, I'm not sure I understand the logic, although that doesn't mean I necessarily have a better idea!
Comment: Timestamp wasn't really important in this case so I just copy pasted the same data.  All we are trying to accomplish is weed out the entires (which amount in the thousands) which aren't real people.  The end result is to understand the best tracking codes used (which correlate to the original domains used)
Answer: I believe I found the answer in case anyone else needs a query like this.
SELECT t.tracking, count(t.tracking) as COUNT FROM tracking t
JOIN (
    SELECT s.ip, count(s.ip) FROM tracking s GROUP BY s.ip HAVING COUNT(s.ip)<=2) d
ON d.ip = t.ip
GROUP BY t.tracking

Answer: Try this one:
select xyz.tracking,count(xyz.tracking) as `count` from (select ip,count(ip),tracking from tracking group by ip having count(ip)<3) xyz group by xyz.tracking;

Comment: Sorry, I was really bad in my initial description and have edited it.
Comment: That's it.  Thank you....couldn't wrap my head around the subquery syntax.  Thank you!
Comment: I'm not sure that query is working correctly after testing.  It was in the initial case, but I just edited my data set and added row #21.  This one is 192.168.1.4, has a different tracking code (789), however, 192.168.1.4 previously visited with code 100.  In the current SQL statement you gave me, row #21 doesn't come up in the results.  Shouldn't it since the count for 192.168.1.4 is less than 3?
Comment: Is your query somehow not returning the 789 tracking code because it's only grabbing the first code for each IP?
Comment: do you think that a single query will fulfill all the requirements?
Comment: yes I edited my original post with a modified query that seems to work correctly.  It is slower with the JOIN, but I indexed the IP column to speed things up.  If you see something wrong with it, please let me know.
Comment: if you are getting the expected result in all the cases, your query is fine. Since, you have the application and data, you are the best one to verify your query. Performance improvement of your query is another section.


Regarding T-Test for point hypotheses

Question: I have, so far only conducted hypotheses tests having the null hypothesis as a point hypothesis while the research hypothesis is composite.
But what procedure shall I follow if my research hypothesis is a point hypothesis? In particular, my research hypothesis states that the differences in mean of two populations is zero. I wish to test this hypothesis.
Thank you.
Answer: Point hypothesis is always false, since the point is infinitely small, the probability of an effect to be exactly that point is 0.
What you can do is equivalence testing, where you wouldn't test exactly zero, but close to zero within some margin that is close enough for you.
See for example Lakens 2018 https://doi.org/10.1177/2515245918770963  but there are many ways to do it. Informally, you can just look if the edges of your confidence interval are close enough to 0

Regarding T-Test for point hypotheses


Arduino data type confusion. Have string, need const char?

Question: I'm working with an UNO and I'm using maniacbug's RF24 library with soft spi, and his rf24network library. https://github.com/maniacbug/RF24Network
All I'm trying to do is send data but I'm stuck with the wrong data type.
{
last_sent = now;

printf("Sending...\r\n");
const char* hello = "Hello, world!";
RF24NetworkHeader header(/*to node*/ other_node);
bool ok = network.write(header,hello,strlen(hello));
if (ok)
  printf("\tok.\r\n");
else
{
  printf("\tfailed.\r\n");
  delay(250); // extra delay on fail to keep light on longer
}
}

If I change it to
bool ok = network.write(header,myString,strlen(myString));

I get an error on data type.  So how do I get my string to fit this structure.  My thought was to to a myString.toCharArray then maybe loop through that?
Comment: What is `myString` and how is it declared??
Comment: @TheEditor - you should just use the `c_str()` method of the String class in the call to `network.write` I.e `network.write(header, myString.c_str(), myString.length());`
Answer: Convert the String into a char array first:
size_t len = myString.length();
char buf[len+1]; // +1 for the trailing zero terminator
myString.toCharArray(buf, len);

and then you can pass buf:
bool ok = network.write(header,buf,strlen(buf));


How to Identify a homogeneous first order first degree ODE

Question: The following equation is homogeneous edit: y dx - x dy + 3x^2y^2e^(x^3) dx = 0 (source: Wolfram alpha)
but it is not of the form of $f(zx,zy)= z(f(x,y))$. How do I identify such type of special Homogeneous equation that do not fit the definition?
Answer: Substituting $t=xy $ we have $y'= \left(\frac{t}{y}\right)' =\frac{t'x -t}{x^2 }$ thus we have $$\frac{t'x -t}{x^2 } =y' =\frac{dy}{dx} =\frac{y -y^3 x^2}{x+ x^3 y^2} =\frac{\frac{t}{x} -\frac{t^3}{x}}{xt^2 +x} =\frac{1}{x^2}\cdot \frac{t-t^3}{t^2 +1}$$
hence
$$t'x -t =\frac{t-t^3}{t^2 +1}$$
and $$t'x =\frac{t-t^3 +t +t^3}{t^2 +1} =\frac{2t}{1+t^2} $$
therefore
$$\left( \frac{1}{2t} +\frac{1}{2} t\right)dt =\frac{dx}{x}$$
so the solution is $$\frac{1}{2}\ln |t| +\frac{1}{4} t^2 = \ln |x| +C$$
Comment: But How do I Check For it is Homogeneous or not? As the above equation is found to be Homogeneous it can be solved By Putting y=v*x.
Comment: It is not homogeneous in the sense that you're write above.
Comment: I got it , i actually posted the wrong question..... can you plz tell me to check homogeneous equations for such types :-  y dx - x dy + 3x^2y^2e^(x^3) dx = 0
Comment: If you have equation of the form $$P(x,y ) dx +Q(x,y ) dy =0$$ then it is homogenous if and only if the function $$\xi (x,y )=\frac{Q(x,y)}{P(x,y)}  $$ is homogenous i.e. $$\xi (tx,ty ) =\xi (x,y).$$


How is the anatomy of memory mapped Kernel space

Question: I try to understand the mechanism in Linux of mapping kernel mode space into user mode space using mmap.
First I have a loadable kernel module (LKM) which provides a character device with mmap-functionality. Then a user space application open the device and calls mmap the LKM allocate memory space on the heap of the LKM inside the kernel mode space (virtual high address). On user space side the data pointer points to a virtual low address.
The following picture shows how I imagine the anatomy of memory is. Is this right?

Please let me know if question is not clear, I will try to add more details.

Edit: The picture was edited regarding to Gil Hamilton. The black arrow now points to a physical address.
Comment: Yes. That's basically correct. I would draw it with the heavy black arrow pointing to the right. That is, it's sharing the same physical pages. It doesn't get the same virtual address as the kernel and it doesn't somehow "point to" the kernel data area. Instead it gets its own independent mapping to the same physical memory pages.
Comment: Yes. In that model, the kernel virtual address space is the top 1GB (for x86 32bit). The user-mode space is the bottom 3GB. So they do share the 4GB virtual address space. When there is a context switch, a new page table is installed. It has the same mappings for the top 1GB but new mappings for the user mode of the new process. However, user mode can never access the top 1GB (i.e. if it attempts to access that memory, it will receive a `SIGSEGV` due to page table access restrictions). Kernel mode *can* technically access user-mode space directly, though it's generally done through an API.
Comment: Often I can read that every thread in Linux get a own virtual memory region split into a 1GB kernel and a 3GB user space. In this case: Do some parts of the kernel module lay inside kernel space part of the user space application?
Comment: @GilHamilton Can you put your comments as an answer?
Answer: The drawing is missing out a few important underlying assumptions.
The kernel does not need to mmap() to access user space memory. If a user process has the memory, it's already mapped in the address space by definition. In that sense, the memory is already shared between user and kernel.
mmap() creates a new region in user's virtual address space, so that the address region can be populated by physical memory if later accessed. The actual allocation of memory and modifying the page table entry is done by the kernel.
mmap() only makes sense for managing user-half of the virtual address space. Kernel-half of the address space is managed completely differently.
Also, the kernel-half is shared by all processes in the system. Each process has its dedicated virtual address space, but the page tables are programmed in such a way that the page table entries for the kernel-half are set exactly the same for all processes.
Again, the kernel does not mmap() in order to access user space memory. mmap() is rather a service provided by kernel to user to modify the current mapping in user's virtual address space.
BTW, the kernel actually has a few ways to access user memory if it wants to.
First of all, the kernel has a dedicated region of kernel address space (as part of its kernel space) which maps the entirety of the physical memory present in consecutive fashion. (This is true in all 64-bit system. In 32-bit system the kernel has to 'remap' on-the-fly to achieve this.)
Second, if the kernel is entered via a system call or exception, not by hardware interrupt, you have valid process context, so the kernel can directly "dereference" user space pointer to get the correct value.
Third, if kernel wants to deference a user space pointer of a process while executing in a borrowed context such as in an interrupt handler, kernel can trace process's virtual address by traversing the vm_area_struct tree for permission and walking the page table to find out actual physical page frame.
Answer: You can check the memory regions by iterating through vma's "struct vm_area_struct" through current.
If you walk pagetables and derive mapped physical addresses for virtual addresses which is not related to user space then memory layout will be more clear.
Apart from this minor correction in this figure,
BSS is not a segment but section which is embed to Data segment, refer ELF specification for more details, linker script


There is no ftp menu in Visual Studio 2022 publish menu. How can I publish via ftp?

Question: I'm trying to create an app via C# WPF and deploy it as an ftp server.
And this is my development environment.
C#(WPF), Visual Studio Community 2022, .NET 6.0
I went into the properties of the solution as it says on the internet.
And when I go to posting, the ftp menu is not visible.
Is there no way I can distribute the app via ftp?
Comment: I guess it could be because of payloads not selected during installation; not sure. Try adding ASP.NET
Answer: For Wpf application publish list will be as you can see. FTP/FTPS server options will be lost.
You can create an ASP.NET Core Web App to check it out.


Mathematician wants the equivalent knowledge to a quality stats degree

Question: I know people love to close duplicates so I am not asking for a reference to start learning statistics (as here).
I have a doctorate in mathematics but never learned statistics. What is the shortest route to the equivalent knowledge to a top notch BS statistics degree and how do I measure when I have achieved that.
If a list of books would suffice (assuming I do the exercises lets say), that's terrific. Yes, I expect working out problems to be an implicit part of learning it but I want to fast track as much as realistically possible. I am not looking for an insanely rigorous treatment unless that is part of what statistical majors generally learn.
Comment: Try reversing "statistician wants equivalent knowledge to a quality maths degree" - there is not likely to be any fast routes.
Comment: Could you share with us *why* you want to learn stats?  Curiosity?  Needed for a project or research?  Wanting to change jobs?  Need to teach some courses?  Want to collaborate with statisticians as the theoretical person?
Comment: I think it's almost always important to develop domain-specific expertise as well. A lot of statistics is learning the models relevant to specific fields.
Comment: Roll a dice 100 times and you are done. ;)
Comment: what field of mathematics you received your doctorate? This might be relevant.
Comment: It would be useful in my work which involves a heavy amount of machine learning. It would also be useful at times as my (very small) company occasionally could use a genuine statistician.
Answer: (Very) short story
Long story short, in some sense, statistics is like any other technical field: There is no fast track.
Long story
Bachelor's degree programs in statistics are relatively rare in the U.S. One reason I believe this is true is that it is quite hard to pack all that is necessary to learn statistics well into an undergraduate curriculum. This holds particularly true at universities that have significant general-education requirements.
Developing the necessary skills (mathematical, computational, and intuitive)  takes a lot of effort and time. Statistics can begin to be understood at a fairly decent "operational" level once the student has mastered calculus and a decent amount of linear and matrix algebra. However, any applied statistician knows that it is quite easy to find oneself in territory that doesn't conform to a cookie-cutter or recipe-based approach to statistics. To really understand what is going on beneath the surface requires as a prerequisite mathematical and, in today's world, computational maturity that are only really attainable in the later years of undergraduate training. This is one reason that true statistical training mostly starts at the M.S. level in the U.S. (India, with their dedicated ISI is a little different story. A similar argument might be made for some Canadian-based education. I'm not familiar enough with European-based or Russian-based undergraduate statistics education to have an informed opinion.)
Nearly any (interesting) job would require an M.S. level education and the really interesting (in my opinion) jobs essentially require a doctorate-level education.
Seeing as you have a doctorate in mathematics, though we don't know in what area, here are my suggestions for something closer to an M.S.-level education. I include some parenthetical remarks to explain the choices.

D. Huff, How to Lie with Statistics. (Very quick, easy read. Shows many of the conceptual ideas and pitfalls, in particular, in presenting statistics to the layman.)
Mood, Graybill, and Boes, Introduction to the Theory of Statistics, 3rd ed., 1974. (M.S.-level intro to theoretical statistics. You'll learn about sampling distributions, point estimation and hypothesis testing in a classical, frequentist framework. My opinion is that this is generally better, and a bit more advanced, than modern counterparts such as Casella & Berger or Rice.)
Seber & Lee, Linear Regression Analysis, 2nd ed. (Lays out the theory behind point estimation and hypothesis testing for linear models, which is probably the most important topic to understand in applied statistics. Since you probably have a good linear algebra background, you should immediately be able to understand what is going on geometrically, which provides a lot of intuition. Also has good information related to assessment issues in model selection, departures from assumptions, prediction, and robust versions of linear models.)
Hastie, Tibshirani, and Friedman, Elements of Statistical Learning, 2nd ed., 2009. (This book has a much more applied feeling than the last and broadly covers lots of modern machine-learning topics. The major contribution here is in providing statistical interpretations of many machine-learning ideas, which pays off particularly in quantifying uncertainty in such models. This is something that tends to go un(der)addressed in typical machine-learning books. Legally available for free here.)
A. Agresti, Categorical Data Analysis, 2nd ed. (Good presentation of how to deal with discrete data in a statistical framework. Good theory and good practical examples. Perhaps on the traditional side in some respects.)
Boyd & Vandenberghe, Convex Optimization. (Many of the most popular modern statistical estimation and hypothesis-testing problems can be formulated as convex optimization problems. This also goes for numerous machine-learning techniques, e.g., SVMs. Having a broader understanding and the ability to recognize such problems as convex programs is quite valuable, I think. Legally available for free here.)
Efron & Tibshirani, An Introduction to the Bootstrap. (You ought to at least be familiar with the bootstrap and related techniques. For a textbook, it's a quick and easy read.)
J. Liu, Monte Carlo Strategies in Scientific Computing or P. Glasserman, Monte Carlo Methods in Financial Engineering. (The latter sounds very directed to a particular application area, but I think it'll give a good overview and practical examples of all the most important techniques. Financial engineering applications have driven a fair amount of Monte Carlo research over the last decade or so.)
E. Tufte, The Visual Display of Quantitative Information. (Good visualization and presentation of data is [highly] underrated, even by statisticians.)
J. Tukey, Exploratory Data Analysis. (Standard. Oldie, but goodie. Some might say outdated, but still worth having a look at.)

Complements
Here are some other books, mostly of a little more advanced, theoretical and/or auxiliary nature, that are helpful.

F. A. Graybill, Theory and Application of the Linear Model. (Old fashioned, terrible typesetting, but covers all the same ground of Seber & Lee, and more. I say old-fashioned because more modern treatments would probably tend to use the SVD to unify and simplify a lot of the techniques and proofs.)
F. A. Graybill, Matrices with Applications in Statistics. (Companion text to the above. A wealth of good matrix algebra results useful to statistics here. Great desk reference.)
Devroye, Gyorfi, and Lugosi, A Probabilistic Theory of Pattern Recognition. (Rigorous and theoretical text on quantifying performance in classification problems.)
Brockwell & Davis, Time Series: Theory and Methods. (Classical time-series analysis. Theoretical treatment. For more applied ones, Box, Jenkins & Reinsel or Ruey Tsay's texts are decent.)
Motwani and Raghavan, Randomized Algorithms. (Probabilistic methods and analysis for computational algorithms.)
D. Williams, Probability with Martingales and/or R. Durrett, Probability: Theory and Examples. (In case you've seen measure theory, say, at the level of D. L. Cohn, but maybe not probability theory. Both are good for getting quickly up to speed if you already know measure theory.)
F. Harrell, Regression Modeling Strategies. (Not as good as Elements of Statistical Learning [ESL], but has a different, and interesting, take on things. Covers more "traditional" applied statistics topics than does ESL and so worth knowing about, for sure.)

More Advanced (Doctorate-Level) Texts

Lehmann and Casella, Theory of Point Estimation. (PhD-level treatment of point estimation. Part of the challenge of this book is reading it and figuring out what is a typo and what is not. When you see yourself recognizing them quickly, you'll know you understand. There's plenty of practice of this type in there, especially if you dive into the problems.)

Lehmann and Romano, Testing Statistical Hypotheses. (PhD-level treatment of hypothesis testing. Not as many typos as TPE above.)

A. van der Vaart, Asymptotic Statistics. (A beautiful book on the asymptotic theory of statistics with good hints on application areas. Not an applied book though. My only quibble is that some rather bizarre notation is used and details are at times brushed under the rug.)
Comment: @John Salvatier, you're correct that those methods aren't covered in this text. Then again, this strikes me as more a matter of taste, particularly since the text's main focus is not on algorithms. To wit, your concerns are directly addressed by the authors in the introduction (pg. 13).
Comment: @cardinal: Scandinavian universities usually do offer bachelors level degrees as well. That being said, I think statisticians take themselves a bit too seriously. I disagree that you'd need a doctorate degree in order to get an "interesting" job. I believe that as science and research becomes more and more cross-disciplinary statistics have been imposed on studies from many different areas. Half of the articles on high impact journals have some questionable statistical analysis, just to meet the demands, even though it might not make any sense, given in original context/domain of the problem.
Comment: @cardinal, ex-Soviet universities have separate undergraduate statistics studies. In Vilnius University for example you can get bachelor degree in statistics. From what I see with the students I wholeheartedly agree that master or even doctorate-level education is needed for interesting jobs.
Comment: @cardinal, @mpiktas 4 years in BS + 2 yearts in MS + 4 years in PhD makes ten years to learn something interesting :) I would give $+\infty$ to this great answer if possible. Most books are new to me.
Comment: @cardinal Mood book was a great suggestion because nowadays it is difficult to find an introductory book on statistics that is formal enough for someone with a math background. Has anybody read this book new book?
Panateros, "Statistics for Mathematicians" https://www.springer.com/us/book/9783319283395
Comment: @cardinal: ignoring any quibbling over one text vs. another, the only thing I see in your list that is a serious omission is the lack of a reference on robust statistics. Maronna, Martin, and Yohai is a decent choice, or you can go 'classic' and put Huber or Hampel in there.
Comment: @Wesley: Thanks for the comment. Yes, explicit mention of robust statistics is missing. However, I haven't neglected it completely. Section 3.13 of Seber & Lee gives a nice 15-page introduction and several chapters of van der Vaart also deal with robust statistics. So, it's in there, if in slightly disguised form. Huber (1981) is a delightful little book, but I think it'd probably have to go under the "advanced" category in my list above.
Comment: I had a look at Boyd & Vandenberghe, Convex Optimization as it appears to be available online for free, and I found it a bit concerning. It had no mention of any of the following phrases: "conjugate gradient" "BFGS" "Broyden"(of BFGS). Those are standard modern methods, so I am confused why they would not be at least mentioned.
Comment: @John, My personal interpretation of the intent of this text is to provide the machinery necessary to *recognize* a problem as falling within the class of convex optimization problems rather than develop the algorithmic tools necessary to solve them (though some of this *is* presented) safely. Perhaps an appropriate analogy can be found in the standard treatments of linear regression.
Comment: I would also recommend Boyd and Vandenberghe, especially if it is available for free.
Comment: [continuation from previous comment] ... I dont know if this is the case with the OP, but I can definitely relate to the dilemma of trying to fast forward, especially if you are done with your education. It's simply unrealistic to go through a long list of books, exercises and spend months and years to be able to do your job, which might not have anything to do with theoretical statistics... (I'm sorry if I sound too frustrated)
Comment: @posdef, I certainly empathize with your feelings of frustration. I take a little issue with some remarks that you've made that I suspect are mostly a product of this frustration. To respond to your comments completely would require an essay. Modern applied statistics is a mathematically and computationally sophisticated field which requires a fairly high degree of specialized knowledge. It strikes me as a bit presumptuous to want to become good/competent in the field without putting in the effort. Click on the link I provided for a more eloquent version of this.
Comment: As someone who originally came from another discipline, I understand the desire to learn quickly enough to be productive. Unfortunately, my experience is that that is difficult and potentially dangerous. What is your background? If someone with a B.S. In statistics came to you and said "I need to know your field. Make me an expert as quickly as possible," what would you realistically suggest to them? When would *you* feel safe calling them an expert and handing them their own project that *your* business or livelihood depended on?
Comment: Like I said, I think a well-thought-out essay is needed and this is hardly a good format for it, unfortunately. The points you raise regarding poor statistical analysis in the literature are valid. My argument would be that this is often due to precisely the problem we are trying to address in this thread. There are many, *many* people doing statistics without fully grasping what they are doing. There are also too few statisticians that have sufficient domain expertise in the area of application they are working in.
Comment: @cardinal: While I mostly agree with you, what I find highly troubling is the assumption of "interest to master" the field of statistics. When I ask, or answer, a question on StackOverflow, I don't make assumptions on intentions to master anything, I only intend to learn to solve my problems. Likewise I don't assume people want to master the field of programming when they ask something there. Mastery, as you have mentioned, comes over time and effort of course. My experience SO vs CV and statistics vs programming have been bitterly different in terms of help/utility :(
Comment: @posdef, thanks for your comments. My response was tailored to the question of the OP who "wanted the equivalent knowledge of a quality stats degree." I read that as a desire for a certain degree of mastery. While programming requires a very significant degree of both logic and creativity, I would speculate that most of the questions on SO are about more direct implementation issues. CV is more geared towards helping others understand and apply statistics, which generally requires a deeper dialogue with the OP to do well (correctly) and involves addressing more subtleties. My $0.02.
Comment: @cardinal: ah, i guess you're right... I'm sorry for creating an off-topic discussion like this, and for being very bitter on the subject. I gotta work on that, somehow.
Comment: @posdef, no worries. The discussion is interesting (to me) nonetheless. The best way to fight the feelings of frustration is to continue to learn when the opportunity arises. I, for one, am glad to have your participation here. Applied statistics as a field will only continue to grow through positive interactions with those interested in its applications. I would argue that in many cases the reverse is true as well.
Comment: @cardinal: thanks! I'm trying to get rid of the prejudice and the frustration by trying to ignore the negative sides, and try to figure out the right "mindset". I believe science is somewhat like language, you'll never be fluent unless you learn to think in that language instead of thinking in some other language and translating in your head. We'll see how well that works out for me... :)
Comment: @cardinal: You make many good points. Two experiences I might add, once I had summer student who had just finished a Phd in math and wanted to switch to statistics - they had a very hard time getting that statistics was just not identifying functions and then doing calculations. Another time I had clients who had Phds in biophsyics with a lot of math. They were the least affected by any advice I offered...
Comment: Agresti's categorical book is now in its 3rd edition.
Comment: @cardinal I have a PhD in Functional analysis, particularly dealing with Banach space theory. I am looking to learn more about time series forecasting models such as ARIMA, GARCH, etc. I particularly like Brockwell and Davis's Theory and Methods book as they really provide rigour. Do you happen to know any other books that are similar levels to Borckwell and Davis?
Comment: Is Convex Optimisation that useful for statisticians to know?
Answer: I can't speak for the more rigorous schools, but I am doing a B.S. in General Statistics (the most rigorous at my school) at University of California, Davis, and there is a fairly heavy amount of reliance on rigor and derivation. A doctorate in math will be helpful, insomuch as you will have a very strong background in real analysis and linear algebra--useful skills in statistics. My statistics program has about 50% of the coursework going to support the fundamentals (linear algebra, real analysis, calculus, probability, estimation), and the other 50% goes towards specialized topics that rely on the fundamentals (nonparametrics, computation, ANOVA/Regression, time series, Bayesian analysis).
Once you get the fundamentals, jumping to the specifics is usually not too difficult. Most of the individuals in my classes struggle with the proofs and real analysis, and easily grasp the statistical concepts, so coming from a math background will most definitely help. That being said, the following two texts have pretty good coverage of many topics covered in statistics. Both were recommended in the link you provided, by the way, so I wouldn't say your question and the one you linked are necessarily uncorrelated.
Mathematical Methods of Statistics, by Harald Cramer
All of Statistics: A Concise Course in Statistical Inference, by Larry Wasserman
Comment: +1 All of Statistics: it would be a great place to start.
Comment: the UC-Davis program looks good and I think you'll get a great education there. I wouldn't consider it "less rigorous" than other places. I thought the comment on their "integrated B.S./M.S. degree" **[page](http://anson.ucdavis.edu/undergrad/bs-ms)** was interesting and relevant to the thread: "There is a high demand for statisticians, but the knowledge and skill achieved by those with a BS degree in Statistics are often not sufficient for the needs in the [government or industrial] workplace."
Answer: The Royal Statistical Society in the UK offers the Graduate Diploma in Statistics, which is at the level of a good Bachelor's degree. A syllabus, reading list, & past papers are available from their website. I've known mathematicians use it to get up to speed in Statistics. Taking the exams (officially, or in the comfort of your own study) could be a useful way to measure when you're there.
Comment: The Graduate Diploma exams are effectively final year undergraduate exams; for "staging" purposes there are lower level certificates that can be taken first. The RSS exams are available, if I recall correctly, worldwide with the exception of Hong Kong (which has its own statistical society and exams). An alternative is the undergraduate Diploma in Statistics offered by distance learning by the Open University in the UK, but again available worldwide. This is of slightly lower level than the RSS Grad Dip so may be seen as preparation for it. As a taught course it's substantially more expensive.
Answer: I would go to the curriculum websites of the top stats schools, write down the books they use in their undergrad courses, see which ones are highly rated on Amazon, and order them at your public/university library.
Some schools to consider:

MIT - technically, cross-taught with Harvard.
Caltech
Carnegie Mellon
Stanford

Supplement the texts with the various lecture video sites such as MIT OCW and videolectures.net.
Caltech doesn't have an undergrad degree in statistics, but you won't go wrong by following the curriculum of their undergrad stats courses.
Comment: OCW is certainly a very fine resource and a great initiative. This is no doubting that. As for your assertion that mixing and matching from the "best schools" is a superior solution, I find that highly suspect, particularly for undergraduate studies. While a highly motivated student is bound to get a very good undergraduate education at any of those schools, an undergrad education as good or better can be found at many, many "worse" schools. Schools such as those that you list do tend to "win out" for graduate education, I would say.
Comment: Actually, this was the first thing I tried. I tried this before posting the question. Finding a list of courses wasn't hard, but finding information about which books actually got used for those courses and what sections of those books were covered was much more difficult.
Comment: this seems like a bit of an odd list. To my knowledge, Carnegie Mellon is the *only* school on that list that (formally) offers an undergraduate degree in statistics. Neither Caltech nor MIT even have graduate programs in statistics.
Comment: @cardinal. why must you doubt me? :) I put in links to the undergrad stats courses at those fine institutions. Also, mixing and matching courses from the best schools will beat out following a degree path from a worse school.
Answer: I come from a computer science background focusing on machine learning.
However, I really started to understand (and more important to apply) statistics after taking a Pattern Recognition course using Bishop's Book
https://www.microsoft.com/en-us/research/people/cmbishop/#!prml-book
here are some course slides from MIT:
http://www.ai.mit.edu/courses/6.867-f03/lectures.html
This will just give you the background (+ some matlab code) to use statistics for real work problems and is definitely more on the applied side.
Yet, it highly depends on what you want to do with your knowledge.
To get a measure for how good you are you might want to browse the open course ware of some university for advanced statistics courses, to check if you know the topics covered.
Just my 5 cent.
Answer: E.T. Jaynes "Probability Theory: The Logic of Science: Principles and Elementary Applications Vol 1", Cambridge University Press, 2003 is pretty much a must-read for the Bayesian side of statistics, at about the right level.  I'm looking forward to recommendations for the frequentist side of things (I have loads of monographs, but very few good general texts).
Comment: I disagree, Jaynes' book is a terrible recommendation in this circumstance: 1) the notation is sloppy and non-standard, which makes it difficult to cross reference with other sources, 2) he's long winded and gets bogged down in silly and irrelevant arguments (the OP asked for the "shortest route") 3) there's also the errors (such as the marginalization paradox)
Comment: I would suggest It's a must read for *anybody* who wants to be a good statistician, Frequentist, Bayesian or anything else.
Comment: @Dikran Marsupial, do you own the Schervish text on statistical inference? I've been on the fence regarding whether to purchase it or not, so was curious, since you appear to align yourself pretty strongly with the Bayesian approach.
Comment: I wouldn't say I was strongly aligned to the Bayesian approach.  It is the approach I understand the best, which is not the same thing.  Essentially I am an engineer at heart, and I want both tools in my toolbox, maintained in good order!  A proper understanding of the benefits and disadvantages of each approach is what we should aim for.  I haven't got Shervishes book, but I did read a paper of his on Bayes factors that seemed quite flawed to me (I'll see if I can find it and post a question for someone to explain it to me!).
Comment: @Dikran, Your (potential) question sounds interesting. I look forward to a post on it.
Comment: I expect I am just missing something, but it is the paper by Lavine and Schervish "Bayes factors: what they are and what they are not".  The example 2 seems a bit odd as they use a Bayes factor in a situation where they have a well specified (and highly informative) prior on the hypotheses.  As a result it seems unsurprising that it behaves a little oddly given that the information (mu) is used in computing the Bayes factor, but then treated as unknown in the hypothesis test itself.  I like reading papers on what things actually mean though and being wrong is a good way of learning!
Comment: Late in the day, but I added a plus to the comment against Jaynes. It's a book of some considerable interest to those who have their own slant on statistics already. As an introduction it could only be singularly bizarre, even for the mathematically well educated. Cambridge U.P. were completely right to publish it, flaws and all, but the flaws reduce its pedagogic value considerably.
Answer: I have seen Statistical Inference, by Silvey, used by mathematicians who needed some workaday grasp of statistics. It's a small book, and should by rights be cheap. Looking at http://www.amazon.com/Statistical-Inference-Monographs-Statistics-Probability/dp/0412138204/ref=sr_1_1?ie=UTF8&s=books&qid=1298750064&sr=1-1, it seems to be cheap second hand.
It's old and concentrates on classical statistics. While it's not highly abstract, it is intended for a reasonably mathematical audience - many of the exercises are from the Cambridge (UK) Diploma in Mathematical Statistics, which is basically an MSc.
Answer: Regarding the measurement of your knowledge: You could attend some data mining / data analysis competitions, such as 1, 2, 3, 4, and see how you score compared to others.
There are a lot of pointers to textbooks on mathematical statistics in the answers. I would like to add as relevant topics:

the empirical social research component, which comprise sampling theory, socio-demographic and regional standards
data management, which includes knowlegde on databases (writing SQL queries, common database schemes)
communication, how to present results in a way the audience stays awake (visualization methods)

Disclaimer: I am not a statistician, this are just my 2cents
Answer: I think Stanford provides the best resources when it comes to flexibility. They even have a machine learning course online that would provide you with a respectable base of knowledge when it comes to designing algorithms in R. Search it up on Google and it will redirect you to their Lagunita page where they have some interesting courses, most of them being free. I have Tibshirani's books, Introduction to Statistical Learning' and 'Elements of Statistical Learning' in PDF formats and both are extremely good resources.
Since you're a mathematician, I would still advise you to not fast track as that wouldn't provide you with a solid base that you might find very helpful in the future if at all you start doing some serious machine learning. Treat statistics as a branch of mathematics for getting insights from data, and that requires some work. Other than that, there are tons of online resources, Johns Hopkins provides similar stuff as Stanford. Although experience always pays, a respectable credential will always reinforce that base. You can also think of the specific fields that you would like to enter; by that I mean whether you want to go into text analytics or applying your math and stats skills in finance. I come in the latter category so I have a degree in econometrics where we studied finance + statistics. A combination can always be very good.