VPC-TRANSIT: Difference between detached VGW and Direct IPSec connection (csr1000v)

Question: Picture worth thousands words So i draw 2 different network diagrams involving the VPC Transit infrastructure on AWS using csr1000v.
Direct connection between csr1000v and on premise
Connection using detached VGW instead
Can anyone tell me if there is a big difference between using one or another schema. The major one I see for myself is that using the detached VGW, i don't have to configure the Cisco routers to connect to on premise network and I get even a configuration file for different on premise router: checkpoint, cisco, etc...
So of course, i'm a big fan of the detached gateway diagram but is there any drawback over the direct ipsec connection csr <-> on-premise ?
Thx a lot
btw: My connection would never exceed 100 Mbps, so relatively small throughput
btw2: The router on premise are not from cisco
Comment: Source: http://docs.aws.amazon.com/solutions/latest/cisco-based-transit-vpc/appendix-d.html
Answer: One interesting point you have pointed out is that one can use non-cisco routers on-prem and configure CSR.
Apart from that I would say that if you are using a Multi-site on-prem configuration and with a 2 ISP for (active / failover) config; then detached VGW configuration would help.
You can use DMVPN cloud to setup the multi-site config in CSR v1000.
Comment: thanks for your answer, i asked aws customer service and they told me the same, no much difference (not good over bw > 10gbps) the detached vgw is easier to setup obviously. +1 for DMVPN.


how to filter out only the subitem from array

Question: {
  "s" : {
    "this_key_might_not_be_known_ahead_of_time" : [
      {
        "service": "c",
        "stack": "c_c",
        "deploymentId": "abc"
      },
      {
        "service": "c",
        "stack": "del_in_pr",
        "deploymentId": "deg"
      }
    ]
  }
}

How do I get the "deployment_id" for only the "stack" which are in "c_c" status.
Note: as the name this_key_might_not_be_known_ahead_of_time suggests, I might not know the key name
The closest I got was jq -c '.s[] | . - map(select(.stack | contains("c_c"))) | .[] .deploymentId' but it does the exact opposite of what I want and if I remove the '-' from the query above it does not work
Comment: `jQuery` is a JavaScript library. What does that have to do with `jq`?
Comment: How about `jq -r '.s[][] | select(.stack | contains("c_c")).deploymentId'`?
Answer: You can use .[] to stream/iterate all values of an object, regardless of their key. You can then use the map(select(...)) pattern to select only the interesting items from the inner array:
.s[] | map(select(.stack=="c_c").deploymentId)

Output:
[
  "abc"
]


Why do I get an enumeration error using xlwings to return the result of an Excel add-in function?

Question: I have an Excel addin that has a formula I would like to use.  I have xlwings update the spreadsheet with the formula and then get the value of the formula.
I have had numerous times where I have received an enumeration error when I am using xlwings.  Is there a way to get past this error with error handling?
I have the following code:
<code>for attempt in range(10):
        try:
            wb.sheets('Sheet1').range('A1').value = '=KSINV(0.05,'+str(sum1)+','+str(sum2)+')'
        except:
            w=0#nothing
        else:
            break

for attempt2 in range(10):
        try:
            dcrit=wb.sheets('Sheet1').range('A1').value
        except:
            w2=0#nothing
        else:
            break
</code>
This does not seem to be helping.  Do I need to increase the attempts?
Comment: Perhaps try the solution [here](https://stackoverflow.com/a/33151033/18571565), to load the add-in to ensure that it is active before your calculations.
Answer: I was using the addin when suddenly the formula for the function I was using included the path to the xlam before the function.
I copied the xlam file as a different name and activated the addin with that name.  I haven't had an error since.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


3 simple questions about file permissions

Question: 1- Wonder, is this a good setup of permissions in the /var directory?
drwxr-xr-x  2 root root  4096 2010-05-30 03:34 backups
drwxr-xr-x  7 root root  4096 2010-05-29 17:55 cache
drwxr-xr-x 29 root root  4096 2010-05-29 17:55 lib
drwxrwsr-x  2 root staff 4096 2009-07-14 04:36 local
drwxrwxrwt  3 root root    60 2010-06-02 03:34 lock
drwxr-xr-x  9 root root  4096 2010-06-02 03:34 log
drwxrwsr-x  2 root man   4096 2009-09-20 20:36 mail
drwxr-xr-x  2 root root  4096 2009-09-20 20:36 opt
drwxrwxrwt 12 root root   420 2010-06-02 12:12 run
drwxr-xr-x  4 root root  4096 2009-09-20 20:37 spool
drwxrwxrwt  2 root root  4096 2009-07-14 04:36 tmp
drwxr-xr-x 14 user root  4096 2010-05-30 22:21 www

2- Could you give me a brief explanation of the columns above? First one is which permissions they have. Second is a nr. Third and fourth says "root root" for example. fifth is another nr (4096 for example). and the others are obvious.
3- Could you give me a brief explanation of the folders above? Especially the "lock" and "tmp" folders. Lock contains an apache2 folder which seems empty.
Thanks
Answer: The best explanation of *nix permissions I found is at:
http://content.hccfl.edu/pollock/AUnix1/FilePermissions.htm
It is long, but worth the read.  Pay special attention to what directory permissions mean as it might not be what you would guess.  For example, write permission on a directory allows you to do delete files in that directory, regardless of the permissions on the file itself. Also look as the sticky bit is to find out about t for the temp directory.

As far as ls -l, output it is:
<FileType-Permisions> <Hardlink Count> <Owner> <Group> <Size> <Modification Time> <Name>

FileType Permissions:

Character 1: File Type
Character 2: Owner Read
Character 3: Owner Write
Character 4: Owner Execute
Character 5,6,7: Group Read, Write, Execute
Character 8,9,10: All Read, Write, Execute

They are evaluated left to right in a short-circuit method.  This means that even if all has read access, if you are the owner and owner doesn't have read, you won't be able to read it.  If you want to be more accurate, have look at what posix says:
"%c%s%s%s%c", <entry type>, <owner permissions>,
    <group permissions>, <other permissions>,
    <optional alternate access method flag>

Links:

If a file, how many links to that file exist, when all links are deleted, the file is deleted. If the file is a directory, it is how many directory links exist in that directory.

Owner, Group:

The name of the owner of the file and group owner of the file.  See /etc/passwd/ and /etc/group

Size:

The size in blocks.  The block size can be different on different systems, but it is normally 4 KBytes..  Oh, it is just in bytes actually.  But you will notice everything has to be at least one block, so new files with something in them will at least take up 4096 even though this column might only show one byte.

Modification Time:

When the file was last modified.  See ctime and atime as well.

Name:

The Name of the file.
Answer:
Permissions comming with your distribution are normally OK and should probably not change if you're not sure of what you're doing. It seems ok even if backups directory might be with rwx------ permission (700)
Answer is in man ls, 2nd is number of links to the file (in case of directory all inside file count as 1, non recursive), 5th nr is the file size, then there is the modification date.
You will find your answer here http://www.pathname.com/fhs/ and more exactly here and here. In few words lock is used by apache to know if apache is already running or not, tmp is for temporary files
Comment: By the 5th number beeing file-size, what do you mean exactly? The size of the folder only, or the size of it and its content? How come all file-sizes are the same then? Also, why are there two "root" in the desciption above, is one for the owner and the other the group or something. Ex: root root 4096 etc etc. Why two root?
Comment: For a folder size is not very useful, if you want size of folder content use 'du'. root root is user then group. Again, see man ls it's well explained
Answer: For an answer on the contents of the various folders check man hier.
The /var/lock directory is intended to contain lock files. It is mainly used for devices and applications.  File locks are usually placed in the directory being locked on next to the file being locked.
/var/tmp is another /tmp directory.  As /tmp is often on a tmpfs and is therefore cleared by a reboot, it useful if you need to create a temp file which will survive a reboot.  This directory is rarely used.


Showing diagonalisability using primary decomposition

Question: I am trying to solve the following exercise (not to be handed in):

Let $T : V \rightarrow V$ be a $\mathbb{F}$-linear map with $\dim V < \infty$. Suppose
  that $p(T)=0$ for some monic polynomial $p(x) \in \mathbb{F}[x]$ which factorizes into distinct linear factors. Show
  that $T$ is diagonalisable.

Since $p(T) = 0$ and $p(x)$ factorizes into some, say $n$ distinct linear factors, I can decompose $V$ into a direct sum of kernels in the following way
$$V = \ker a_1 \oplus \ker a_2 \oplus \ldots \oplus \ker a_n$$
where $p(x) = a_1 \cdot a_2 \cdots a_n$ is the factorization of $p(x)$. But how do I use this to show that $T$ is diagonalisable?
Since this is meant for exam study and is not really homework, I would like the solution to be more than a hint.
Comment: How do you know it has at least $n$ factors?
Comment: I probably don't know that, and I have removed it from the question.
Answer: The point here is the word "linear". If the factors are linear, it means that are of the form $t - \lambda$. Then, the invariant subspaces in your decomposition are just eigenvector subspaces:
$$
\mathrm{Ker} (T - \lambda \mathrm{Id}) \ .
$$
So, you pick a basis of each one -which will be formed by eigenvectors-, and put all these bases together, obtaining a basis of $V$ made out of eigenvectors. Thus, $T$ is diagonalisable.
Comment: I would argue that the point is "distinct" and not "linear" since there exist a field extension where the polynomial is always splits into linear factor but is diagonalizable iff they are distinct
Comment: They are both important; if $(x-1)^{2}$ is the minimal polynomial, then $x$ can be non-diagonalizable. "distinct linear" makes sense to me.
Comment: Yes, you're right: linear + distinct makes the thing.
Comment: @user32240: $(x-1)^2=(x-1)(x-1)$ so it does splits into linear factors. both are of course important but since the splitting is of no issue in an extension field the real key point is the factors being distinct
Comment: @Belgi: Yes, but in our case the minimal polynomial would be degree 2, so not "linear" anymore. But I agree.
Comment: @user32240 - if $m_T=(x-1)(x-2)$ is of degree $2$ - but splits into different linear factors so the conclusion "so..." is not really correct (and I think that you didn't mean that...)
Comment: @Belgi: Yeah, we do need to add the condition the eigenvalues are the same. Thanks for the reminder.
Answer: As stated in my lecture note the theorem say that if we have a decomposition
of the minimal polynomial of $T$ into irreducible elements in $\mathbb{F}[\lambda]$
$$m_{T}(x)=(\varphi_{1}(\lambda))^{c_{1}}...(\varphi_{r}(\lambda))^{c_{r}}$$
Then there are $r$ invariant subspaces $$W_{1},...W_{r}$$ s.t $$V=W_{1}\oplus...\oplus W_{r}$$
and $T|_{W_{i}}=\varphi_{i}(\lambda))^{c_{i}}$
In your case you have some polynomial $p$ s.t $p(T)=0$ and $p$
splits into distinct linear factors, since $m_{T}\mid p$ we have it that
$m_{T}$ splits into distinct linear factors.
Let $\alpha_{1},...,\alpha_{r}\in\mathbb{F}$ s.t $m_{T}(x)=(x-\alpha_{1})...(x-\alpha_{r})$
(and recall $i\neq j\implies\alpha_{i}\neq\alpha_{j})$.
Since each $W_{i}$ is invariant and by the stated above we have that
this means $T(W_{i})\subset W_{i}$ and $\forall v\in W_{i}:\, T|_{W_{i}}(v)=\alpha_{i}v$
Denote $k_{i}:=dim(W_{i})$, then by $V=W_{1}\oplus...\oplus W_{r}$
we have it that $k_{1}+...+k_{r}=n$. Take a basis $B_{i}$ for $W_{i}$
and from $\forall v\in W_{i}:\, T|_{W_{i}}(v)=\alpha_{i}v$ deduce
that $[T|_{W_{i}}]_{B_{i}}$ is of the form $$diag(\alpha_{i},...,\alpha_{i})$$
Since this is a direct sum we have a basis $B=\cup B_{i}$ and $[T]_{B}$is
diagonal as a direct sum of diagonal matrices.
Note: You can also use Jordan normal form to deduce that the minimal polynomial splits into distinct linear factor iff the matrix is diagonalizable but I chose to do it by the theorem as asked (the existence of the Jordan normal form in this case should not worry you since the eigenvalues are on the field in this is sufficient, in any case there is a field containing $\mathbb{F}$ in which the Jordan normal form exist).
Answer: Simply realize that the minimal polynomial consists of different linear factors. If this is the case T is diagonalisable (To see this use the primary decomposition, every characteristic subspace is of dimension 1).
Comment: What do you mean by "every characteristic subspace is of dimension 1" ? if I understand you correctly then this is wrong. take for exmaple $T=Id$ then $m_T=x-1$ but the $W=W_1$ in the  primary decomposition is of dimension $n$ = the dimension of the eigenspace corresponding to the eigenvalue $1$ . In general the dimension is not $1$ but rather the geometric multiplicity of the eigenvalue


How can i use input data from a file in C programming?

Question: I have a program that uses word search. I have a data file which contains the puzzle and the words. What can i implement into my program so that it reads the file and stores the letters present in it as an array?
Example of the data file (it is called testdata):
h e l l o a c d
f g b w o r l d
h a c c v b n a
e q b x n t q q
y e h n c a q r
hello
world
hey

I want to store all the letters in a 2-d array.
Also, I need to store all the words in a 1-dimensional array.
The maximum number of rows of columns or rows that AxA square of letters that is possible in a data file is 25. So, I believe that I should declare an array of that size for the letter and then write them into that array.
I just can't figure out how to read them into that array. There is a space after each letter in the array and no spaces in the words so I think that might be helpful when putting the letters in one array and words in another.
Comment: Regarding _all the letters in a 2x2 array_, do you mean 2-dimensional array.  I see more than a 2x2 array there.
Comment: Use `fopen`, `fscanf`, etc. This is really beginner stuff.
Comment: @ryyker sorry, my bad. yes i meant a 2-d array.
Comment: Hi - sorry, had to leave for awhile. It looks as if you are doing something very similar to a cross-word puzzle, of sorts, where there are really two parts to your data file.  1) the puzzle, 2) the words to find within the puzzle.  I think I can describe a way to do this, I will do it in an answer below.  If my description is accurate, (or not) let me know, then I can help with implementation for the parts you need help with, i.e. reading the letters into a 2D char array and the strings into another array.  (it will actually be an array of strings, but for now that's just semantics)
Answer: I would parse the file line by line and char by char looking for what i need. In the example (which is untested), i hold three counters to help filling the arrays correctly.
char letters[25][25];
char words[10][25]

int letters_x_pos = 0; // Row counter
int letters_y_pos = 0; // Column counter
int words_pos = 0;

for (int i = 0; i < 25; i++) {
    for (int j = 0; j < 25; j++) {
        letters[i][j] = '\0';
    }
}

const char *line;
while (line = some_read_function()) {
    if (!(strlen(line) > 1)) {
        continue;
    }

    if (line[1] == ' ') {
        // Line contains letters
        const char *letter = line;
        while (*letter != '\0') {
            if (*letter == ' ' || *letter == '\n' || *letter == '\r') {
                continue;
            }
            else {
                letters[letters_x_pos][letters_y_pos++] = *letter;
            }
            if (letters_y_pos == 25) {
                // Maximum reached
                break;
            }
            letter++;
        }
        // Increment row counter and reset column counter
        letters_x_pos++;
        letters_y_pos = 0;
        if (letters_x_pos == 25) {
            // Maximum reached
            break;
        }
    }
    else {
        // Line contains word
        strncpy(words[words_pos++], line, 25);
        if (words_pos == 25) {
            // Maximum reached
            break;
        }
    }
}

Answer: Given your question, and your input, there are a few questions, but in the interest of time, for now, I have made some assumptions about the dimensions of the array, i.e. that it is not necessarily square (as implied by columns or rows that AxA square).  The actual data sample disagrees, so I wrote a routine that counts everything as it goes.  The letter array is simply an array of arrays, but since it is stored in sequential memory, it just looks like one long array.  The strings are each in there own location as well.  In any case, this code should illustrate enough to get you on the right track...
#include <ansi_c.h>
#include <stdio.h>

void GetFileContents(char *file, int *nWords, int *lw, int *r, int *c);
void allocMemoryStr(int numStrings, int max);
void allocMemoryLtr(int numStrings, int max);
void freeMemoryStr(int numStrings);
void freeMemoryLtr(int numletters);
#define FILENAME "c:\\dev\\play\\_puzzle.txt"

char **letters;
char **strings;

int main()
{
    int  longest, cnt,  wCount, rows, cols, i;
    char line[260];
    FILE *fp;
    char *buf=0;

    GetFileContents(FILENAME, &wCount, &longest, &rows, &cols);

    allocMemoryStr(wCount, longest); //for strings
    allocMemoryLtr(rows*cols, 1); //for strings

    //read file into string arrays
    fp = fopen(FILENAME, "r");
    cnt=0;
    for(i=0;i<rows;i++)
    {
        fgets(line, 260, fp);
        buf = strtok(line, " \n");
        while(buf)
        {
            strcpy(letters[cnt], buf);
            buf = strtok(NULL, " \n");
            cnt++;                      //use as accurate count of words.
        }
    }
    cnt=0;
    while(fgets(line, 260, fp)) //get remainder of lines into strings
    {
        //[EDIT]removed fgets()
        buf = strtok(line, " \n");
        while(buf)
        {
            strcpy(strings[cnt], buf);
            buf = strtok(NULL, " \n");
            cnt++;                      //use as accurate count of words.
        }
    }
    fclose(fp);
    freeMemoryStr(wCount);
    freeMemoryLtr(rows*cols);
    return 0;
}

void GetFileContents(char *file, int *nWords, int *lw, int *r, int *c)
{
    char line[260];
    FILE *fp;
    char *buf=0;
    char temp[80];
    int wc=0, rc=0, cc=0, ck=0;

    fp = fopen(FILENAME, "r");
    while(fgets(line, 260, fp))
    {
        rc++;
        buf = strtok(line, " \n");
        while(buf)
        {
            strcpy(temp, buf); // word handler
            if(strlen(temp) > 1)
            {
                wc++;
                rc--; //
            }
            else if(strlen(temp) == 1) //leter handler
            {
                cc++;
                (cc>ck)?(ck=cc):(cc=cc);
            }
            buf = strtok(NULL, " \n");
        }
        cc = 0;
    }
    fclose(fp);
    *nWords = wc;
    *r = rc;
    *c = ck;
}

void allocMemoryStr(int numStrings, int max)
{
    int i;
    strings = calloc(sizeof(char*)*(numStrings+1), sizeof(char*));
    for(i=0;i<numStrings; i++)
    {
      strings[i] = calloc(sizeof(char)*max + 1, sizeof(char));
    }
}
void allocMemoryLtr(int numletters, int max)
{
    int i;
    letters = calloc(sizeof(char*)*(numletters+1), sizeof(char*));
    for(i=0;i<numletters; i++)
    {
      letters[i] = calloc(sizeof(char)*max + 1, sizeof(char));
    }
}

void freeMemoryStr(int numStrings)
{
    int i;
    for(i=0;i<numStrings; i++)
        if(strings[i]) free(strings[i]);
    free(strings);
}
void freeMemoryLtr(int numletters)
{
    int i;
    for(i=0;i<numletters; i++)
        if(letters[i]) free(letters[i]);
    free(letters);
}

Comment: Thank you for taking the time to answer. I looked at your answer and I am trying to learn the concepts you have used. I ended up using fgetc for creating the arrays.


Android: Anyway to know if 'Unknown Sources' is checked?

Question: Is there any way to find out if the user has checked the 'Unknown Sources' checkbox in the 'Application settings' menu?
Comment: Possible duplicate of [Is there a way to check if "Install from unknown source" is enabled on Android?](http://stackoverflow.com/q/6664984/456814).
Answer: You can use the INSTALL_NON_MARKET_APPS setting. Something like that :
boolean canInstallFromOtherSources = Settings.Secure.getInt(Settings.Secure.INSTALL_NON_MARKET_APPS) == 1;


Show that if $n$ divides $a^n-b^n$ then $n$ divides $\frac{a^n-b^n}{a-b}$

Question:
Let $a,b,n \in \mathbb Z^+$. Show that if $n$ divides $a^n-b^n$ then $n$ divides $\frac{a^n-b^n}{a-b}$.

This is from Apostol's Introduction to Analytic Number Theory, Chapter $5$, exercise $13$.
It is trivial when $\gcd(n,a-b) = 1.$
It is also easy when $n$ divides $a-b$ since $\frac{a^n-b^n}{a-b}=\sum_{k=0}^{n-1} a^kb^{n-1-k} \equiv na^{n-1}\pmod n \equiv 0\pmod n$.
But after that, I am stuck. Any hint or help is appreciated, thank you.
Answer: Let $d=\gcd(n,a-b)$. The explicit expression
$$\frac{a^n-b^n}{a-b}=a^{n-1}+a^{n-2}b+a^{n-3}b^2+\ldots+a^2b^{n-3}+ab^{n-2}+b^{n-1},$$
shows that, because $a\equiv b\pmod{d}$, we also have
$$a^{n-1}+a^{n-2}b+a^{n-3}b^2+\ldots+a^2b^{n-3}+ab^{n-2}+b^{n-1}\equiv na^{n-1}\equiv0\pmod{d}.$$
That is to say $d$ divides $\tfrac{a^n-b^n}{a-b}$.
Comment: I couldn't see why this proves the result.
Comment: @OskarIngEnte If there is some part of the answer you do not understand, feel free to ask for clarification. Please do not vandalize the answer.
Comment: You have not proved that $n | \frac{a^n - b^n}{a - b}$.
Comment: @Laz Can you point out which part of the argument is lacking or unclear?
Comment: @Servaes The question was to prove that $n$ divides $\frac{a^n-b^n}{a-b}$, not that $d$ divides this number. You only proved that $d$ divides it.
Answer: Proof:
When $n\in\mathbb{P}$:
1). $n\mid a$
$\Rightarrow n\mid b\Rightarrow n\mid\frac{a^n-b^n}{a-b}$
2). $n\nmid a\land n\nmid a-b$
$\Rightarrow n\mid\frac{a^n-b^n}{a-b}$
3). $n\nmid a\land n\mid a-b$
$d≔a-bn⇒a=b+nd$
$\because n\mid \binom{n}{i},\ 0<i<n$
$\therefore n\mid \binom{n}{1}b^{n-1}+\binom{n}{2}b^{n-2}\left(nd\right)+\cdots+\left(nd\right)^{n-1}=\frac{a^n-b^n}{a-b}$
When $n\notin\mathbb{P}$:
$\exists p_1,\cdots,p_s\in\mathbb{P}:n=p_1\cdots p_s$
$n_1≔p_2⋯p_s$
$\frac{a^n-b^n}{a-b}=\frac{a^{n_1p_1}-b^{n_1p_1}}{a^{n_1}-b^{n_1}}\cdot\frac{a^{n_1}-b^{n_1}}{a-b}$
Based on the previously proven case where n is a prime number, we have
$p_1\mid\frac{a^{n_1p_1}-b^{n_1p_1}}{a^{n_1}-b^{n_1}}\Rightarrow\exists q_1\in\mathbb{N}^\ast:\ \frac{a^n-b^n}{a-b}=p_1q_1\frac{a^{n_1}-b^{n_1}}{a-b}$
Repeat the above method,
$\exists q_2,\ \cdots,q_s\in\mathbb{N}^\ast:\ \frac{a^n-b^n}{a-b}=p_1q_1\cdots p_sq_s=nq_1\cdots q_s$
$\therefore n\mid\frac{a^n-b^n}{a-b}$
Q. E. D.


Why is the first inversion of a C Major Chord very rarely used on guitar even though it is easier to play?

Question: The open C Major Chord is one of the first basic chords taught to beginning guitar students.  It is also one of the most common chords I see in the music I listen to.
The instruction books teaching the fingering for the open C Major Chord stress the importance of avoiding the open low E string when playing the C Major Chord and the chord diagrams for the C Major Chord always show the 6th string being muted.

But the E is the third of the C Major Triad (part of the chord) and playing the low E string on the open C chord would be much easier than trying to avoid it with your pick or mute it with a finger tip. I realize that if you included the Low open E string in the chord it would be a first inversion of the C chord or could be referred to as a C with E as the bass note (C/E).  But it is still a C Major Chord (just a different voicing) as explained Here and Here by two of the most venerable contributors to this site.
So  why does it seem that guitar instruction books make it sound so wrong to play all 6 strings when playing the open C Major Chord?
And why is it rarely used in composing music for guitar?
I often see the second inversion of the C Major Chord in music composed for guitar (C/G) but don't remember ever seeing any song I have ever looked up the chords for that called for a C with E in the bass (first inversion).
Many of the songs I have learned to play use the first inversion of the D Major Chord D/F# and I play that chord in many of the songs I cover and it sounds good.
So why is the first inversion of the D Major Chord far more common than the rarely used first inversion of the C Major Chord which is certainly easier to play than the D/F sharp because it's just a matter of strumming all 6 strings?
Is it just a coincidence that the songs I choose to look up the chords for just don't have the C/E chord as part of the arrangement whereas many of the songs I look up do specify the D/F# chord?
Or is there something about a C/E that diminishes its use in music written for guitar?
Comment: Perhaps the more resonant open E string makes the E seem like a pedal tone, making C/E sound more like a contrapuntal neighbour chord of E minor rather than a strong chord of its own.
Comment: It seems like this is a question about why guitar method book writers present the topic of chord inversions in a particular way.  In actual music I think different inversions are just as common on guitar as they are anywhere else.  Perhaps an abundance of guitarists who were always taught from rigid and prescriptive method books statistically gives lie to my statement, but in general it is the case from a theory perspective.
Comment: I don't know much about music theory, but this seems obvious. Typically guitarists want the lowest note of the chord to be the root. It just "sounds better" in almost every case.
Answer: Root position and 2nd inversion triads sound stronger than triads in 1st inversion. Maybe it would be better to say that triads in 1st inversion sound more harmonically ambiguous than the other two options.
Consider that for a major triad in 2nd inversion, the fifth is in the bass, and this is the note most closely related to the tonic of the chord. But, for a major triad in 1st inversion, the third is in the bass. This note is not only less suggestive of the tonic, but is itself the fifth of another note. For a CMaj triad in 1st inversion, the E is in the bass. This is a fifth away from A, and the notes E G C are suggestive of an Amin7 chord (containing the guide tones of Amin7).
Alternatively, taking E as the root, E G C looks like an Em♭6 chord which is missing only the fifth. Thus, the CMaj triad in 1st inversion has a harmonic ambiguity that the root position and 2nd inversion voicings lack.
The context in which the chord arises matters. In the context of a progression like C/E - A7 - DMaj7 which is the best way to think of the C/E? Is it a ii chord (Em♭6), a v7 chord (Am7), a ♭VII (CMaj), or something else? Does the melody provide any clues? In the context of another progression: C/E - A7 - Dmin7 - G7, I would say that the C/E sounds very much like a I chord (CMaj). I suspect that this slipperiness is the reason that 1st inversion triads don't show up in beginner method books more frequently; this is a time when simple grips that establish the chord sounds need to be learned.
As to why the 1st inversion voicings are used less frequently by experienced players and composers, I am not sure that this is true (well, it probably is). For me, 1st inversion voicings are most useful as passing chords, or when the third is part of a moving bass line on the guitar, part of the voice leading, or when someone else is playing the bass notes.
Register Issues
The above provides an explanation for why triads in 1st inversion are less common in general, but does not shed light on why a CMaj open chord with an E in the bass is rarely seen. I think the implicit suggestion here is that the particular voicing asked about by Rockin Cowboy may be even less common than other voicings of C/E.
As has been pointed out by another answer and by Todd Wilcox in the comments, some intervals can begin to sound muddy in the lower registers. This phenomenon is discussed here and here, and may be one explanation for why this particular voicing of C/E is avoided.
I note that at this page and this page it is stated that the low E should be avoided with the open C voicing, but no reasons other than that it doesn't sound good are given. On the other hand, this page does mention this voicing, and states that Stone Temple Pilots used it in their tune Plush. All three of these resources seem to be pitched at a beginner level.
One of my favorite resources for information about chords is Ted Greene's Chord Chemistry. He does include this voicing, as an E/G♯ moveable form situated at the 4th fret. This is not a beginner book, and it is assumed that players will use their ears to judge when voicings work and when they do not.
I see some 2nd inversion voicings in the beginner resources mentioned above, but I see almost no 1st inversion voicings. The second page does show a D/F♯ with the F♯ on the bottom string, and now that I think about it I used that voicing a lot at one time.
Summing Up
I think that in general triads in 1st inversion are tricky to use because of their harmonic ambiguity. Add to this that they can also sound muddy or otherwise jangly in the lower register and you have good reason to avoid introducing them to beginners. The moveable C barre form with the third in the bass may be avoided in such cases because it is harder to play than the other barre chords, and it requires some judgment to determine if it sounds good or not.
Comment: This has the important music theoretical reasons and explanation and leaves out the fact that the open low E string on guitar can be tricky. Open A chords in second inversion with the open low E usually don't work either. The open low E can easily sound muddy and doesn't have to be strummed very hard to make it noticeably change pitch as it rings out. Also we should remember that guitars sound an octave lower than written so it's quite a low note and on piano, for example, inversions that low can sound muddy also.
Comment: You have good points here, but "sound stronger" is a fuzzy statement, and "suggestive of an Am⁷ chord" a bit far-fetched since A itself never actually turns up. I'd rather say it's suggestive of Em♭₆.
Comment: @leftaroundabout -- I picked up the language of "some triad inversions sound stronger than others" from a teacher years ago; I agree that it is a little vague (which doesn't bother me too much here). Good point about **Em♭6**, but I do think that **C/E** is _suggestive_ of **Am7** even in the absence of an A. I have expanded my answer a bit.
Comment: @ToddWilcox -- I think that register may be a contributing factor, but cowboy **A** chords with low open E notes in the bass are very common, at least with the E working in an alternating `A - E - A` bassline fashion. Also, **C/G** with the fifth in the bass seems to be an extremely common chord, and that is not much higher than the **A/E**.
Comment: I can't get those alternating bass patterns to work without muting the bass note I'm not playing. Meaning, when I play the G under a C chord the A string is muted and there's no C. Likewise with the E-A combination. It might be more of a factor with my particular guitars, but even with piano music I don't see a lot of harmonic sixths or fourths in the lower registers.
Answer: In the same way that  a first inversion C chord played on the lowest notes of a piano will sound less satisfying  to most ears than one an octave or two higher,  a first inversion open C chord with that unrestrained, booming E string is unlikely to satisfy the way a more balanced D/F# will. It is true that one can tame the beast somewhat with finger picking and arpeggiating, but it will always be a problem child compared to the more tractable D/F#.
Comment: Yes... chords generally don't subjectively "work" as well down in the bass range, and at the lower end of the guitar, you're already in the range where some things can sound a bit ropey.
Comment: Also, it is the lowest note, so consistency would be difficult. e.g. if a song were **C**, **Bm**, **Am**, then a **C/E** would raise questions about **Bm/D**, **Am/C** (I know other chords aren't required to have inversions, but still the question would be asked). IMHO, this is one reason why **D/F#** works: it offers options both above and below.
Comment: Thanks for addressing why the D/F# is more common.  What do you believe makes the D/F# more balanced?  Is it because it is fretted and thus not "unrestrained" or is it because the 3rd in the D/F# is paired with the 5th on the open A string whereas the 3rd in the open C/E  (the open E String) is paired with the root on the (C played on 5th string)?  Or a different reason?
Comment: @MichaelEaster Great point about the open E being the lowest possible note on guitar.  It has been my experience that the D/F# is often used as a passing chord or as part of a bass walk down resolving to an Em chord.  You can't "walk down" any farther than the low E which may explain why we don't see the first inversion of open C used as often as the 1st inversion of open D.
Answer: Many times a 1st inversion is used on the V chord to substitute for the vii° and to give you a bass note that leads back to the tonic. C is the dominant of F major and that is a very difficult key to play on guitar and not many songs are written for guitar in F (or many songs at all really) when it can be dropped half a step to E. That could be one possible reason it's not common.
Guitar books are generally for beginners and teach how to play each chord starting on the root. I am confident the books also show a D chord muting the E and A sting even though you can play a D/A just as easily as a C/E.
But on a side note I actually use it a lot when going from a C to F and it sounds fine and I like it.
Answer: It helps to think of the harmonics when it comes to the chords.
Playing a C-Chord, with G-C as the bottom two notes
G-C are the 3rd and 4th harmonics: C-C-G-C - so the "real" base of the chord is actually an octave and a half beneath that G.
Playing a C-chord, with E-C as the bottom two notes
E-C is a bit higher up the harmonic series: C-C-G-C-E-G-Bb-C.  So the real base is more than two octaves lower than the E.
If you're playing E-C in a high register?  Then it's not a problem - two octaves down isn't a problem, and would be a pleasant note.  But if you're playing the lowest string on the guitar, and then mentally adjusting it 2+ octaves downward?
If you want to do an experiment, go to a piano and play the following intervals further and further down the piano's register:

Octave (1st and 2nd harmonic)
Fifth (2nd and 3rd harmonic)
Fourth (3rd and 4th harmonic)
Major Third (4th and 5th harmonic)
Minor Third (5th and 6th harmonic)
Diminished Fifth (5th and 7th harmonic)

... you'll find the further away from the fundamental the interval gets, the higher the register has to be before it's pleasant to the ears.
Answer: Playing a five string chord on guitar has a different sound and texture than playing a six string chord, even if the chord is technically the same, and the further up the neck you play the shorter the strings get and the more different they sound. Chords that utilize open strings are so popular because they sound good as well as being easier to play than barre chords. Since the open C major is one of two 5 string major chord shapes playable on the guitar it makes sense that teachers would emphasize this to get the student used to playing 5 strings. Being able to mute the low E string is something everyone should learn and not avoid simply because they think it's too hard.
A student should always first learn to play in root position since it sounds the clearest with regards to harmonic intent. The A major chord shape could also potentially use the low E as a second inversion tone, but again, there's no point in practicing this when you could be practicing playing the E or G major chords instead.

Many of the songs I have learned to play use the first inversion of the D Major Chord D/F# and I play that chord in many of the songs I cover and it sounds good.

This is because D is the second highest note of the guitars lowest octave and thus it loses a lot of low end and can sound uncomfortably high compared to other open chords around it.
Answer: Different chord inversions work best at different places in a progression.  First-inversion chords are best in cases when the bass note is a half-step below that of the preceding and/or succeeding chord.  In the case of the C/E chord, that would most likely occur when the neighboring chords are a six-string F chord or Bb/F.  Guitar pieces for beginners don't generally contain either of those chords, and thus wouldn't have any place where a C/E would be particularly appropriate.
Note, btw, that it's easy to mute the sixth string while playing a C chord, using the same finger that is fretting the fifth string (typically the ring finger).  Indeed, for many people it would be easier to deliberately mute the sixth string (by placing the finger slightly toward that string), than it would be to let it ring freely (placing the fifth-string finger precisely between the fourth and sixth strings without touching either).
Comment: @RockinCowboy: The primary point of interest was that it may be easier than trying to avoid strumming the sixth string, but since the OP was able to play C/E and was having trouble with strumming, I was suggesting that--at least for the OP--muting the sixth string would be easier than *both*.
Answer: Two main reasons really

It's poor voice leading. Doubling the third is rarely a good idea to begin with, let alone in the bass; it is almost certain to result in parallel or hidden octaves or an abused leading tone.
It sounds pretty bad without a capo. If you're higher up the neck it is bearable. Lower frequencies are harder for your ear to differentiate. In general you will find composers will space notes more sparsely the farther down you go on the staff.
Comment: Assuming all six strings are plucked, the fingering described in the question is a E_C_E_G_C_E voicing. So it's a tripled third...
Answer: I know you can get pretty complex with the music theory behind the answer, but the simpler answer is, because it sounds "best" to have the root note of the chord as the lowest tone.  That helps your ear place the chord in context with the song, especially when playing the guitar as a solo instrument.
Note that if you are playing with a bass player, all bets are off and you can get really creative with your chord voicings, it's the bass player's job to anchor the chord with the root note on the beat or as needed. Jimi Hendrix often used this voicing with the major 3rd as the root, although higher up the fret board.
Regarding D/F#, that is often used as a transition chord, but you won't often hear a song written in the key of D use a D/F# voicing - on the root chord, you want to hear that root note in the bass.
Answer: There's really two issues here:

Why do books and tutorials tell you to start on the C on the second string?

Because the standard answer is that you play a chord starting on the root. If the bass note is not serving another purpose (such as making a cadence stronger or providing a walking bass line), then use the root.

Why do guitarists rarely play C over E?

They don't, many guitarists will play that low E string whenever a C appears for a fuller sound, to add a little more bass, or simply because they don't feel like muting that string.
There's nothing inherently wrong with it and it's itiomatic of a lot of guitar music.
Comment: Well, I don't know what you mean by _huge amount of bass range_. I do like it when the guitar has a sound that makes it _able_ to get a bit fat in the bass range, be it for a harder rock riff or for percussive-infused rhythmic stuff on an acoustic guitar. And yes, it can also be nice for e.g. a long-ringing final chord if the guitar adds a really low major third only slightly above the bass note. But not for _always_ just leaving any low string ringing whenever it happens to be a chord tone.
Comment: I wonder who you mean by those "many" guitarists who play the low E _whenever_ a C appears. I don't know any, and I'm definitely glad I don't play _with_ any. This kind of thing can be really annoying when you're playing a bass instrument.
Comment: @leftaroundabout You probably wouldn't notice. Particularly if you're playing a bass note an octave or two lower.
Comment: Sure I would notice, like I do in the case of D/F♯ or F/A. — You can't play that C a whole octave lower – well, you can on a 5-string bass, but that's really a pretty extreme deep end. The only option you have to not get a muddying clash in the bass range is to _also_ play E, but then it is really clearly an inverted chord and wants to resolve to F.
Comment: @leftaroundabout A bass guitar's open strings are an octave lower than a guitar's four low open strings. Yes, that means that the guitar's low E is a third above the lowest C on a standard bass. It really doesn't clash, tho. Unless, perhaps, the guitar's got a huge amount of bass range on it's EQ and the bass, erm, doesn't.
Comment: This is just false and incorrect.
Answer: C/E is not the first inversion of C since then the second note would be G, not C.  So the bass note is quite more detached than if we were actually talking about a proper first inversion.
Comment: Only the bass note matters in the inversion. See this for more info about inversions: https://www.musictheory.net/lessons/42


Migrating from commercial music notation software to free alternative

Question: A friend of mine dislikes composing music on the commercial software he owns (Si..us). The main reason is that he is into modern, avant-garde music and the notation on his current system is just not there yet or what's offered does not satisfy him. He is a professional music composer.
I have no idea about music composition. I really love LaTeX and would consider no other alternative. I am quite able with it and I am able at programming in general.
He asked me for helping him and I see I have two choices, either I experiment writing some plugin for his current commercial software I mentioned, which is uncharted waters for me plus only available on an OS I don't have, or ...
... using a TeX-based or TeX-like (free) music composition system, if available and doing all programming, templating etc. in this myself. Advantages: platform independent and free.
I can manage any installation challenge and possibly I can persuade him to free himself from the GUI for the sake of programmability and typesetting/engraving quality.
So, my question is:
Has anyone here had any experience with both the free and the commercial music-composition softwares and can give some advice whether it's wise to dump the commercial for the free without compromising typesetting quality which is my primary metric.
And also whether there will be lots and lots of symbol libraries for him to choose from?
Edit: I posted similar question on LilyPond user forum
Comment: @KJO If Sibelius doesn't meet the guy's needs, Musescore certainly won't.
Comment: Lilypond is "TeX like". But the question is off-topic here: the TeX family has MusixTeX, but that's very far from your friend's need, as far as I can see.
Comment: Most people I know who produce music scores using "avant garde"  notation don't use any music notation apps. They do it with graphic design software like Adobe InDesign. The the whole point of music notation apps is that they "understand" conventional music notation, and if you don't want to *use* conventional notation, that means everything the app was written to do just gets in the way.
Comment: the old means of moving between lilypond and musescore went about 5 years ago the current transfer between the two is using MusicXML which needed xml2ly conversion, not sure how to relate to TeX but both are mentioned in the LaTeX guide for musicians http://ctan.math.washington.edu/tex-archive/info/latex4musicians/latex4musicians.pdf
Comment: there is also https://ctan.org/pkg/lyluatex
Comment: Totally uneducated on music have only run any for a few minutes to get a beginners feel, however in any specialised field an expert user will quickly push a basic system to the point they spend more time augmenting a system rather than using a pre-built repertoire the only contender here is lilypond but it would struggle to get a bet for even a "place" let alone odds on favourite apart from the two leaders Fin... Sib... the best to look at may be MuseScore
Comment: @KJO Somehow managed to unvote your useful comment. Thanks. I will post to LilyPond mailing list and edit my post when I get a URL.
Comment: For people who stumbled into this thread and know a bit about music, but never saw any "avant garde" notation, here are a few  samples: https://www.nashvillepublicradio.org/post/avant-garde-music-scores-go-graphic-when-traditional-notes-arent-enough http://www.openculture.com/2018/01/notations-john-cage-publishes-a-book-of-graphic-musical-scores.html
Answer: The main reason to use Open Source software is its longevity, in my opinion.
After having to learn new programs when CorelDraw and Aperture were no longer maintained for Mac, I always try to find some Open Source alternative.
Maybe it is not so good, but it will probably last much longer since anybody who has the skills and interest can maintain it.
In the case of music, I have been using Lilypond since I started learning to play guitar.
Since I already know LaTeX, it has not been to difficult nor frustrating, which is what happens usually with people who has never used such format.
So, if you know LaTeX I would recommend you to use Lilypond also.
About the potential longevity of Lilypond in comparison with comercial software, this question is interesting.
In Lylipond you can of course use all kind of commands to get the output you want, but If the notation that is required is not traditional, as @alephzero says in comments, then I still would go for Open Source, chosing Inkscape instead of InDesign.
Answer: You certainly won't get any better options with freeware music notation programs as has been pointed out in the comments to the question.
You can actually make a lot of "avant garde" notation in Sibelius, but Finale is especially good on that matter.
If you want to see examples of avant garde types of scores made with Sibelius and Finale google these terms:
graphic notation Sibelius
graphic notation Finale
If you want to expand the possibilities, which can include other types of software, google:
Contemporary Music Notation software
Here is a good result from googling that line:
https://www.quora.com/What-software-should-every-contemporary-composer-own
Find other relevant terms to google and explore the possibilities.
Comment: The developers of Sibelius were all canned and they created a new package called Dorico. I've never used it but that might be one for the OP to check out as well. Music notation is so complicated that it is hard to imagine a freeware application at the level of, say, FINALE.
Comment: As an answer to the question, Lilypond is probably not the best solution, but those who think that it doesn't meet the standards of commercial offerings like Finale might want to check this link: http://www.musicbyandrew.ca/finale-lilypond-1.html which compares the two.  Lilypond is a great piece of software.
Comment: thank you for the links and the terms (unknown to me) to google, especially that Quora post is great. I have installed Abjad (python+LilyPond) and is impressive. I am slowly getting into this...


Erro tentando acessar um elemento do array

Question: Como faço para que a execução do meu loop gere um código do cadastro automaticamente?

Erro na linha 36 - 'livro[i].cod = i;' [Error] subscripted value is neither array nor pointer nor vector

Objetivo desde código: cadastrar 5 livros com informações dos mesmo e gerar um código automaticamente para cada livro gerado.
Código atual:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*Definindo tamanho*/
#define TAM 5

int main(void) {

    /*--Criando a struct--*/
    struct ficha_do_livro {
        int cod;
        char nome_da_obra[50];
        char nome_do_autor[50];
        char nome_da_editora[50];
    }livro;

    /*--Cadastro do Livro--*/
    int i;

    for (i = 0; i < TAM; i++) {

        printf("\n---------- Cadastro dos Livros -----------\n\n\n");

        livro[i].cod = i;
        printf("Insira o nome da Obra: ");
        fflush(stdin);
        fgets(livro.nome_da_obra, 40, stdin);

        printf("Insira o nome do autor: ");
        fflush(stdin);
        fgets(livro.nome_do_autor, 40, stdin);

        printf("Insira o nome da Editora: ");
        fflush(stdin);
        fgets(livro.nome_da_editora, 40, stdin);

    }
}

Answer: Tam alguns erros no código. Este que aparece é que está tentando acessar um elemento de um array em algo que não é um array. Você declarou uma estrutura, e uma variável com o tipo dela, mas ali só cabe um único elemento. Se você quer colocar vários elementos precisa colocar na sintaxe que quer isto, indicando quanto elementos esta variável terá. Aí este erro desaparecerá. Mas dará outros erros já que os outros membros da struct depois do código também precisam ser acessados pelo índice do array, então falou colocar o i lá também.
Preste bastante atenção porque retirei um monte de coisas que não eram necessárias neste código, e arrumei algumas coisas que o deixa mais eficiente. Sim, até o comentário não é necessário porque ele diz uma obviedade, comentários não foram feitos para isso. Não use coisas que não sabe para que serve.
#include <stdio.h>

#define TAM 5

int main(void) {
    struct {
        int cod;
        char nome_da_obra[41];
        char nome_do_autor[41];
        char nome_da_editora[41];
    } livros[TAM];
    for (int i = 0; i < TAM; i++) {
        printf("\n---------- Cadastro dos Livros -----------\n");
        livro[i].cod = i;
        printf("Insira o nome da Obra: ");
        fgets(livro[i].nome_da_obra, 40, stdin);
        printf("Insira o nome do autor: ");
        fgets(livro[i].nome_do_autor, 40, stdin);
        printf("Insira o nome da Editora: ");
        fgets(livro[i].nome_da_editora, 40, stdin);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Você escreveu uma perguntar muito vaga, "E o que isso quer dizer?" não especifica o contexto do seu comentário referente ao meu, especificadamente quis dizer que não é um projeto objetivo, com foco em escopo e eficiência do mesmo sendo sua estruturação atual focada em um desenvolvimento de teste e aprendizado, a estruturação do comentário no mesmo é para em futuro próximo ter fácil entendimento do escopo do próprio algoritmo.
Comment: Esse é apenas o inicio de um projeto não o mesmo completo, ainda vou colocar mais coisas por isso ainda esta em alpha. vlw pela atenção
Comment: E o que isso quer dizer?
Comment: Seu comentário é muito vago, eu dei uma resposta, você comentou algo que não parece ter significado algum. O contexto do meu comentário é o seu comentário sem contexto. Eu não falei nada sobre o contexto do seu projeto ou o que você quer fazer com ele. Eu falei qual o erro que você cometeu e que tem um monte de coisas desnecessárias nele, e agora que você dá alguma contexto posso dizer que coisas desnecessárias são ruins para o aprendizado.
Comment: Quando usa o que não precisa, aprende errado, e eu odeio quando as pessoas aprendem errado, por isso sempre ajudo em tudo o que posso, não apenas consertando o erro apresentado, porque isso não ensina. Eu costumo dizer "funcionar é diferente de estar certo". Se pesquisar aqui encontrará isso e ilustração de como é o software da maioria das pessoas quando elas não se preocupam em fazer certo. Eu percebi que você teve o problema resolvido, mas não entendeu a solução, por isso coloquei na resposta descrição do erro e o que eu corrigi, mas parece que você não valorizou isso.
Comment: Nem todos sabem como estrutura todos tipos de códigos, se estou aqui é porque estou para tirar minhas duvidas e aprender com as mesmas, agradeço que goste de ajudar, mas compreenda que nem toda forma de aprendizado se dar na explicação dos erros mas também quando nos os cometemos e os corrigimos para assim aprender com os mesmos. O aprendizado não se da apenas de uma boa estruturação semântica do código o tornado 'eficiente', mas também de errar e reconhecer que nunca saberá o suficiente sobre tal assunto.
Comment: É um direito seu acreditar nessa falácia.
Answer: Você precisa usar um array de estruturas.
Obs. não testado.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*Definindo tamanho*/
#define TAM 5

int main(void)
{

  /*--Criando a struct--*/
  struct ficha_do_livro
  {
    int cod;
    char nome_da_obra[50];
    char nome_do_autor[50];
    char nome_da_editora[50];
  } livro[TAM]; // <-----------------------

  /*--Cadastro do Livro--*/
  int i;

  for (i = 0; i < TAM; i++)
  {
    printf("\n---------- Cadastro dos Livros -----------\n\n\n");

    livro[i].cod = i;
    printf("Insira o nome da Obra: ");
    fflush(stdin);
    fgets(livro[i].nome_da_obra, 40, stdin); // <---------------

    printf("Insira o nome do autor: ");
    fflush(stdin);
    fgets(livro[i].nome_do_autor, 40, stdin); // <-----------------------

    printf("Insira o nome da Editora: ");
    fflush(stdin);
    fgets(livro[i].nome_da_editora, 40, stdin); // <---------------------

  }
}

Comment: Vlw a todos, vc me mostrou onde estava os erros de sintaxe, mas não entendi o por que de ser stdin no fgets e não stdio...


Piano mordent with two notes

Question: I'm trying to play Brahms' Hungarian dance №11 and there is a technical question.
How do I play a mordent from the 4th measure? Whether both notes should be played with mordent or just the upper one? Could someone make me a hint of fingering please?
I've attached the scores below.
Comment: Just double checking, are we talking about measure 3?  Because there's an 8th note pick up before the first measure which could look like a full measure... ;-)
Answer: In these sorts of cases, I trust the community of professional and semi-professional musicians more than my own music history knowledge. (Read: I searched youtube for several videos and saw what they did).
For the uninitiated who stumble upon this question: a mordent is the proper name for the squiggle above the staff in measure 4. It is similar to a trill, but starts on the note in question, and only alternates with the note above it once.
In every instance I watched (a different piano solo arrangement,  an orchestral arrangement, A 4-hand piano arrangement,  and a piano/violin arrangement), the initial mordent is played between the D and the C. Most of the videos play the mordent before the beat, with one playing on the beat.  Most of those videos included both the top and bottom notes in the mordent. Further support for including both notes comes from observing the grace notes in measures 6, 7, 10, and 11; it seems like the intent is to have both notes involved in the ornaments.
If you can play a sixth with a 3-1 stretch, I would recommend playing the mordent with 5-2 and 4-1, playing the third diad with 3-1. Keeping the mordent light will help you play it quickly. If this is too difficult, it's acceptable (especially below a professional level) to involve only the top note in the mordent.
It's worth noting that many piano teachers advocate first learning the piece without any ornaments, and then adding them in at the end. This is largely to avoid any timing issues, as these ornaments typically should not alter the timing of the other notes. If you notice that any ornaments are bogging you down or screwing up the timing of the other notes, it might be worthwhile to leave them out for the time being.
Comment: There's a trill in there???
Comment: I believe this is a trillo, and not a mordent. A mordent would look the same, only with a vertical line over the centre.
Comment: @11684, the nomenclature is confusing and has changed from the Baroque era to the Romantic. To distinguish the manner in which the ornament is played, it is often (but not always) called a Trillo in Baroque music and an upper mordent in Romantic music. The symbol you describe is simply called a mordent in Baroque music and a lower mordent in Romantic music. The hows and whys of this change are well out of the scope of this answer, but the wikipedia article I linked has a brief overview.
Comment: @Luke, I wanted to avoid using musical jargon (I mean, everybody knows what a trill is. Who has ever heard of a mordent outside of a music school?). In any case, I agree that we should probably use correct musical terms. Edited and added a definition. If anyone can improve my 5-second definition, please do!
Comment: Thank you for your detailed answer!
This is really a little difficult for me to involve both notes in the ornament so I will alternate only the top one as you advised to. Thanks!
Comment: Wow, I didn't know that, thanks for learning me something. If you edit your answer I can lift my downvote and give you an upvote. (I might forget to check back, so you could notify me by comment when you have edited the answer.) @Babu
Answer: John Thompson's Modern Course For The Piano The Fourth Grade Book p. 54 Ornaments:  The Mordent has a vertical line through the middle of it that is written directly over and above the written note and includes the written note and the note immediately below and then plays the written note again and this must be played within the time frame given according to the time signature and the time given by the written note. The example given in the text is in a 4/4 time signature and a quarter note Treble E is the written note to begin the Mordent that is to be played thus: E as a 32nd note followed with a D as a 32nd note followed by an E as a 16th note tied to an E as an 8th note all played within the time frame of a quarter note.
An Inverted Mordent is played as the above with the same timing, but it differs in two ways: It's symbol does not have a vertical line and the written note is played followed by the first note above it then like above, the written note is played again.
Therefore in the Key of C Major on your music score it is directing you to play in 2/4 time (where each quarter note is equivalent to 1 beat, an 8th note 1/2 beat, a 16th note 1/4 beat, a 32nd note is equivalent to 1/8th of a beat, a 64th note=1/16th of a beat). Your score, however, requests an Inverted Mordent to be played within the time frame of a 16th note, so play very lightly and quickly a Trebble C as a 64th note, followed by a D as a 64th note, followed by a C as a 32nd note.
Happy ornamenting!

Piano mordent with two notes


Number of zeros of $f(x)= \frac{1}{2} E\left[ \tanh \left( \frac{x+Z}{2} \right) \right]-\tanh(x)+\frac{x}{2}$ where $Z$ is standard normal

Question: Consider the following function:
\begin{align}
f(x)= \frac{1}{2} E\left[ \tanh \left( \frac{x+Z}{2} \right) \right]-\tanh(x)+\frac{x}{2},
\end{align}
where $Z$ is standard normal.
Question: How to show that this function has only three zeros? Note, that we are not interested in the locations just the number of zeros.
By using that $\tanh(x)$ is an odd function, it is not difficult to show that $f(0)=0$.
However, I am not sure how to show the existence of the other two zeros.
I know that two more zeros exist from the numerical simulation (see the attached figure).
Edit:  The current answer shows that there are at least 3 zeros.  Now we need to show that there can be no more than 3 zeros.
Edit 2 Idea for a proof.  Consider only positive $x$.  I think  if we can show the following:

$f(x)>0$ for  all $x>x_1$,
$f(x)$ is convex for $x \in (0,x_2)$, and
$x_2>x_1$.

Then this will imply that the function is convex in the regime while it changes a sign. Therefore, it can only have at most one sign change.
Comment: @SangchulLee Thanks. It's coming from estimation theory.  $\tanh(x)$ is related to an estimator of $X \in \pm 1$ in Gaussian noise.  The number of zeros is just an intermediate bound that I need.
Comment: Intriguing question. Is there any motivation of context as to why you consider this function?
Answer: Not a complete proof, but rather a sketch. First, observe that as $x\to +\infty$, than $\tanh (x) \to 1$, so $f(x)$ asymptotically asymptotically equivalent to $\frac{1}{2} E [1] - 1 + \frac{x}{2} = \frac{x-1}{2}$, so for some large enough positive value of $x$ one has $f(x) > 0$. After that, let's look at the graph of the function and notice that $f'(0)$ must be negative, which is not hard to prove: As
$$
\frac{1}{2} E\left[ \tanh \left( \frac{x+Z}{2} \right) \right] =
\frac{1}{2} \int_\mathbb{R} \tanh \left( \frac{x+z}{2} \right) \frac{1}{\sqrt{2\pi}} e^{-z^2/2}dz
$$
So
$$
f'(x) = \frac{1}{2} \int_\mathbb{R}
\frac{\partial}{\partial x}\left[
\tanh \left( \frac{x+z}{2} \right)\right] \frac{1}{\sqrt{2\pi}} e^{-z^2/2}dz +
\frac{d}{dx} \left[-\tanh (x) + \frac{x}{2}\right] = \\ =
\frac{1}{4} \int_\mathbb{R} \frac{1}{\cosh^2 \left( \frac{x+z}{2} \right)} \frac{1}{\sqrt{2\pi}} e^{-z^2/2}dz - \frac{1}{\cosh^2 (x)} + \frac{1}{2} \\
f'(0) = \frac{1}{4} \int_\mathbb{R} \frac{1}{\cosh^2 \left( \frac{z}{2} \right)} \frac{1}{\sqrt{2\pi}} e^{-z^2/2}dz - 1 + \frac{1}{2} \leq
\frac{1}{4} \int_\mathbb{R} \frac{1}{\sqrt{2\pi}} e^{-z^2/2}dz - \frac{1}{2} =
\frac{1}{4} - \frac{1}{2} = -\frac{1}{4}
$$
where the inequality is obtained from $\frac{1}{\cosh^2 \left( \frac{z}{2} \right)} \leq 1 \;\forall z \in \mathbb{R}$. So, it means that $f(x)$ is decreasing in some neighborhood of zero.
So, there exists some $x^+ > 0$ s.t. $f(x^*) > 0$ and some $x^- > 0$ s.t. $f(x^-) < f(0) = 0$. So, by intermediate value theorem (it's also an exercise to check the continuity of $f(x)$) there exists some $x^* \in [x^-, x^+]$ s.t. $f(x^*) = 0$. As $f(x)$ is an odd function, it means that $-x^*$ is also a root.
EDIT: as $\frac{1}{2} - \frac{1}{\cosh^2(x)} \leq f'(x) \leq \frac{3}{4} - \frac{1}{\cosh^2(x)}$ and $f'(0) = 0$, I suppose that with similar methods one can prove that $f$ also has a stationary point somewhere on positive axis, which can help in proving that there are no other roots.
Comment: @Boby yes, you're right. Currently I can't come up with proper proof on showing that there are only two more zeros, but I've included some thoughts in the edit.
Comment: This shows that there exist two more zeros. Thanks.  Correct me if I am wrong, but this doesn't show that there are only three zeros, right?
Comment: Thanks and thanks for the ideas.
Comment: @Boby by the way, the given plot is somewhat confusing, since $f(x)$ looks like cubic.
Comment: I had to zoom in far enough to show that there were three zeros.  I guess,  I can try to fix it
Comment: I think I have an idea for proof. Can you check it out?
Comment: @Boby yes, sure. Idea looks fine to me.
Answer: Note: The proof below works, but I made it unnecessarily difficult. In equality $(1)$, I forgot about the normalising factor $1/\sqrt{2\pi}$ which made the upper bound unnecessarily large (it still works since $1/\sqrt{2\pi}<1$).

Claim. The real function $g(x)=x-2\tanh x+\Bbb E\tanh((x+Z)/2)$ has exactly three real zeros.
Proof: Since $\Bbb E\tanh((-x+Z)/2)=\Bbb E\tanh((-x-Z)/2)=-\Bbb E\tanh((x+Z)/2)$, we know that $g$ is odd. As $g(0)=0$, it suffices to show that $g$ has exactly one positive root.
Computing the first derivative, we have $g'(x)>1-2\operatorname{sech}^2x$ since $$\frac d{dx}\Bbb E\tanh\frac{x+Z}2=\frac12\Bbb E\operatorname{sech}^2\frac{x+Z}2>0.$$ Therefore, $g$ is strictly increasing for all $x>\operatorname{arccosh}\sqrt2$, so it suffices to show that $g'$ is strictly increasing on $(0,\operatorname{arccosh}\sqrt2)$; that is, a convexity argument on $g$.
Computing the second derivative, we obtain $g''(x)=4\tanh x\cdot\operatorname{sech}^2x-h(x)$ where \begin{align}h(x)&=-\frac d{dx}\Bbb E\operatorname{sech}^2\frac{x+Z}2\\&=\Bbb E\left[\tanh\frac{x+Z}2\cdot\operatorname{sech}^2\frac{x+Z}2\right]\\&=\int_{-\infty}^\infty\frac{e^{-(z-x)^2/2}\sinh(z/2)}{\cosh^3(z/2)}\,dz\tag1\\&=2e^{-x^2/2}\int_{-\infty}^\infty\frac{e^{-2z^2+2xz}\sinh z}{\cosh^3z}\,dz\\&=2e^{-x^2/2}\int_1^\infty\frac{e^{-2\operatorname{arccosh}^2t+2x\operatorname{arccosh}t}-e^{-2\operatorname{arccosh}^2t-2x\operatorname{arccosh}t}}{t^3}\,dt\tag2\\&=4e^{-x^2/2}\int_0^\infty\frac{e^{-2\operatorname{arccosh}^2(t+1)}\sinh(2x\operatorname{arccosh}(t+1))}{(t+1)^3}\,dt\\&<4e^{-x^2/2}\int_0^\infty\frac{\sinh(2x\operatorname{arccosh}(t+1))}{(t+1)^7}\,dt\tag3\end{align} where

in $(1)$, we use the law of the unconscious statistician;

in $(2)$, we split the integral into $(-\infty,0)\cup(0,\infty)$ and substitute $t=\cosh z$, and

in $(3)$, we use the inequality $\cosh x\le e^{x^2/2}$ for all real $x$ which rearranges to $\exp(-2\operatorname{arccosh}^2t)<1/t^4$ for all $t>1$.

Credits to @KStarGamer for help in the evaluation of this integral! We first exploit the Laplace transform integral identity $$\int_0^\infty\frac{\sinh(2x\operatorname{arccosh}(t+1))}{(t+1)^7}\,dt=\int_0^\infty\mathcal L\left[\sinh(2x\operatorname{arccosh}(t+1))\right](s)\cdot\mathcal L^{-1}[(t+1)^{-7}](s)\,ds.$$ Since $\mathcal L^{-1}[(t+1)^{-7}](s)=s^6e^{-s}/6!$ and \begin{align}\int_0^\infty e^{-st}\sinh(2x\operatorname{arccosh}(t+1))\,dt&=e^s\int_1^\infty e^{-st}\sinh(2x\operatorname{arccosh}t)\,dt\\&=e^s\int_0^\infty\left(e^{-s\cosh u}\sinh u\right)\sinh2xu\,du\\&=e^s\int_0^\infty\frac{2x}se^{-s\cosh u}\cosh2xu\,du\\&=\frac{2x}se^sK_{2x}(s)\end{align} through integration by parts, we are left with $$\int_0^\infty\frac{\sinh(2x\operatorname{arccosh}(t+1))}{(t+1)^7}\,dt=\frac x{360}\int_0^\infty s^5K_{2x}(s)\,ds=\frac{2x}{45}\Gamma(3-x)\Gamma(3+x)$$ using Ramanujan's master theorem and that $K_{2x}$ is a linear combination of modified Bessel functions of the first kind. The reflection formula finally yields $$h(x)<\frac{8\pi x^2(x^4-5x^2+4)}{45e^{x^2/2}\sin\pi x},$$ so a sufficient condition for $g''(x)>0$ is $$\frac{\sinh x}{\cosh^3x}>\frac{2\pi x^2(x^4-5x^2+4)}{45e^{x^2/2}\sin\pi x}\iff p(x)=\frac{2\pi x(x^4-5x^2+4)e^{x^2}}{45\sin\pi x}<1$$ using $\cosh x\le e^{x^2/2}$ and $\sinh x\ge x$. It suffices to show that $(\log p(x))'>0$ since $p$ is positive and $p(\operatorname{arccosh}\sqrt2)<1$. This is equivalent to $$\frac{2x^6-5x^4-7x^2+4}{x(x^4-5x^2+4)}>\pi\cot\pi x$$ which can be written as $$2x+\frac1{x-2}+\frac1{x-1}+\frac1x+\frac1{x+1}+\frac1{x+2}>\sum_{n\in\Bbb Z}\frac1{x-n}$$ using the Mittag-Leffler expansion of $\cot$, which is true for all $0<x<3$ (more than what we need) since $$\sum_{n=-\infty}^{-3}\frac1{x-n}+\sum_{n=3}^\infty\frac1{x-n}=\sum_{n=3}^\infty\frac{2x}{x^2-n^2}<0.\tag*{$\square$}$$
Comment: Really nice solution combining a lot of ideas and theorems! (+1)
Comment: Hi again. Thanks for you your answer.  A colleague of mine and I  are writing a paper and have a generation of this problem appear.  I was wondering if you would be willing to participate or at least a look at the problem we are trying to solve?
Comment: @Boby I don't have much time for now but sure, I can look at the context behind this.
Answer: $()=\frac{1}{2}[tanh(\frac{+}{2})]−tanh()+\frac{x}{2}$
with $E[]$ the standard normal of the $tanh$. Doing some experiments with the statistically distributed $Z$ can be visualized like this:

This shows that the experimental functions with a standard normal distribution parameter $Z$ are restricted in between two limiting functions. They can not be anywhere other than between these two limiting curves. For $x/rightarrow \infty$ all function are divergent to $-\infty$ for negatives and $+\infty$ for positives.
As can be seen from the plot there is another limiting function in the set. For this function, there are three zeros. There is a range for which there are two zeros and around that is valid for the ones lying higher in the graph there is only one zero and for the lower, there is only one zero too.
The rest of the work is discussing the given function as a real values function.
The derivative has two zeros which can be calculated using numerical methods different from zero: $\{-0.5752778985889421`, 0, 0.5752778985889421`\}$. Evaluating these extremes in the given function gives $\{0.0916058, 0, -0.0916058\}$.
So these values for $Z$ are the boundaries for which only one zero remains in the range of $Z$. These functions cross only once the $x$-axis. In between the range with two and three zeros.
At $z=+/-0.46$ or very close are the limits for only one zero:

Blue is the positive value, orange the negative.

This shows the range is very narrow in which two zeros occur. This depends on the representation. It appears that almost this limiting values are that where two zeros happen.
This shows the given problem as a contour plot with the regions under interest:

So far the general discussion of the problem.
Mathematica provides a function that might help further: Expectation.
But this does at present and for my license not with $tanh$.
This works as I mentioned earlier for sampling. Generate by a stochastic process under the regime of the normal standard the $Z$ and calculate and expectation value:
$12[tanh(+2)]\approx 1/10 (1/2 tanh[1/2 (-1.2738 + x)] + 1/2 tanh[1/2 (-0.951708 + x)] +
   1/2 tanh[1/2 (-0.376436 + x)] + 1/2 tanh[1/2 (-0.194455 + x)] +
   1/2 tanh[1/2 (-0.0016944 + x)] + 1/2 tanh[1/2 (0.131413 + x)] +
   1/2 tanh[1/2 (0.325943 + x)] + 1/2 tanh[1/2 (0.684325 + x)] +
   1/2 tanh[1/2 (1.01493 + x)] + 1/2 tanh[1/2 (2.91656 + x)])$
The more $Z$ sample in $E$ the better but the more complex the root term is going to be.
With this in mind I concducted numerical experiments with my system here is the result for an intermediate many sample for $E$ around $50000$:

The orange curve is the function given without $Z$ and expectation. The broader blue graph is a set of samples for $E[0.5 tanh(\frac{x+Z}{2}]$ between 10000 to 100000 in steps of 10000. The standard normal noise is already reduced and a clear position of the curves is visible.
Around $0$ the effect is not present. For bigger $Z$ the influence becomes a deviation. The noise is to broad to name a tendence. For sure this is lifting the curve for negatives up and down for positives. The zeros move to more negatives and more positives. It is like a $x$-dependent correction that is asymptotically constant. It is like accumulating the noise where the bending changes of the curve. And only where bending changes noise is still present.
This looks pretty much like being still off convergence for larger $x$. The expectation will cancel out in the limit and the function without the expectation value will be the limit taken with a modified factor in the $tanh$. This is close to $0.39$ instead of $0.5$. It is expected that there is an explanation and a calculation method for that statistical damping.

This shows for a proof how well the standard normal is reproduced in the sampling:

So this statistics standard normal shows little effect as long as it is centered around $Z=0$ and the plain standard normal and little happens. The broad discussion seems overpaced. But the standard normal may be everything. It is normal restricted.


Changing typeface of Snackbar

Question: I build Snackbar by this code:
Snackbar sb = Snackbar.make(drawer,  "message", Snackbar.LENGTH_LONG)
       .setAction("action", new View.OnClickListener() {
       @Override
       public void onClick(View view) {

       }
});

Now I want to change the typeface of message and action button but can't find any solution, How to do that?
Answer: You can set TypeFace by getting view from Snack bar
TextView tv = (TextView) (mSnackBar.getView()).findViewById(android.support.design.R.id.snackbar_text);
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/font_file.ttf");
tv.setTypeface(font);

For AndroidX, use resource ID com.google.android.material.R.id.snackbar_text
Answer: Styling Both the Snackbar Text and Action
You can use the same method to style both the snackbar_text and snackbar_action.
Once you've created a snackbar, you can use the following to get the Views associated with the text and the action and then apply whatever adjustments to the view.
Snackbar snackbar = Snackbar.make( ... )    // Create the Snackbar however you like.

TextView snackbarActionTextView = (TextView) snackbar.getView().findViewById( android.support.design.R.id.snackbar_action );
snackbarActionTextView.setTextSize( 20 );
snackbarActionTextView.setTypeface(snackbarActionTextView.getTypeface(), Typeface.BOLD);

TextView snackbarTextView = (TextView) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text);
snackbarTextView.setTextSize( 16 );
snackbarTextView.setMaxLines( 3 );

In my example, I've set the Action to be font size 20 and Bold, and the Text to be size 16 and allow up to 3 lines.
Answer: For AndroidX
android.support.design.R.id.snackbar_text won't be available.

Use com.google.android.material.R.id.snackbar_textinstead.

If you are using kotlin, then I prefer you to use extension function:
fun Snackbar.changeFont()
{
    val tv = view.findViewById(com.google.android.material.R.id.snackbar_text) as TextView
    val font = Typeface.createFromAsset(context.assets, "your_font.ttf")
    tv.typeface = font
}

and call it like:
mSnakeBar.changeFont()

Comment: createFromAsset didn't work for me and the app crashed every time saying that it can't find my font i used getFont from ResourceCompat like this
`val font = ResourcesCompat.getFont(context, R.font.my_font)`
Answer: In addition to this answer: now package to find snackbar's textview by id is
val snackText = snackView.findViewById<TextView>(
                    com.google.android.material.R.id.snackbar_text)

Answer: Get the snack bar view and apply customization
TextView tv = (TextView) sb.getView().findViewById(android.support.design.R.id.snackbar_text);
tv.setTextColor(Color.WHITE);
tv.setTypeface(Typeface.createFromAsset(
                    getAssets(),
                    "fonts/ur_file.ttf"));

Or this
SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Add ");
int boldStart = snackbarText.length();
snackbarText.append("bold color");
snackbarText.setSpan(new ForegroundColorSpan(0xFFFF0000), boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
snackbarText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
snackbarText.append(" to Snackbar text");

Snackbar.make(view, snackbarText, Snackbar.LENGTH_LONG).show();

Or you can give a look at this and this.
Thank you.
Answer: Starting from Support Library 26, fonts can be used as resources.
val mainTextView = view.findViewById(com.google.android.material.R.id.snackbar_text) as TextView
val font = ResourcesCompat.getFont(applicationContext, R.font.your_font)
mainTextView.typeface = font

Answer: For those who are still reading this 7 years later, you can change the text appearance of the snackbar for the whole app by overriding its theme parent in your themes.xml file.

And then in your styles.xml file insert the your_snackbar_text_style style there

Answer: Get assets
AssetManager assets = context.getAssets();

Get Typeface
Typeface typeface = Typeface.createFromAsset(assets,PATH OF .TTF FILE);

Path: font/robotoregular.ttf (if .ttf file is stored in assets/font path)
Answer: if you want to change the font of Action Button and textview use this code :
Snackbar.make(this,message,Snackbar.LENGTH_LONG).also {snackbar ->
  snackbar.setAction("ok"){
     snackbar.dismiss()
  }
  val actionButton = snackbar.view.findViewById(com.google.android.material.R.id.snackbar_action) as Button
  val textview = snackbar.view.findViewById(com.google.android.material.R.id.snackbar_text) as TextView
  val font = Typeface.createFromAsset(context.assets, "fonts/your_custom_font")
  actionButton.typeface = font
  textview.typeface = font
  ViewCompat.setLayoutDirection(snackbar.view,ViewCompat.LAYOUT_DIRECTION_RTL)

}.show()
Answer: For every one that crashes when calling createFromAsset() you can use
Font font = ResourcesCompat.getFont(getApplicationContext(), R.font.your_font);

Changing typeface of Snackbar


Solving a recurrence relation with the characteristic equation

Question: I have some trouble solving this due to not seeing the steps to be able to feed it into the characteristic equation.
$$T(n) = 4T(n-2) +n + 2^nn^2\ \text{with}\ \ T(0)=0,\ T(1)=1$$
(don't have to solve for the constants)
I don't understand the steps to transform this into the $(R-x)(R-y)$ form. I know that I should transform it into the $T(n) - 4T(n-2) - n - 2^nn^2 = 0$ but somewhere here I get lost. Can someone give me a hint (not solve it, from that i won't learn anything).
I know that if i look at it I like $T(n) - 4T(n-2)$ I can get it down to $(r+2)(r-2)$ which in it's turn means $T(n) = A(-2)^n + B(2)^n$. But that doesn't help me?
Comment: Sorry for not realizing this site understands LaTeX formatting! Thanks for edit :)
Answer: Here is a solution
$$T(n) = \frac{1}{2}\,{2}^{n}+{\frac {7}{18}}\, \left( -2 \right)^{n}-{\frac {8}{9}}-\frac{n}{3}+ \left( n+1 \right)  \left( \frac{n}{2}+1 \right)  \left( \frac{n}{3}+1
\right) {2}^{n}$$
$$- \left( n+1 \right)  \left( \frac{n}{2}+1 \right){2}^{n}
\,.$$
First, you find $T_h(n)$ of the homogeneous recurrence relation
$$ T(n)-4T(n-2)=0 \,, $$
which you have already obtained $T_h(n)= A(-2)^n + B(2)^n  \,.$ Keep this solution aside for a while and move to the next step. The second step is to find a particular solution $T_p(n)$. See here for rules of choosing a form for the particular solution. You need to assume
$$T_p(n) = A n + E + 2^n n(B n^2 +C n + D)$$
and substitute back in the recurrence relation
$$ T(n) = 4T(n-2) + n + 2^n n^2 \,, $$
to find the constants. The final solution is given by
$$T(n) = T_h(n) + T_p(n) = A(-2)^n + B(2)^n + T_p(n) \,.$$
Since you have given initial conditions, then you can use them to find the constants $A$ and $B$ in the above equation, once you find them, plug them back in the solution $T(n)$.
See other techniques.
Comment: The op specifically asked for the problem not to be solved but rather a hint.
Comment: @EuYu: I just gave the final solution and see the edit.
Comment: So if i the recurrence relation of $T(n) - 4T(n-2)$ is $T(n) = A(-2)^n + B(2)^n$ it means that the ah...

I just don't get it. By specifying that i shall not solve for the constants i only have to figure out the recurrence relation right? Why are they even there to begin with...
Comment: @saxly: This the solution to the homogeneous recurrence. call it $T_h(n) = A(-2)^n + B(2)^n$ and just keep it aside for the moment. Now, find the particular solution as I mentioned in my answer $T_p(n)$. So you have to find all the constants. Once you do that, write the general soltion $T(n)=  A(-2)^n + B(2)^n + T_p(n)$ and use the initial conditions to find $A$ and $B$.


Solve $y'=(x+y)^2$

Question: $y'=(x+y)^2$
The equation above is in the form $y'=P(x)y^2+Q(X)y+C(x)$ which is known as Ricatti equation.
I set $z=x+y$  so ${dz\over dx}={dy\over dx}+1 \implies {dy\over dx}={dz\over dx}-1 \qquad(1)  $
From the initial equation I get ${dy\over dx}=z^2  \qquad   (2)$
Finally $(1)=(2) \implies {dz\over dx}-1=z^2 \implies {1\over z^2+1}dz=dx $
If I integrate both sides with respect to x I get $atan(z)=x+c$ where c constant
Then $z=tan(x+c) \implies y=tan(x+c) -x$
Is the logic above solid or am I mistaken somewhere?
Comment: Whenever when you solve a DE, if you are not sure you should check your answer....
Comment: Your solution is correct. But i wonder why wolfram alpha is displaying such rubbish http://www.wolframalpha.com/input/?i=y%27%3D%28x%2By%29%5E2
Comment: I am wondering the same!
Comment: You can transform the result to the solution you obtained. I don't know why wolfram is showing this representation. But nevermind your solution work, i also checked it by plugging in the function itself.
Answer: Hint:
Substitute your answer back in the original D.E.
LHS = $\sec^2(x + c) - 1$
RHS = $\tan^2(x+c)$
Is there an identity connecting the two ?
Comment: $sec^2(\theta)=1+tan^2(\theta)$ so my result is correct!
Comment: @DimitriC. Absolutely. Actually you did very well in solving. Just wonder why you did not do the reverse checking
Comment: I did but I was not sure if the identity hold truth!

Solve $y'=(x+y)^2$


Distribution of the sample variance given that $\sigma^2$ is unknown

Question: By Cochran's theorem, if $y_1,....,y_n\sim\mathcal{N}\left(0,\sigma^2\right)$ independently with a known variance $\sigma^2\in\mathbb{R}_{>0}$, then
\begin{equation}
(n-1)\frac{S^2}{\sigma^2}\sim\chi^2_{n-1},
\end{equation}
where
\begin{equation}
S^2=\frac{1}{n-1}\sum_{i=1}^{n}(y_i-\bar{y})^2\sim\frac{1}{n-1}\sum_{i=1}^{n}y_i^2,
\end{equation}
is the sample variance. However, when the variance $\sigma^2$ is unknown, what is the distribution of $S^2$? Would this require applying Bayes' theorem such that
\begin{equation}
p\left(S^2\right)=\int_0^{\infty} p\left(S^2\mid \sigma^2\right)p\left(\sigma^2\right)\mathop{d\sigma^2},
\end{equation}
and, if so, what would be an appropriate (probably uninformative) prior pdf for $\sigma^2$? One option is using Jeffrey's prior, where we have $p(\sigma^2)\propto\sigma^{-2}$ and so $\sigma^2\sim\text{Scale-inv-}\chi^2(\nu,S^2)$ with $\nu=n-1$, since the data is normal. The distribution for $S^2\mid\sigma^2$ would be scaled chi-squared which is given as
\begin{equation}
p(S^2\mid\sigma^2)=\frac{2^{-\nu/2}}{S^2\Gamma(\nu/2)}\left(\frac{\nu S^2}{\sigma^2}\right)^{\nu/2}\exp\left(-\frac{\nu S^2}{2\sigma^2}\right),
\end{equation}
if I haven't made an error with the CDF method. Any help would be much appreciated.
Comment: Whether you know $\sigma^2$ or not, the distribution remains the same: nature doesn't care about your state of mind.
Comment: $$p\left(S^2\right)=\int_0^{\infty} p\left(S^2\mid \sigma^2\right)c\sigma^{-2}\mathop{d\sigma^2} = cS^{-2}$$ With an improper distribution for $\sigma$ you will get that the marginal distribution of $S^2$ will be improper as well. It is the posterior distribution, which is a ratio of two improper distributions, where the constant $c$ disappears.
Comment: @SextusEmpiricus Thank you for that derivation (I would upvote if I could).
Answer:
One option is using Jeffrey's prior, where we have $p(\sigma^2)\propto\sigma^{-2}$

This won't work. With an improper distribution for $\sigma$ you will get that the marginal distribution of $S^2$ will be improper as well.
More precisely you will get
$$p\left(S^2\right)=\int_0^{\infty} p\left(S^2\mid \sigma^2\right)c\sigma^{-2}\mathop{d\sigma^2} = cS^{-2}$$
It is the posterior distribution, which includes a ratio of two improper distributions $p(\sigma^2)$ and $p(S^2)$, where the constant $c$ disappears.

I derived the above indirectly by using Bayes' formula and the expression for the inverse Gamma distribution.
$$p(\sigma^2|S^2) = \frac{p(\sigma^2) p(S^2|\sigma^2)}{p(S^2)}$$
with $p(\sigma^2)$ and $p(S^2|\sigma^2)$ known, you can argue that $p(\sigma^2|S^2) \propto {p(\sigma^2) p(S^2|\sigma^2)}$ must be an inverse Gamma distribution. Then you use the expression for the inverse gamma distribution to figure out the normalization constant and derive $p(S^2)$.


A question about the Peano's axioms

Question: I was watching a set of lectures on introductory real analysis. LINK. Brazilian portuguese only unfortunately.
The lecturer starts defining (his own words):
Peano's axioms
Let $\mathbb{N}={1,2,3,\dots}$:

There exists an injective function  $s:\mathbb{N}\rightarrow\mathbb{N}$;
There exists an element $1$ such that $1 \in \mathbb{N}$ but $1 \notin s(\mathbb{N})$, i.e. $1 \notin Im(s)$;
(induction) Let $A$ be a set such that $A \subset \mathbb{N}$. If $1 \in A$ and ($n \in A \implies s(n) \in A$) then $A = \mathbb{N}$.

I'm still learning the very (very) basics of this, so I'm not sure whether this a proper way to define this stuff neither I can tell if these are right or wrong.
The question that bugs me is:

He assumed that there is such a thing as a "function" and also assumed "advanced" concepts like "injection". Can he do that given we are in the terrain of very primitive mathematical foundation, i.e. things that all other things build upon in math? In my beginner's math mind he should have used more primitive mathematical concepts (I'm not sure which ones exactly).
Comment: Yeah, Peano usually requires only first order logic, not set theory. This is a reformulation of Peano in a kind of naive set theory. Still, even in first order logic, we have "functions" they just aren't set theory functions, and only in the models of the theory do we talk about them as set functions.
Comment: So in first order theory, there's be a constant $1$ and a function $S$ defined on our whole domain such that $S(x)=S(y)$ implies $x=y$ and $\forall x:S(x)\neq 1.$\
Comment: How  to present Peano's Axioms with notions of "first" and "next":
1. $1$ is a natural number ('$0$'is often used instead).

2. Every natural number has a unique "next" natural number. (Functionality of the successor relation)

3. Different natural numbers have have different next natural numbers. (Injectivity of the successor relation)

4. No natural number has $1$ as its next natural number, i.e. 1 is the "first" natural number.

5. Every natural number but $1$ can be reached by a process of  repeatedly going to the next natural number starting at $1$. (Equivalent to induction)
Comment: @daniel.franzini In fact, it is an introduction to real analysis.
Comment: Yes, @user0102, it is! My bad. Fixed!
Comment: Using "first", "next" and "previous": 1. $1$ is a natural number ('$0$'is often used instead). 2. Every natural number has a unique "next" natural number. (Functionality of the successor relation) 3. If a natural number has a "previous" natural number, then that previous number is unique. (Injectivity of the successor relation) 4. $1$ is the "first" natural number, i.e. it has no previous natural number. 5. Every natural number but $1$ can be reached by a process of repeatedly going to the next natural number starting at $1$. (Equivalent to induction)
Comment: For what it is worth, here is my formal proof of the above mentioned equivalence to induction using a form of natural deduction: http://www.dcproof.com/InductionIffAccessible.htm (228 lines)
Comment: @daniel.franzini: You are right that your lecturer is using less primitive concepts than are needed. Do note that this approach essentially requires a background set theory, otherwise you have **nothing** that you can apply the so-called induction axiom to. Peano came way before FOL was properly understood, so his axiomatization was unclear. This is why in modern logic PA is **not** the same, and *spaceisdarkgreen* has adequately pointed that out. However, for your purposes (undergraduate mathematics) you already **must** work within some set theory, otherwise you cannot express many things.
Comment: @daniel.franzini: So just keep track of all the primitive notions that you need to use, and only in the future if you are interested in foundations of mathematics do you need to think about how little you want to assume, for which you can read [this post](https://math.stackexchange.com/a/1808558/21820). By the way, Dan's linked website is useless; its system cannot be used for real mathematical work, and some articles are based on conceptual errors.
Answer: As others have pointed out, things like "injective function" can be rephrased in more elementary way. The induction axiom is where all the action is. In order to make sense of the induction axiom, we need to have a notion of arbitrary subsets of $\mathbb N,$ which requires some set theoretical commitments. In other words, we need second-order and not merely first-order logic to state and interpret this.
One way to "get around" this is to replace the induction axiom with a first-order schema. So we have for each first-order formula $\varphi(x,\vec y)$, a first-order induction axiom Ind$_\varphi$: $$ \forall \vec y\;((\varphi(0,\vec y)\land \forall x\;(\varphi(x,\vec y)\to \varphi(Sx,\vec y)))\to \forall x\;\varphi(x,\vec y)).$$
Now our theory is first-order and we can make sense of it without any set theory. However, it's also much weaker and does not determine the natural numbers up to isomorphism (in other words, it has nonstandard models, which is pretty much inevitable with purely first-order axiomatizations).
In my experience "Peano Axioms" refers to the five axioms in the second-order formulation. Whereas "Peano Arithmetic" (aka PA) refers to a first-order axiomatization with an infinite schema of induction axioms that also includes the arithmetical operations $+$ and $\cdot$ in the language.
Answer: Peano arithmetic is usually defined in a way to avoid this. It is not hard to change. Instead of defining successor as a function, you say "Every integer has a successor." And instead of saying it is an injective function, you say "If $n, m$ have the same successor, then $n = m$."
Answer: I like very much the way Terence Tao describes the Peano's axioms.
Complementing the answer given by @MichaelBarz and the comments of @ThomasAndrews, I advise you to consider the following formulation:

$0$ is a natural number.
Every successor of a natural number is a natural number.
$0$ is not the successor of any natural number.
Different natural numbers have different successors.
Induction axiom.

In his book "Analysis I", he discusses the motivation for each of them. It is very enlightening.
Hopefully this helps!

A question about the Peano's axioms


Problems with chisq_test in R coin package

Question: this is my first question on stackoverflow, so hopefully I will give you all the necessary information.
I'm trying to conduct a chi-squared test based on an exact distribution, using the chisq_test function in the coin package. I'd like to compare two groups concerning one variable but I'm running in a warning message. Here's a minimum reproducible example (at least I hope it is one):
library(coin)

dt <- as.data.frame(alzheimer)

xtabs(~ disease + gender, data = dt)

chisq_test(disease ~ gender, data = dt, distribution = "exact")

I'm checking the contingency table to make sure, there are enough cases per cell. When I'm conducting the test, I get this output:
> chisq_test(disease ~ gender, data = dt, distribution = "exact")

    Exact Pearson Chi-Squared Test

data:  disease by gender (Female, Male)
chi-squared = 9.7121, p-value = 0.3895

Warning messages:
1: In T - expectation(object) :
  longer object length is not a multiple of shorter object length
2: In (T - expectation(object))^2/variance(object) :
  longer object length is not a multiple of shorter object length

I calculated the p-value using an approximate distribution, to make sure, the warning really is a problem:
> chisq_test(disease ~ gender, data = dt, distribution = approximate(nresample = 1e+05))

    Approximative Pearson Chi-Squared Test

data:  disease by gender (Female, Male)
chi-squared = 9.7121, p-value = 0.00756

Since both p-values differ a lot, I guess there is something going wrong using the exact distribution, but I just can't figure out the problem.
Maybe someone can help me solve the problem or understand the reason for the warning.
Comment: Could you please give insight of your dataframe? The error states, that your input data differs. Could it be, that `gender` and `disease` is not of equal length? Got `NAs`? Or something similar? Also try your code with an example dataset. This way you can be sure, that your code is right and your issue is with the data.
Comment: Thank you for the quick reply! The dataframe is some data coming with the coin package, so I considered it an exaple dataset. I used this data to get a reproducible example.
There are no `NAs` in the data and both `gender` and `disease` are of equal length.

With this additional information: Is it still necessary to try out with some other data?
Comment: a 2x3 exact test is not supported it seems `chisq_test(table(dt$disease, dt$gender), distribution = 'exact')`, and the formula method does not correctly catch the error
Comment: If you just change the input to `chisq_test(table(dt$gender, dt$disease), distribution = 'exact')` you get the same output I posted. So the number of rows in the table has to be two. In `?chisq_test` it reads `the distribution can be ... computed exactly for univariate two-sample problems by setting distribution to ... "exact"`, so there shouldn't be a limit for the number of columns (as long it's a 2xk table or problem).
Answer: I wrote to Torsten Hothorn, one of the authors of the package. He told me that the exact distribution for the chi-squared test only works in the case of 2x2 problems. So the warning or the fact that you don't get an error message is a bug in the current version 1.3-1 of the coin package. In the R-forge version of the package this bug is already fixed.


BottomNavigation Fragment state

Question: I have a BottomNavigation implemented in my app. when i tap on navigation items it shows their respective fragments, it is working fine. I have implemented a progress bar in every fragment so whenever i select a fragment from BottomNavigation the progress bar displays, my question is when i select any option from BottomNavigation progress bar shows then fragments load but when the fragment is loaded it should gets saved when i come back to that option from BottomNavigation it loads again... is there any way to save the state of that fragment so that it only loads for the first time.
Answer: Use onSavedInstanceState(Bundle) This will get you the required behavior, so this method is called before an activity may be killed so that when it comes back some time in the future it can restore its state.
Here i use activity which in respect is any activity, even if its a fragment, this example is from the official documentation.
For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via onCreate(Bundle) or onRestoreInstanceState(Bundle).
check out this cool link, it describes everything and a little bit more: https://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en

BottomNavigation Fragment state


Event related to node - how to display?

Question: Thinking how to achieve what I need, looking into possibilities. I have a content type that is used for all kind of locals: restaurants, clubs and so on. Now, what I want is to have a list of nearest 3 events that will take place in that specific place.
So far I was thinking about creating new type of nodes for events. Let's say: Event content. Seems logical, right? Now, using Entity Reference I should be able somehow to add relation between an event and club (not sure about this one yet). Next step would be displaying this added event on the node of that club. How could I achieve that? Creating a View and putting it into the node display somehow? Block?
Really could use some ideas for that.
Answer: You should create a view and add relationship using node reference(entity reference) and after adding relationship you should add fields corresponding to node for which relationship has been added.
Check the link on how to add relationship in views

Event related to node - how to display?