Flush/Clear System.in (stdin) before reading

Question: At work, we have 5 RFID readers attached to a PC running Linux. The readers are all recognized as keyboards and send their input (what they read form the Chip) as an key-input-event sequence. To be able to tell which reader send what sequence, I'm doing a raw-read over /dev/input/XX and get their input this way.
The problem with this is, that the send keyboard-events generated by the RFID readers are still "in" stdin and when I try to read from System.in via Scanner (input should be generated by a normal keyboard this time), I first get the "pending" input from the readers (which consists of 10 Hex-decimal digits and a newline (\n)).
Now, the question is: How can I flush all these "pending" input's from stdin and then read what I really want from the keyboard?
I tried:
System.in.skip(System.in.available());

But seek is not allowed on stdin (skip throws an IOException).
for (int i = 0; i < System.in.available(); i++){
  System.in.read();
}

But available() doesn't estimate enough (still stuff in stdin afterwards).
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
  scanner.nextLine();
}
System.out.println("Clean!");

But hasNextLine() never becomes false (the print never executes).
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null);
System.out.println("Clean!");

Same as above.
Anyone with any more ideas?
Comment: [`Scanner.hasNextLine()`](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine%28%29) may block if there is no input, so I suspect your print statement never executes for that reason. Not a solution, but an observation of why at least one of your approaches has failed.
Comment: (not enough rep to comment)... This is awesome: This worked for me **System.in.read(new byte[System.in.available()])** user5466753**
Answer: Based on @Joni's advice, i put this together:
Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
    if (scanner.hasNextInt()){
        choice = scanner.nextInt();
        break;
    } else {
        scanner.next(); // Just discard this, not interested...
    }
}

This discards the data that is already "pending" in stdin and waits until valid data is entered. Valid, in this context, meaning a decimal integer.
Answer: This worked for me
System.in.read(new byte[System.in.available()])

Answer: A related one.
I read a double, then needed to read a string.
Below worked correctly:
double d = scanner.nextDouble();
scanner.nextLine(); // consumes \n after the above number(int,double,etc.)
String s = scanner.nextLine();

Answer: There is no built-in portable way to flush the data in an input stream. If you know that the pending data ends with \n why don't you read until you find it?
Answer: Devices usually send data using a well defined protocol which you can use to parse data segments.
If I'm right, discard data that isn't properly formatted for the protocol. This allows you to filter out the data you aren't interested in.
As I'm not familiar with the RFID scanner you're using I can't be of more help, but this is what I suggest.
Comment: The incoming data is probably formatted and I'm also interested in it, but not at that later time. I suspect that the data is still in stdio because I never took it from stdio, but read it from the device itself instead...
Answer: You could do this with multiple threads.

Your real application reads from a PipedInputStream that is connected to a PipedOutputStream
You need to have one thread reading from System.in continuously. As long as the real application is not interested in the data coming from System.in (indicated by a boolean flag), this thread discards everything that it reads. But when the real application sets the flag to indicate that it is interested in the data coming from System.in, then this thread sends all the data that it reads to the PipedOutputStream.
Your real application turns on the flag to indicate that it is interested in the data, and clears the flag when it is no longer interested in the data.

This way, the data from System.in is always automatically flushed/clead
Answer: The best practice (that I've found) when dealing with terminals (aka. the console) is to deal with i/o a line at a time.  So the ideal thing to do is get the entire line of user input, as a string, and then parse it as you see fit.  Anything else is not only implementation specific, but also prone to blocking.
Scanner sc = new Scanner(System.in);
String line = "";

while (true) {
    System.out.println("Enter something...");

    try {
        line = sc.nextLine();
        //Parse `line` string as you see fit here...
        break;
    } catch (Exception e) {}
}

I include the while & try/catch blocks so that the prompt will loop infinitely on invalid input.
Answer: You can try:
System.in.skipNBytes(System.in.available());

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).


Minimizing $a^TPa$ (for arbitrary $a$) vs minimizing trace$(P)$.

Question: Context: I am reading "Introduction to stochastic control theory"
by Karl Johan Åström. There he develops a Kalman filter with the goal of "minimizing $a^TPa$ for arbitrary vector $a$", where $P$ is the resulting covariance matrix of the filter. Surprisingly, the result doesn't depend on the vector $a$. Moreover, I have seen other papers/notes in which they develop the exact same result, but by minimizing trace$(P)$ instead, without mentioning any "arbitrary vector $a$".
Question: This confuses me. Is minimizing $a^TPa$ (for arbitrary $a$) somehow the same as minimizing trace$(P)$? What does "arbitrary $a$" mean anyway in this context?
Comment: It means Any vector $a$
Comment: Oh, for sure. But how does one minimize $a^TPa$ for some arbitrary $a$? Is that: optimize $a^TPa$ for all $a$?  Meaning that we expect the optimal P to be the same for an infinite amount of cost functions?
Comment: It can also be noted that if $P=\mathbb{E}\!\left((x-\mathbb{E}(x))\,(x-\mathbb{E}(x))^\top\right)$ than that $\text{trace}(P)=\mathbb{E}\!\left((x-\mathbb{E}(x))^\top (x-\mathbb{E}(x))\right)$.
Answer: Yes, minimizing $\text{trace}(P) = \sum_i P_{ii}$ is the same as minimizing $a^TPa$ for an arbitrary vector $a \neq 0$ because $P$ is symmetric (it is a covariance matrix) and so it can be diagonalized. That is, there exist matrices $D, V$ such that $P = VDV^T$, where $D = \text{diag}(d_1, \ldots, d_n)$. Since the trace operator is invariant under a change of basis and $a^TPa = a^TVDV^Ta=b^TDb=\sum_i b_i^2d_i$, minimizing the last term is the same as minimizing the trace because $b_i^2 > 0$.
Comment: Nice! Can you elaborate in the last part? Why minimizing that last term is the same as minimizing the trace? I get the intuition but I do not seem to be able to show it formally. Thanks!
Comment: Note that $d_i > 0$ because $P$ is positive-definite. It is easy to proof that for positive constants $c_1, \ldots, c_n$, the minimum of $\sum_i c_ix_i$ is attained at the same values of $x_i$ that the minimum of $\sum_i x_i$, if $x_i$ are constrained to be non-negative.
Comment: I think I get that. However, preciselly that "easy" part is the part where I'm struggling. I'll mark the answer as correct anyway. Thanks sir!


Unable to renew lets encrypt using certbot

Question: I'm running centos 6, I recently tried installing python 3, might have messed something up related to python
if I do
python2 /usr/local/bin/certbot-auto renew
I get
file "/usr/local/bin/certbot-auto", line 20 if [ -z "$HOME" ]; then ^
SyntaxError: invalid syntax

If I do
/usr/local/bin/certbot-auto renew
I get
import ssl File "/usr/local/lib/python2.7/ssl.py", line 146, in <module>
import base64        # for DER-to-PEM translation File
"/usr/local/lib/python2.7/base64.py", line 11, in <module> import binascii
ImportError: No module named binascii WARNING: unable to check for
updates. Traceback (most recent call last): File "<stdin>", line 16, in
<module> File "/usr/local/lib/python2.7/distutils/version.py", line 140,
in cmp compare = cmp(self.version, other.version) AttributeError:
StrictVersion instance has no attribute 'version' root@~$

Answer: Certbot was trying to run using python 2.6 which broken, I read the certbot bash script and saw that it can run using python 3 as well, so I ran it using python 3 like this
USE_PYTHON_3=1 ./usr/local/bin/certbot-auto renew
Issue solved


Como usar Javascript com Bootstrap4?

Question: Estou fazendo meu front-end com Bootstrap, quero usar js para eventos como onclick, por exemplo.

Caso não dê pra visualizar a imagem (versao resumida):

    <title>AgileHub - Parafernalia</title>
    <meta charset="UTF-8">
    <link rel="stylesheet"  type="text/css" href="parafernalia.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

         <button type="button" class="btn btn-primary btn-sm col-12" id="new" onclick="AddNewCard()">New issue</button>

Já inseri o jQuery e o bootstrap.js, mas ainda assim não está funcionando. Alguém pode me dar uma luz?
Comment: Recomendo você ler aqui: https://getbootstrap.com/docs/4.1/getting-started/introduction/
Comment: Bootstrap da versão 4 pra cima, requer "popper.js": jQuery primeiro, depois Popper.js, depois Bootstrap JS
Comment: Não esquece de colocar `` na primeira linha.
Comment: Eu coloquei o doctype e os scripts na ordem, mas ainda não funcionou, não acontece nada quando clico o botão.
Answer: Segue onde está o erro:

    <title>AgileHub - Parafernalia</title>
    <meta charset="UTF-8">
    <link rel="stylesheet"  type="text/css" href="parafernalia.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

         <button type="button" class="btn btn-primary btn-sm col-12" id="new" onclick="AddNewCard()">New issue</button>

      <---- aqui está errado

Segue o código correto:
<!DOCTYPE html>

    <title>AgileHub - Parafernalia</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="parafernalia.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

      <button type="button" class="btn btn-primary btn-sm col-12" id="new" onclick="AddNewCard()">New issue</button>

     <------ fecha

Comment: Agora foi, muito obrigada :)

Como usar Javascript com Bootstrap4?


open screen in background and start a process

Question: I want to do the following: After reboot I want to start a screen which then should execute a script. Therefore I searched for crontab and screen and I also did find some answers. However, nothing works for me. I am running a ubuntu linux with screen installed and I want to run a python script.
The following works screen -d -m which opens a screen but does not run anything. Instead, I'd like to create a screen and start a script. From what I found on the net answers told that this is accomplished by screen -d -m scriptname. In my case scriptname is main.py (which I checked that it is executeable).
However, screen -m -d /path/to/main.py does not create a screen. This is my console output
$ screen -d -m /opt/main.py
$ screen -x
There is no screen to be attached.

However, this works but does not execute the python script:
$ screen -d -m
$ screen -x

What am I doing wrong here? Thanks :)
Comment: What is the console output of `/opt/main.py` without screen?
Comment: It is a print("blabla"). However, I do not understand why this is important. The script works
Comment: Yes, and when the script finishes, screen terminates itself. What's wrong with that?
Comment: Ah, okay. You mean that the termination of the progam automatically quits the screen? Okay, but why does a `screen -d -m` not do the same?
Comment: Nope, this is not the case. The screen is _not_ terminated after execution. I modified my python script such that is take about 1 minute to complete. However after `screen -d -m /opt/main.py` I get again the response that `There is no screen to be attached.`. I do not think that this is reason why it does not work
Comment: Sorry, I made a mistake. It works. Thank you very much for your help :)
Comment: Could you write that up as an answer and accept it? Else this question will return to the front page every now and then and that would be very confusing :)
Answer: Actually screen -d -m /path/to/executable-python-script.py works fine.
However, after the script has terminated, the screen is automatically closed. Also, keep in mind that something like screen -d -m /usr/bin/python3 /path/to/executable-python-script.py does NOT work!
So, use for instance the following python script testscript.py to test:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time

def main():
    for i in range(10):
        print("Python3 Script " + str(i))
        time.sleep(5)

main()

And then do:

chmod +x testscript.py
screen -d -m /path/to/testscript.py
Quickly do a screen -x to check that the script is actually running


Mapear JSON para formato específico de array para gráfico de linha do Google Charts

Question: Tenho um JSON no seguinte formato:
[
  {
    "Countrys": [
      "Cyprus",
      "Finland",
      "Germany",
      "Grenada",
      "Haiti",
      "Ireland",
      "North Korea",
      "Swaziland",
      "Turkmenistan",
      "Zambia"
    ],
    "ListDataPerYear": [
      {
        "Year": 2011,
        "ListValues": [
          2110,
          6540,
          3870,
          0,
          387,
          2870,
          566,
          0,
          4770,
          609
        ]
      },
      {
        "Year": 2012,
        "ListValues": [
          1960,
          6280,
          3880,
          0,
          396,
          2850,
          574,
          0,
          4850,
          620
        ]
      },
      {
        "Year": 2013,
        "ListValues": [
          1690,
          6120,
          3940,
          0,
          393,
          2810,
          434,
          0,
          4880,
          635
        ]
      }
    ]
  }
]

Preciso usar esse JSON para gerar um gráfico de linha (Line Charts do google charts). Caso queiram ver um exemplo de como será o gráfico, será algo como está no snippet oculto abaixo:

      google.charts.load('current', {'packages':['line']});
      google.charts.setOnLoadCallback(drawChart);

    function drawChart() {

      var data = new google.visualization.DataTable();
            data.addColumn('number', 'Ano');
            data.addColumn('number', 'Cyprus');
            data.addColumn('number', 'Finland');
            data.addColumn('number', 'Germany');
            data.addColumn('number', 'Grenada');
            data.addColumn('number', 'Haiti');
            data.addColumn('number', 'Ireland');
            data.addColumn('number', 'North Korea');
            data.addColumn('number', 'Swaziland');
            data.addColumn('number', 'Turkmenistan');
            data.addColumn('number', 'Zambia');

            data.addRows([
                [2011, 2110, 6540, 3870, 321, 387, 2870, 566, 630, 4770, 609],
                [2012, 1960, 6280, 3880, 407, 396, 2850, 574, 900, 4850, 620],
                [2013, 2930, 6120, 3940, 201, 393, 2810, 434, 1500, 4880, 635]
            ]);

      var options = {
        chart: {
          title: 'Box Office Earnings in First Two Weeks of Opening',
          subtitle: 'in millions of dollars (USD)'
        },
        width: 800,
        height: 400
      };

      var chart = new google.charts.Line(document.getElementById('linechart_material'));

      chart.draw(data, google.charts.Line.convertOptions(options));
    }

Para isso preciso mapear o JSON para um array no formato abaixo:
[
    [Year, ListValues[0],  ListValues[1],  ListValues[2], ...,  ListValues[9]],
    ...
]

Ficando assim:
[
    [2011, 2110, 6540, 3870, 0, 387, 2870, 566, 0, 4770, 609],
    [2012, 1960, 6280, 3880, 0, 396, 2850, 574, 0, 4850, 620],
    [2013, 1690, 6120, 3940, 0, 393, 2810, 434, 0, 4880, 635]
]

Eu já consegui formatar o array, mas gostaria de saber se tem alguma forma de mapear esse formato de JSON de forma mais simples do que essa que fiz abaixo:

var result = [
  {
    "Countrys": [
      "Cyprus",
      "Finland",
      "Germany",
      "Grenada",
      "Haiti",
      "Ireland",
      "North Korea",
      "Swaziland",
      "Turkmenistan",
      "Zambia"
    ],
    "ListDataPerYear": [
      {
        "Year": 2011,
        "ListValues": [
          2110,
          6540,
          3870,
          0,
          387,
          2870,
          566,
          0,
          4770,
          609
        ]
      },
      {
        "Year": 2012,
        "ListValues": [
          1960,
          6280,
          3880,
          0,
          396,
          2850,
          574,
          0,
          4850,
          620
        ]
      },
      {
        "Year": 2013,
        "ListValues": [
          1690,
          6120,
          3940,
          0,
          393,
          2810,
          434,
          0,
          4880,
          635
        ]
      }
    ]
  }
];

var arrayAux = result.map(value => value.ListDataPerYear)[0];
var dataArray = [ arrayAux.map(value => value.Year), arrayAux.map(value => value.ListValues) ];

var dataLineChart = [];
arrayLength = dataArray.length;

//Montar array com valores (cada ano representa um linha)
for (var i = 0; i < dataArray[0].length; i++) {
 var row = [];
 row.push(dataArray[0][i]);
 for (var j = 0; j < dataArray[1][i].length; j++) {
  row.push(dataArray[1][i][j]);
 }
 dataLineChart.push(row);
}

console.log(dataLineChart);
Answer:

var result = [
  {
    "Countrys": [
      "Cyprus",
      "Finland",
      "Germany",
      "Grenada",
      "Haiti",
      "Ireland",
      "North Korea",
      "Swaziland",
      "Turkmenistan",
      "Zambia"
    ],
    "ListDataPerYear": [
      {
        "Year": 2011,
        "ListValues": [
          2110,
          6540,
          3870,
          0,
          387,
          2870,
          566,
          0,
          4770,
          609
        ]
      },
      {
        "Year": 2012,
        "ListValues": [
          1960,
          6280,
          3880,
          0,
          396,
          2850,
          574,
          0,
          4850,
          620
        ]
      },
      {
        "Year": 2013,
        "ListValues": [
          1690,
          6120,
          3940,
          0,
          393,
          2810,
          434,
          0,
          4880,
          635
        ]
      }
    ]
  }
];

var dataLineChart = result[0].ListDataPerYear.map(dataPerYear => [ dataPerYear.Year, ...dataPerYear.ListValues ]);
console.log(dataLineChart);

Isso é legível? Acredito que seja a maneira mais prática de se criar o array, mas você consegue entender o que está acontecendo?
Comment: Os três pontos é o operador _spread_. Quando utilizado antes de um array, esse operador desconstrói o array e passa cada um dos itens do array como um parâmetro diferente.
Comment: Ficou muito mais elegante, consigo entender sim, mas poderia explicar o motivo do '...' nesse trecho: [ dataPerYear.Year, ...dataPerYear.ListValues ]?
Comment: Perfeito! Se importa de editar e adicionar essa explicação na sua resposta? Me ajudou de mais, sabia que havia uma forma mais prática!! :)


adLDAP user must change password

Question: I have to let the user change his password when on the Active Directory System the flag, "user has to change password" ist set.
That just works when I grant adLDAP access via my AD Adminsitrator.
So, when a user trys to login I check if the attribute "pwdlastset" has a value that indicates, that the user has to change his password.
When yes I redirect him to a renew pw dialog.
The Problem at this solution is, that when the user enters a invalid initial password I also would redirect him.
Because I cant validate him. When I try to bind the user, with the attribute "pwdlastet" set it always returns me an error "Unable to bind".
<code>$adldap = new \adLDAP(array("base_dn" => $basedn, "account_suffix" => $accsuffix,"domain_controllers" => $dc,"admin_username" => $adminuser, "admin_password" => $adminpw));

//Get Requesting Users "pwdLastSet" Field over the Admin Account
$userToAuthInfo =  $adldap->user()->info($name,"pwdlastset");
if($userToAuthInfo[0]["pwdlastset"][0] == 0)
{
//redirect user to pwd renew
}
else
{
//bind user and redirect to home
}
</code>
Does anybody know how I could solve this ?
I thought if a seperate attribute with the pw would exist I could request that and check if its the same. But when i'm not wrong I think such an attribute does not exist.
Answer: <code>function userchange($username,$pwdLastSetVal,$domadlogin,$domadpw,$domctrl)
{
    $ldapServer = $domctrl;
    $ldapBase = 'OU= ,DC= ,DC= '; //be sure to set this according to your ldap settings
    $ds = ldap_connect($ldapServer);

    if (!$ds)
       die('Cannot Connect to LDAP server');

    $ldapBind = ldap_bind($ds,$domadlogin,$domadpw);
    if (!$ldapBind)
       die('Cannot Bind to LDAP server');

    ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3) or die("Error setting LDAP version");

    ldap_set_option($ds, LDAP_OPT_REFERRALS, 0) or die("Error setting referrals option");

    $attrs = array("samaccountname", "pwdlastset");
    $filter = "(samaccountname=".$username.")";
    $sr = ldap_search($ds, $ldapBase, $filter, $attrs);
    $ent= ldap_get_entries($ds,$sr);
    $dn=$ent[0]["dn"];
    $userdata=array();

    $userdata["pwdlastset"][0]=$pwdLastSetVal;

    ldap_modify($ds, $dn, $userdata); //change state

    ldap_close($ds);
}

// -1 or 0 after the username parameter
userchange($username, -1, $domadlogin, $domadpw, $domctrl);
</code>
I would call this function and pass -1 just before you try and bind the user and change their password to something new, if the bind is successful (the user supplied the incorrect current password), then call the userchange function again and pass 0, so it sets it back to what it was before and the user can try again. When the user successfully binds and sets their new password, you can call the userchange function and pass -1 in after the $username parameter.
Comment: Thank you, your solution pointed me into the right direction.

adLDAP user must change password


Some strange multinomial averaging

Question: How do I prove :
$\sum_{j=2}^{n} (-1)^j {\frac {M(n+j,j;2)}{j!}} = (-1)^n n! + 1$?
where $M(n+j,j;2)$ is the multinomial sum $M(n+j,j;2) = \sum_{t_1 + t_2 + \dotsc + t_j = n+j, t_k \geq 2} {n+j \choose t_1 \dotsc t_k}$ which denotes the number of surjective functions from $n+j$ points to $j$ points with at least two elements in each pre-image.
Answer: $M(n+j,j;2)$ is the number of ways of putting $n+j$ distinct balls into $j$ distinct urns such that each urn contains at least two balls. This is also the number of functions from a domain of $n+j$ objects (the balls) into a range of $j$ objects (the urns) which are doubly-surjective, i.e. every element of the range has at least two pre-images.
This latter problem has been solved in Notes on Doubly-Surjective Finite Functions by Walsh, who shows that $$M(n+j,j;2) = \displaystyle\sum_{k=0}^j\left[(-1)^k{j \choose k}\sum_{i=0}^k{k \choose i}\frac{(n+j)!}{(n+j-i)!}(j-k)^{n+j-i}\right]$$
Comment: This makes it more complicated triple sum. I have tried using induction and recursion formula by Walsh.
Comment: I would add some comments as to what I have thought more : multiplying by the $\pm 1$ we have to show $n! = {\frac {M(2n,n;2)}{n!}} - {\frac {M(2n-1,n-1;2)}{(n-1)!}} + \dotsc$ where $M(n+1,1;2) := 1$ for the case $j=1$. The terms ${\frac {M(n+j,j;2)}{j!}}$ can be better seen as the set ${\mathcal A}_j$ of all doubly surjective functions $f : \{ 1, 2, \dotsc, n+j \} \rightarrow \{ a_1, \dotsc, a_j \}$ modulo the equivalence that two such are same iff they coincide up to a bijection on the image.
Comment: By changing a image of one point to $x_{j+1}$ and adding to $n+j+1 \mapsto x_{j+1}$ produce some partial order to the disjoint union $\cup_{j=1}^{n} {\mathcal A}_j$. But the Moebius map of this is not the  one capturing the alternate signs in the sum.

Some strange multinomial averaging


How to query all Korean words start with an initial character

Question: It is easy to query all the words start with an initial character in English, for example to query all the words start with "a", we execute this query:
SELECT * FROM table WHERE word LIKE 'a%';

We can get results like "an", "at", "after"....
But it is not the same in Korean, because a Korean word is considered as a single Unicode character,
so this query:
SELECT * FROM table WHERE word LIKE 'ㄱ%';

will not return words like "가", "고", "간"... (The results may like "ㄱ자", "ㄱ견"...)
So what I should do to get the result as I expect? (i.e. I will get words like "가", "고", "간"... when I want to query the word start with "ㄱ")
Thank you very much!
Answer: Your problem here is one of unicode format and Korean's unique behavior of combining consonants and vowels to create a new character.  You can either store these new characters as individual glyphs, or as combined glyphs.  If you want to search like this, you need to store them as individual glyphs.  That means taking every incoming string that will be stored in the db and processing them before inserting them, breaking up compound glyphs into its components.  And if you have an existing db, you'd have to do that to the existing data as well.
The other route is to make a list of every possible combination of glyphs with that character with a complex expression in unicode, and search for all of them with a massive set of ORs.
Either way is a pain in the neck.  Asian languages can be a real problem for programmers, they all seem to have little things like that which make them difficult to process.


Why $S \subset X$ disconnected in his subspace topology implies $S$ disconnected on $X$?

Question: if $S$ are disconnected on his subspace topology then there exists $U \cap S$ where $U$ are open on $X$ and $H\cup S$ where $H$ are open in $X$ that $S=(U\cap S)\cup (H\cap S) = (H\cap U)\cup S$ but by this how can i find the open sets in $X$ such that $S$ is his union?
Comment: You also need to add that $\emptyset = (U \cap S) \cap (H \cap S) = (U \cap H) \cap S$ of course, and $U \cap S \neq \emptyset$ and $H \cap S \neq \emptyset$.
Comment: You cannot find two open subsets of $X$ that exactly union up to $S$ in general. That would imply $S$ is open, in $X$ as a union of sets open in $X$, you cannot do better than $S \subseteq U \cup U$.
Answer: $S$ disconnected on $X$ means $S$ is disconnected in its subspace topology by defination!
Your question makes no sense
Comment: I feel you should elaborate more on the real essence of connectedness i.e. any continuous map from S to {0,1} will be a constant map
Comment: S disconnected in X $\Longleftrightarrow$ S disconnected in his subspce topology, i want the details about $\Leftarrow$ and u mean $\Rightarrow$
Comment: @EduardoSilva What $\Leftarrow$, $\Rightarrow$ Please state equivalence between what conditions..?
Answer: $S = (H\cup U)\cap S $ implies $S \subseteq H \cup U$.
You seem to be implying there are two definitions of a disconnected subspace, but there is only one: $S$ is disconnected in its subspace topology.
Comment: but in the conditions that i put + your comments thats the definition of disconnected spaces
Comment: @EduardoSilva it's the translation of being disconnected in the subspace topology.


English translation of Riemann's complete works

Question: Browsing in the library I came across with the mathematical (and some philosophical) papers of Riemann, collected by Weber and Dedekind in the original German (although published by Dover). But apparently there's no English translation reported in internet, even for the most influential papers like the November 1859 report on the Zeta function, and in such a volume some of Riemann's correspondence with mathematicians in other languages are transcribed in the respective original (for example a letter in Italian to Betti). Since the volume is relative thin and certainly highly relevant I wonder if there exists an English translation. (By the way, apparently his complete correspondence has never been fully collected).
Answer: There is an English translation of the collected papers of Riemann, in $2004$. It says "This is the first English translation of the collected papers of Bernhard Riemann (1826-1866), one of the greatest mathematicians of all time. Riemann surfaces, Riemannian geometry and the Riemann zeta function are fundamental concepts of modern mathematics." And so on.
Answer: Though it does not address your question, On the Number of Prime Numbers less than
a Given Quantity is an excellent translation of his Riemann's 1859 Manuscript.
This might be useful to others.


How to pack a SFX file created with DotNetZip library without destroy the file?

Question: I've created a self executable with DotNetZip library and now I will pack the exe.
I've tried it with UPX, BoxedAPP, .NET Shrink and IlMerge, all of them destroys the SFX file.

Important:

The reason of why I'm trying to pack the SFX is because I will find a way to avoid the WinZip/ WinRar/ 7Zip or another extract options when right-clicking in the SFX file
I will mean the options: "Extract file to...", "Extract file here...", etc.
So for me is valid any answer explaining how to pack the DotNetZip SFX or an answer explaining how to avoid that options when creating an SFX with DotNetZip.
Thankyou for read.
Answer: With the help of the packer (like BoxxedApp Packer), you can create an executable file, it will run without the "Extract file to...", "Extract file here...", etc.
Answer: Have you created exe file by DotNetZip?
Answer: I have the same situation. I exactly want it as you describe, because the way I use now has some security leaks.
1) I have added the Winrar SFX auto extractor (exe) to my project as resource.
2) I write the exe to a 'secret' hidden directory in background, all confusingly named.
3) After writing is complete, run the SFX (exe) from that location.
4) Extractor places file (movie in my case) in readonly (temp) mode in a directory and then runs the file.
5) My app tries to delete the exe (will succeed when extraction is complete, otherwise the exe is still in use).
6) When people close the movie player, the temp movie will be deleted immediately.
The difference with your approach is that I try to hide my files for now. If people know about that location and are able to retrieve the exe file before it gets removed, then they can just extract it instead of running it...
I hope we're able to run the exe from within resource, instead of writing it to pc thus possibly exposing the files to people.


Como criar um painel que Exibe/Oculta campos usando Html/Bootstap/JavaScript

Question: Preciso implementar em uma tela, um painel de busca que precisa aparecer quando eu clicar no botão (Pesquisa Avançada) e dentro desse painel deverá ter um botão "Fechar" que, quando clicado, ocultará o mesmo... Como eu faço isso?
//Painel Oculto

//Painel visível

//Código do botão

<button id="btnPesquisaAvancada" type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
  data-original-title="Pesquisa Avançada" data-container="body">

 Pesquisa Avançada
</button>
Answer: Uma das maneiras de se fazer é utilizando jQuery de uma maneira simples com o método toggle.

$(document).ready(function() {

   $(".divOculta").hide();

   $("#btnPesquisaAvancada").on("click", function() {
      $(".divOculta").toggle();
   })

})
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>

<button id="btnPesquisaAvancada" type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
  data-original-title="Pesquisa Avançada" data-container="body">

 Pesquisa Avançada
</button>

    Situação
    <input type="text" class="form-control" id="sit" placeholder="Enter email">

    Tipo de cadastro
    <input type="text" class="form-control" id="cad" placeholder="Enter email">

Comment: Obrigado pela ajuda @Leandro!!!
Comment: Por nada man! :)
Answer: Fiz uma opção com jQuery que pode te atender. Ele faz um .slideToggle() no form de busca avançada. Como parece que vc está usando o BS4 coloquei o css desse framework, mas funciona em qualquer ambiente que tenha jQuery

$("button").click(function(){
    $(this).toggleClass("ativo");
    $(".busca").slideToggle();
});
.busca{
    display: none;
 }
 .ativo {
     background-color: royalblue;
 }
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />

         <button id="btnPesquisaAvancada" type="button" class="btn btn-outline btn-default" data-toggle="tooltip"
                 data-original-title="Pesquisa Avançada" data-container="body">

             Pesquisa Avançada
         </button>

        <form class="busca">

                <input type="text" class="form-control" placeholder="First name">

                <input type="text" class="form-control" placeholder="Last name">

        </form>

Comment: Obrigado pela ajuda @hugocsl... O painel está aparecendo aberto. Como que eu faço para mantê-lo sempre fechado e aparecer somente quando clicado no botão Pesquisa avançada?
Comment: @JalberRomano repare que tem um CSS que faz o `display:none` no elemento que vai conter o form do "busca avançada" dentro. Então basta vc colocar um classe `.busca{ display: none; }` por exemplo no elemento que tem o forme dentro e depois usar o script para fazer o toggle tipo `$(".busca").slideToggle();` Repare que eu Editei a minha resposta para ficar melhor o entendimento.
Comment: @JalberRomano resumindo, então o .busca já começa com o display:none e depois vc faz o toggle com o jQuery. Inclui no .css a regra para usar para esconder e depois fazer a referencia no script quando clicar no btn. Mas qq dúvida é só falar que te dou uma força se precisar de mais alguma explicação.
Comment: Ah simmmm, não tinha reparado que no css estava o "display: none;"....
Comment: @JalberRomano sim tem que usar pra esconder no inicio, boa sorte com o projeto!


How to use url_for to generate a path that doesn't exist in routes

Question: This might not be possible, but I thought I'd ask. I need to generate paths that are not present in my routes file.
For example I would like to be able to generate:
include Rails.application.routes.url_helpers
url_for(
  {
    :controller => 'accounts',
    :action     => 'index',
    :id         => '123',
    :only_path  => true
  }
) # => "/accounts?id=123"

The above will raise a ActionController::UrlGenerationError: No route matches.
Comment: show your `rails routes` output pls
Comment: You can pass extra params in your routes, just don't call it id. For example the following route will go to index action, if you have `ressources accounts` : `accounts_path(other_id: '123')` => /accounts?other_id='123' (I am not in front of my computer to check typos but you understand the point :) )
Answer: You can't do that AFAIK. url_for infers a lot of thing from the routes map and the url generated wouldn't work anyway.
What's the use case ? Maybe there's a better solution available.


New (x, y) position after rotating around z-axis

Question: I have line with end position (x1, y1) that I know. How can I calculate new position (x2, y2) after I rotate that line around it's z-axis by 40 degrees?
I draw the situation in the image below to help clarify.
image
Comment: Have you tried using polar coordinates?
Comment: @R.Burton Hi, yes I tried them in many forms, but nothing seems to work.
Comment: Could you provide more detail?
Comment: @R.Burton I can try. For example I tried r = sqrt(pow(x1, 2) + pow(y1, 2)) -> x2 = r * cos(φ), y2 = r*sin(φ), but that's not correct.
Answer: Using Basic Algebra/Trigonometry
To convert from Cartesian to polar coordinates, use the identity...
$$(r,\theta)=\text{CtoP}(x,y)=\left(\sqrt{x^2+y^2},\text{atan2}(y,x)\right)$$
...where $\text{atan2}$ is the two-argument arctangent.
To convert from polar to Cartesian coordinates, use the identity...
$$(x,y)=\text{PtoC}(r,\theta)=(r\cos{\theta},r\sin{\theta})$$
...where $r$ is the distance from the origin $(0,0)$ to $(x,y)$, and $\theta$ is the angle formed by the line passing through $(0,0,)$ and $(x,y)$ and the $x$ axis.
In the context of your problem, $(x_2,y_2)=\text{PtoC}(\text{CtoP}(x_1,y,1)+(0,40^\circ))$.
Explicitly:
$$(x_2,y_2)=\left(\sqrt{{x_1}^2+{y_1}^2}\cos(\text{atan2}(y_1,x_1)+40^\circ),\sqrt{{x_1}^2+{y_1}^2}\sin(\text{atan2}(y_1,x_1)+40^\circ)\right)$$
Using Linear Algebra
The rotation matrix for a rotation of $\theta$ in the Cartesian plane is given by...
$$\begin{bmatrix}\cos \theta &-\sin \theta \\\sin \theta &\cos \theta \\\end{bmatrix}$$
Using matrix-vector multiplication...
$$\begin{bmatrix}x_2\\y_2\end{bmatrix}=\begin{bmatrix}\cos \theta &-\sin \theta \\\sin \theta &\cos \theta \\\end{bmatrix}\begin{bmatrix}x_1\\y_1\end{bmatrix}$$
Explicitly:
$$(x_2,y_2) = (x_1\cos(40^\circ)-y_1\sin(40^\circ),x_1\sin(40^\circ)+y_1\cos(40^\circ))$$


Web Essentials não exibe opções

Question: Instalei o Web Essentials 2015 no Visual Studio Community 2015, mas ao tentar fazer a minificação de alguns arquivos css, as únicas opções exibidas foram as que estão na imagem abaixo.

Já removi e instalei novamente o Web Essentials, mas nada mudou. Também desistalei o Visual Studio e instalei novamente (o que me custou muito tempo), mas mais uma vez tive o mesmo resultado.
As seguinte opções eram para aparecer:

Como posso resolver isso?
Comment: Quais as opções que deveriam aparecer ali?
Comment: Todas essas: http://i.imgur.com/hes9ueL.jpg
Answer: Segundo o site da extensão Web Essentials 2015 no marketplace a minificação e bundling de JS/CSS, bem como algumas outras funcionalidades, foram movidas para plugins específicos.
Por favor baixe o plugin relevante e verifique se o item de menu necessário aparece.

Web Essentials não exibe opções


How to Solve This PDE and Deal with Boundary Value Using Method of Characteristics. Work Shown.

Question:
The function $u(x,y)$ satisfies $u_y + u_x = 0$ in $x > 0$, $y > 0$ together with the initial condition $u(x, 0) = \sin(x)$, $x > 0$ and the boundary condition $u(0, y) = \sin(y)$, $y > 0$. Determine the values of $u$ in the whole quarter plane $x > 0$, $y > 0$.

My problem is that, although I think I know how to use the initial condition, I don't know how to use the boundary condition?
The characteristic equations are
$$\frac{dy}{dt} = 1, \frac{dx}{dt} = 1, \frac{du}{dt} = 0$$
Writing the initial condition parametrically (parameterising $t = 0$ as the initial condition), we get
$$\Gamma = \Gamma(s) = (x_0(s)), y_0(s), u_0(s)) = (s, 0, \sin(s))$$
The curve $\Gamma$ is called the initial curve.
$\therefore \frac{\partial y(t, s)}{\partial t} = 1, \frac{\partial x(t, s)}{\partial t} = 1, \frac{\partial u(t, s)}{\partial t} = 0$
with initial conditions
$$y = t + C_1(s)$$
$$\therefore y(0, s) = C_1(s) = 0$$
$$x = t + C_2(s)$$
$$\therefore x(0, s) = C_2(s) = s$$
$$u(0, s) = C_3(s) = \sin(s)$$
So our solution is given by
$$x(t, s) = t + s, y(t, s) = t, u(t, s) = \sin(s)$$
I'm not sure entirely sure how to do this, and my textbooks don't discuss how to use method of characteristics to solve problems that have initial conditions and boundary values. I would be very grateful for help.
Answer: The solutions to the PDE $u_x +  u_y = 0$ are functions that are constant in the $(1,1)$ direction.
Recall how you use the initial data $u_0$ to define the solution: for any point $(x,y)$ you follow the characteristic line back to the initial condition at $y=0$ (so the point $(x-y,0)$), and since it was constant along the characteristic, the answer is $u(x,y) = u_0(x-y)$. Since the initial data is defined on $[0,\infty)$, can do this for all points $x\ge y$ i.e. points below or on the line $y=x$.
Now have a look at this graph of the boundary condition, initial condition and characteristic lines-

How would you now define the values of the solution above the $y=x$ line?

(Full solution.) It seems that you don't have any issue using just the "initial condition", i.e. the points $\color{red}{\{(x,0): x\ge 0\}}$. You can also use the "boundary data" i.e. the points $\color{blue}{\{(0,y): y\ge 0\}}$ to define the full "initial curve"
$$ \Gamma = \color{blue}{\{ (0,y, u_{\text{bdry}}(y)) : y\ge 0 \}} \cup  \color{red}{\{ (x,0, u_{\text{init}}(x)) : x\ge 0\}} $$
You can parameterise this using $s\in\mathbb R$,
$$ \Gamma(s) =
\begin{cases}
(s,0, \color{red}{u_{\text{init}}(s)}) & s\in [0,\infty) \\
(0,-s, \color{blue}{u_{\text{bdry}}(-s)}) & s\in (-\infty,0]
\end{cases}$$
with a compatability condition $\color{red}{u_{\text{init}}(0)} = \color{blue}{u_{\text{bdry}}(0)}$.
Now, we implement the method of characteristics. To find the characteristic curves $(x,y) = (x(t),y(t))$, we solve
$$ \frac{d}{dt} u(x(t),y(t)) = 0$$
Of course, $ \frac{d}{dt} u(x(t),y(t)) = u_x(x(t)) x'(t) + u_y(y(t)) y'(t) $ so we just need $x'(t) = y'(t) = 1$. Thus all characteristic curves are given by
$$ (x(t),y(t)) = (x_0,y_0) + (t,t) , \quad t\geq t_0 $$
where $t_0$ is the time we leave the set $\Gamma$. Using the same parameter $s$ as before, we determine $t_0$ using $x_0=x_0(s),y_0=y_0(s)$,
\begin{align} s\ge 0 &\implies x_0 = s,y_0 = 0, t_0 = 0 \\
 s<0 &\implies x_0 = 0, y_0 = -s, t_0 = -s\end{align}
and the full solution is $$u(s,t) = u(x(s,t),y(s,t)) = \begin{cases} \color{red}{u_{\text{init}}(s)} & s\ge 0, t\ge 0 \\ \color{blue}{u_{\text{bdry}}(-s)} & s < 0, t>-s \end{cases}$$
We have defined the solution on the set $\{ (s,t) : s \in \mathbb R, t \ge \max(-s,0) \} $, and they are related to $x,y$ by
$$x = s+t , y=t $$
So that $s = x-y$,
and it should be clear that this defines the region $x\geq 0$ and $y\ge 0$. In particular $\color{red}{x>y>0}$ iff $\color{red}{s>0}$, and $\color{blue}{y>x>0}$ iff $\color{blue}{s<0}$. Therefore, the answer in the original coordinates is
$$ u(x,y) = \begin{cases} \color{red}{u_{\text{init}}(x-y)} & 0\le y\le x \\ \color{blue}{u_{\text{bdry}}(y-x)} & 0 \le x<y\end{cases}$$

(Final remark.) There are many different ways to write this down. However, the graph above captures the main idea that has to be expressed by all proofs of this fact. Regardless of whichever proof you learn, my opinion is that you should make sure that your understanding matches the graph.
Comment: @handler'shandle I have added a full solution.
Comment: @handler'shandle yes, this is the effect of the term $f$.
Comment: @handler'shandle you're welcome!
Comment: I would say that the values of the solution above the $y = x$ line first intersect the $y$-axis, so I would use the condition $u(0, y) = \sin(y)$? I guess, in this case, these would be classified as the "initial condition" for those lines? Not sure if I'm on the right track here.
Comment: @handler'shandle Yes, exactly. The "boundary condition" is nothing more than an initial condition specified along a different curve.
Comment: Oh wow, just as I edited! I didn't think I was right, haha.
Comment: @handler'shandle :) I think you should be able to solve the rest of the problem now
Comment: So would we define a second parameterisation? If I'm not mistaken, $\Gamma = \Gamma(s) = (x_0(s)), y_0(s), u_0(s)) = (s, 0, \sin(s))$ is just along the bottom line?
Comment: @handler'shandle I think the current one is fine, an initial condition for an ODE does not /need/ to be at $t=0$.
Comment: Hmm, I still don't understand the process to solve this. It seems to me like we need 2 solutions, which means that I need to repeat the process above twice, once for the initial condition and again for the boundary condition?
Comment: Maybe I don't understand what you mean by parameterisation. You can arrange it into as many processes as you want, but there's 'only one' thing you need to do, which is to travel backwards along a characteristic until you hit a value you already know.
Comment: For $u_0(s) = \sin(s)$ in $\Gamma = \Gamma(s) = (x_0(s)), y_0(s), u_0(s)) = (s, 0, \sin(s))$, I used the initial condition $u(x, 0) = \sin(x)$. So it seems that I have to repeat this process for the second solution using $u(0, y) = \sin(y)$? I can't find any resources that have examples with initial conditions, so I have no idea what I'm supposed to do.
Comment: It seems like you do understand it but are unsure. I think you really do get it. But some pedantic points - One, It's all just one solution $u$. Two, you already repeat this once for each point $(x,y)$ with $y\le x$. So I'm not so sure why you think it's any different to continue doing this for the points $y>x$. You can find this in full generality in Evans where he defines what kinds of hypersurfaces you can use as initial data but he does it more generally than the 2D case.
Comment: I found some really good lectures online that I'm currently reading: https://sites.ualberta.ca/~aksikas/math337-cha2.pdf
Comment: I am writing notes now and will edit my main post with my new work when I'm done. :)
Comment: Thank you again for such an excellent answer! I spent a hours researching and writing down every detail of this, so I learned a lot. One question: I read that the solution $u$ is supposed to vary exponentially along the characteristics. In our case, isn't $u$ varying sinusoidally along the characteristics?
Comment: @handler'shandle no to both, the solution is *constant* along characteristics.
Comment: This is from page 39 of *Essential Partial Differential Equations* by Griffiths, Dold, and Silvester: "$x = py + k, u = A(k)e^y$. Thus the characteristics are simply straight lines along which $u$ varies exponentially. The parameter $k$ may be eliminated to give the general solution directly in terms of $x$ and $y$:"
Comment: @handler'shandle I bet it is solving a different equation.
Comment: It is solving $pux +quy = f$. So the behaviour of the solution along the characteristic varies depending on the equation?
Comment: Ahh, ok. Thank you again!


Computing $\sum \frac{1}{n^2(n^2+a^2)}$ using the residue theorem

Question: I have to find a closed form for $\sum_{n=1}^{\infty}\frac{1}{n^2(n^2+a^2)}$ (with $a\in \mathbb{R}$).
My idea was to use the residue theorem on $f(z)=\frac{\pi \cot(\pi z)}{z^2(z^2+a^2)}$, thus obtaining:
\begin{equation}
\text{Res}_{0}(f)+\text{Res}_{\pm ia}(f)+2\sum_{n=1}^{\infty}\frac{1}{n^2(n^2+a^2)}
=
\lim_{n\to \infty}\frac{1}{2\pi i}\oint_{c_n}f(z)dz
\end{equation}
($c_n$ is a circle with $r=n+\frac{1}{2}$, in order to avoid poles on the contour.)
Going on:
\begin{equation}
2\sum_{n=1}^{\infty}\frac{1}{n^2(n^2+a^2)}=\frac{\pi^2}{3a^2}-\frac{\pi\coth(\pi a)}{a^3}+\lim_{n\to \infty}\frac{1}{2\pi i}\oint_{c_n}f(z)dz
\end{equation}
At this point, I was quite sure that the integral was $0$, but this does not match the closed form I know to be true.
My questions are:

Is my approach correct? (maybe using
Poisson summation formula, even if it seems to me quite long to deal with the singularity of the series in $n=0$)
What kind of tecniques should I apply to compute the integral?

Note:
As Denklo noted, we can calculate the series using $\frac{1}{n^2}-\frac{1}{n^2+a^2}=\frac{a^2}{n^2(n^2+a^2)}$. The closed form is thus $\frac{1}{2a^4}-\frac{\pi \coth(\pi a)}{2a^3}+\frac{\pi^2}{6a^2}$, which is consistent with my results so far and should imply $\frac{1}{2\pi i}\oint f=\frac{1}{a^4}$
Comment: You may simplify the sum a lot: $$\frac{1}{n^2(n^2+a^2)}=\frac{1}{a^2}\frac{a^2+n^2-n^2}{n^2(n^2+a^2)} = \frac{1}{a^2}\left(\frac{1}{n^2}-\frac{1}{n^2+a^2}\right)$$ The two resulting sums you may look up i guess.
Comment: @denklo you are right, and it's surely quicker this way than my way. I will edit my question
Answer: We first decompose the series in two parts:
$\sum_{n=1}^{\infty} \dfrac{1}{n^{2}(n^{2}+a^{2})} = \dfrac{1}{a^{2}} \sum_{n=1}^{\infty} \dfrac{1}{n^{2}} - \dfrac{1}{a^{2}} \sum_{n=1}^{\infty} \dfrac{1}{n^{2} + a^{2}}$.
For the first series we use $\sum_{n=1}^{\infty} \dfrac{1}{n^{2}}  = \dfrac{\pi^{2}}{6}$.
For the second series we use the identity $\sum_{n = -\infty}^{\infty} \dfrac{1}{n^{2} + a^{2}} = \dfrac{\pi}{a} coth(\pi a)$ in order to get $\sum_{n = 1}^{\infty} \dfrac{1}{n^{2} + a^{2}} = \dfrac{\pi}{2a} coth(\pi a) - \dfrac{1}{2a^{2}}$.
The final result is given by:
$\sum_{n=1}^{\infty} \dfrac{1}{n^{2}(n^{2}+a^{2})} = \dfrac{\pi^{2}}{6a^{2}} - \dfrac{\pi}{2a^{3}} coth(\pi a) - \dfrac{1}{2a^{4}}$.
Answer: The error in my chain of thought was in $\text{Res}_0(f)$, which is not $-\frac{\pi^2}{3a^2}$, it is instead $-\frac{\pi^2}{3a^2}-\frac{1}{a^4}$
Answer: Expanding a little on Denklo's comment
We can solve a more general sum,
$$\sum_{-\infty}^{\infty} \frac{1}{n^{2}+a^{2}} = \frac{\pi}{a} \coth(\pi a).$$
Note that this sum satisfies the conditions in the above link. The poles lie at $z=ia$ and $z=-ia$, so
    $$\sum_{n=-\infty}^{\infty} \frac{1}{n^{2}+a^{2}} = -\pi\left[\operatorname{Res}\left(\frac{\cot(\pi z)}{z^{2}+a^{2}},ia\right) + \operatorname{Res}\left(\frac{\cot(\pi z)}{z^{2}+a^{2}},-ia\right)\right].$$
Computing the residues:
    $$\operatorname{Res}\left(\frac{\cot(\pi z)}{z^{2}+a^{2}},ia\right) = \lim_{z\rightarrow ia}\frac{(z-ia)\cot(\pi z)}{(z-ia)(z+ia)} = \frac{\cot(\pi ia)}{2i a} $$
and
    $$ \operatorname{Res}\left(\frac{\cot(\pi z)}{z^{2}+a^{2}},-ia\right) = \lim_{z\rightarrow  -ia}\frac{(z+ia)\cot(\pi z)}{(z+ia)(z-ia)} = \frac{\cot(i\pi a)}{2ia}.$$
Therefore, summing these we get
    $$\sum_{-\infty}^{\infty} \frac{1}{n^{2}+a^{2}} = -\frac{\pi\cot(i\pi a)}{ia} = \frac{\pi \coth(\pi a)}{a}.$$
You should be able to extend this idea to your sum along with the other term in $n^{-2}$.
Comment: Yes, this is the approach I used to obtain the closed form following Denko suggestion. The question is still: what's wrong in my approach?


How to change default behaviour of IE7 when it can't connect to an internal web server?

Question: We have a series of touch screen workstations located on our production floor. The interface is locked down so that IE7 is the only application running in the foreground, like a kiosk. The problem we have is that the internal web server that IE7 points to sometimes crashes, which after restarting requires that we go to each kiosk and manually reload the page. I would like to either have a custom IE7 error page that comes up once it can't connect to out internal web server that has a 'reload' or 'retry' button, or some way to do this automatically at specific intervals, if possible.
To clarify, I am looking for a way to limit the amount of human sysadmin interaction at each of these workstations when an error occurs connecting to our internal web server. I don't want to have to go to each station, connect a mouse/kb, just so I can hit the reload button and bring the web app back up.
Answer: The kiosk software should have a reload-to-home-page action executed when the terminal is idle for a few minutes, and a "restart" button including custom error pages. If no dedicated kiosk software is used perhaps one should be if the requirements demand these features ^^
I think Firefox can be configured in kiosk mode with a visible home button - useful for kiosk users as well as admins.
The kiosk software I've used always had stuff like this including central configuration, they were usually not expensive either.
If there's an easy way to send a "go to home" command to a running instance/tab of IE7 then you could create a custom screen saver or a scheduled task that starts on inactivity to trigger this...
Comment: There is no kiosk software, this is simply IE7 running in fullscreen mode. In Firefox, the error page has a retry button. Unfortunately, we need IE7 for specific functions of the web application in use.
Answer: I've worked recently with kiosk applications, and should say you, that there must be a possibility to logon as administrator. It's not very clever, that developer didn't create such possibility, see the documentation for this product.
Seconds, the unstable work of IE7 is mainly the result of some 3rd party applications or worms/viruses that works on this computer. Make a clean up !
God bless system administrators !


Boas práticas em uma requisição GET (API Laravel)

Question: Olá, tenho uma tabela com dados de Login de usuário e essa tabela possui relação com diversas outras tabelas (FK).
Estou fazendo uma API utilizando Laravel, porém surgiu uma dúvida. Se eu fizer um GET na tabela de Login, utilizando o ID do usuário, o que é melhor como boa prática: 1. Fazer um relacionamento e quando eu dar um GET na tabela de Login, utilizando o ID do usuário, já vir os dados de todas as tabelas relacionadas.
OU
2. Um "GET", pra cada tabela que tem o FK com o ID da tabela Login, dessa forma eu passaria um ID na requisição e cada tabela faria a "consulta" de forma individual. O que gostaria de fazer é ter uma área com os dados dessas tabela do usuário, pra que ele pudesse alterar, excluir, ler..., mas como estão distribuídas em outras tabelas, não sei o que é melhor prática ou que não seja tão pesado.
Comment: Depende da tua necessidade. Se vc quer apenas pegar os dados essenciais do usuário após o login seria uma boa prática buscar de uma única vez no banco, assim, evita requisições desnecessárias. Como vc já tem os relacionamentos, não teria o pq buscar tabela a tabela no momento do login. Na alteração dos dados, vc pode enviar um json com os dados a serem modificados e no controller validar esses dados para quais tabelas fazem parte.
Comment: Obrigado pela ajuda, nesse caso precisarei dos dados essenciais do usuário após o login, então buscarei de única vez então, como você sugeriu.
Abraço e obrigado!
Comment: Colocarei o comentário como resposta então, caso tenha ajudado. Por gentileza, marque-a como escolhida.
Answer: Depende da tua necessidade. Se vc quer apenas pegar os dados essenciais do usuário após o login seria uma boa prática buscar de uma única vez no banco, assim, evita requisições desnecessárias. Como vc já tem os relacionamentos, não teria o pq buscar tabela a tabela no momento do login. Na alteração dos dados, vc pode enviar um json com os dados a serem modificados e no controller validar esses dados para quais tabelas fazem parte.


Where does this formula for the effect of the mediator on the outcome comes from?

Question: I am reading the paper

Caron, P.-O., & Valois, P. 2018. A computational description of simple mediation analysis. The Quantitative Methods for Psychology, 14(2): 147–158.

There there is the following model for mediation:

Where:

$a_{xm}$ is the coefficient obtained by the following regression:
$$ M = a_{xm} X + \epsilon $$

$c_{xy}$, also called total effect, is the coefficient obtained by the following regression:
$$ Y = c_{xy} X + \epsilon $$

$c_{xy|m}$ and $b_{my|x}$, are obtained by the following regression:
$$ Y = c_{xy|m} X + b_{my|x} M + \epsilon $$

$b_{my}$ (unreported in the picture) is the coefficient obtained by:
$$ Y = b_{my} M + \epsilon $$

The paper says that:
$$ b_{my} = b_{my|x} (1-a_{xm}^2) + a_{xm} c_{xy} $$
This is equation (1) in page 148.
But there is no proof for that.
Why is that? Where does this formula comes from?
Answer: This comes from path analysis. We'll assume these variables are standardized, which is the only case in which these equations make sense.
Path analysis says that the unconditional correlation between two variables, which in this case is just the standardized regression slope of one on the other, is the sum of all the open pathways between the two variables. The contribution of a pathway is the product of all the regression slopes along that pathway.
In this case, we want $b_{my}$, which is the unconditional correlation between $M$ and $Y$. There are two pathways from $M$ to $Y$: the direct pathway and the indirect pathway through $X$. So, $b_{my} = Path_{MY} + Path_{MXY}$. We can compute those paths in a straightforward way using the rules above:
\begin{align}
Path_{MY} &= b_{my|x} \\
Path_{MXY} & = a_{xm} c_{xy|m}
\end{align}
That gives us $b_{my} = b_{my|x} + a_{xm} c_{xy|m}$. We're halfway there.
Next, realize that the total effect, $c_{xy}$, is the sum of the paths from $X$ to $Y$, which include the one through $M$ (the indirect path) and the direct path; the following equation gives the standard mediation decomposition of the total effect into the indirect and direct effects:
$$
c_{xy} = a_{xm} b_{my|x} + c_{xy|m}
$$
which can be rearranged as
$$
c_{xy|m} = c_{xy} - a_{xm} b_{my|x}
$$
If we substitute this formula into our formula for $b_{my}$, we get the result:
\begin{align}
b_{my} &= b_{my|x} + a_{xm} c_{xy|m} \\
       &= b_{my|x} + a_{xm} (c_{xy} - a_{xm} b_{my|x}) \\
       &= b_{my|x} - a_{xm}^2 b_{my|x} + a_{xm} c_{xy} \\
       &= b_{my|x}(1 - a_{xm}^2) + a_{xm} c_{xy} \\
\end{align}


Does the set of commuting endomorphisms always admit a cyclic endomorphism?

Question: Let be $C(u)$ the set of commuting endomorphisms with $u$ over a complex-valued vector space of finite dimension $n \in \mathbb{N}^{*}$.
I call $v$ a cyclic endomorphism iff all its eigenspaces are one dimensional vector space.
I'd like to know if $C(u)$ contains at least always a cyclic endomorphism.
My proof strategy is to distinguish multiple cases:
(1) if $u$ is diagonalizable: I can build such an invertible cyclic endomorphism by considering the eigenspaces
(2) if $u$ is nilpotent: that's precisely my issue, I'm trying to mess with Jordan reduction, but failed to do so.
(3) general case: I write $u = d + n$, such that $d$ is diagonalizable and $n$ nilpotent and $dn = nd$, I get an invertible cyclic endomorphism $v$ which commutes with $d$, but that's not enough to get $vu = uv$.
Comment: What do you mean by plane? two-dimensional subspace or hyperplane or ...? Because if you take your vector space to be $\mathbb C$, there are no planes contained in it and the answer to your question would be no.
Comment: In (3), if it commutes with $d$, why does it have to commute with $u$?
Comment: @James I meant one-dim vector space but I might be wrong in my terminology I will edit.
Comment: @James I think it's edited.
Comment: @ArnaudMortier That's actually false… Right, I thought that $v$ invertible and $dn  = nd$ and $vd = dv$ would suffice to get $nv = vn$ and then $vu = uv$, but that's false.
Answer: Your conjecture is true.
Let $A\in M_n(K)$ where $K$ is an algebraically closed field.
Then the Jordan form of $A$ is as follows
$A=Pdiag(\lambda_1 I_{k_1}+J_{k_1},\cdots,\lambda_p I_{k_p}+J_{k_p})P^{-1}$ where $J_r$ is the nilpotent Jordan block of dimension $r$, $k_1+\cdots+k_p=n$ and the $\lambda_i \in K$ are eigenvalues of $A$ that are NOT NECESSARILY DISTINCT.
Let $\mu_1,\cdots,\mu_p$ be $p$ DISTINCT elements of $K$.
Let $B=Pdiag(\mu_1 I_{k_1}+J_{k_1},\cdots,\mu_p I_{k_p}+J_{k_p})P^{-1}$; then $B\in C(A)$ and is cyclic.
REMARK. On a general field $K$, a cyclic matrix is s.t. its characteristic and minimal polynomials are the same. I don't know (I did not think about) if the previous result holds in this general case.


ZFS report of all user's usage

Question: I have a ZFS file system with over 35TB of data with an unknown number of people who have added data.   How can I get a report of each user's usage like output from zfs get userused@{uid} without knowing all the users that have data in the zfs file system?
Comment: No feedback to the detailed answer you got?
Answer: You can do it with zfs userspace (and zfs groupspace), which shows all users that either have files inside a filesystem (meaning they are the current owner of the file) or a quota inside a filesystem (set by zfs set userquota) or both. Note that it is not recursive (similar to zfs list, so you might have to call it for each child filesystem.
Example shell script
#!/bin/ksh

# get all children file systems from given file system argument
filesystems=$(zfs list -Hro name "${1}")

# get all space usage line by line in the format
# <usedspace>\t<userquota>\t<username>\t<filesystem>\n
# (it can later be sorted by the first column)
for filesystem in ${filesystems}; do
    sizes=$(zfs userspace -Hp -o used,quota,name "${filesystem}")
    IFS=$'\n'

    # multi-line output of userspace makes inner loop necessary
    for size in ${sizes}; do
        printf "%s\\t%s\\n" "${size}" "${filesystem}"
    done
    unset IFS
done

Example output
root@host:/root# ./test.sh rpool | sort -rn
cannot get used/quota for rpool/dump: dataset is busy
cannot get used/quota for rpool/swap: dataset is busy
4273131520      none    root    rpool/ROOT/omnios-2
4197847040      none    root    rpool/ROOT/omnios-1
2681162240      none    root    rpool/ROOT/omnios
[...]

Manpage details with available options
 zfs userspace [-Hinp] [-o field[,field]...] [-s field]... [-S field]...
   [-t type[,type]...] filesystem|snapshot
   Displays space consumed by, and quotas on, each user in the specified
   filesystem or snapshot. This corresponds to the userused@user and
   userquota@user properties.

   -H  Do not print headers, use tab-delimited output.

   -S field
       Sort by this field in reverse order. See -s.

   -i  Translate SID to POSIX ID. The POSIX ID may be ephemeral if no
       mapping exists.  Normal POSIX interfaces (for example, stat(2), ls
       -l) perform this translation, so the -i option allows the output
       from zfs userspace to be compared directly with those utilities.
       However, -i may lead to confusion if some files were created by an
       SMB user before a SMB-to-POSIX name mapping was established. In
       such a case, some files will be owned by the SMB entity and some by
       the POSIX entity. However, the -i option will report that the POSIX
       entity has the total usage and quota for both.

   -n  Print numeric ID instead of user/group name.

   -o field[,field]...
       Display only the specified fields from the following set: type,
       name, used, quota.  The default is to display all fields.

   -p  Use exact (parsable) numeric output.

   -s field
       Sort output by this field. The -s and -S flags may be specified
       multiple times to sort first by one field, then by another. The
       default is -s type -s name.

   -t type[,type]...
       Print only the specified types from the following set: all,
       posixuser, smbuser, posixgroup, smbgroup.  The default is -t
       posixuser,smbuser.  The default can be changed to include group
       types.

 zfs groupspace [-Hinp] [-o field[,field]...] [-s field]... [-S field]...
   [-t type[,type]...] filesystem|snapshot
   Displays space consumed by, and quotas on, each group in the specified
   filesystem or snapshot. This subcommand is identical to zfs userspace,
   except that the default types to display are -t posixgroup,smbgroup.

ZFS report of all user's usage


SSL certificate on the CDN and the origin

Question: One of our SSL certificate is about to expire next month. We use limelight CDN and we had provided them certificate when we started working with them.
We also use same certificates on our sites. All our sites are hosted on IIS.
We have renewed the certificate but I am not sure in which order we should change the certificate.
Possible things

change certificate in IIS site binding first and then ask Limelight (CDN) to change it
Ask Limelight (CDN) to change certificate and then change binding in IIS later
Change certificates at both end at the same time. But this is not an easy task as Limelight (CDN) does not have console and we have to depend on support tickets.

Please suggest what should be done.
Will we get some error if certificates used at IIS and CDN are different?
Comment: Barring special cases around certificate pinning, it doesn't matter which order you do it in, and it doesn't matter how fast you get it done. You could run two different SSL certs permanently, if you want. Hell, you could have 50 servers, each with their *own* different SSL cert, if you really wanted.
Comment: Correct. A valid certificate is a valid certificate, even if there are other valid certificates floating around for the same domain. In fact, it'd be a good idea to use a different certificate *always* for the CDN, so they don't have to have access to your webserver's private key - protects you if the CDN is ever breached.
Comment: Just confirming on this sentence "You could run two different SSL certs permanently, if you want."  Basically you are saying that it does not matter if we have two different certs installed for same domain on CDN and Origin. Is this correct? Sorry if you find this annoying.
Answer: Each TLS certificate has a validity period, which is defined when the certificate is issued. This means that the validity periods of two certificates can overlap.
So, if your current certificate is valid from October 1 2016 till September 30 2017, and your new certificate is valid from September 15 2017 to September 31 2018, it means that you have two weeks time to change the new certificate in your services and both certificates work at the same time.
Comment: But question is in this 2 weeks, can be change cert at CDN today and cert at origin after a week? Will it will impact anything?
Comment: No, it won't impact anything since both old and new certificates are valid (assuming common names match both the CDN and origin).


Deploy multiple spartacus storefronts?

Question: Is it possible to deploy multiple spartacus angular projects on Commerce Cloud?
I have two Spartacus project and want them both accessible to users. However currently they are deployed to the root and the second one overwrites the first.
Answer: This SAP support article has the answers: https://help.sap.com/docs/SAP_COMMERCE_CLOUD_PUBLIC_CLOUD/b2f400d4c0414461a4bb7e115dccd779/1c26045800fa4f85a9d49e5a614e5c22.html?version=v2105
You just need to make sure that you match the manifest.json app name with the output in angular.json outputPath, then you can set the routing in CCV2 by setting properties as followed:
Configure all endpoints to point to the JS Storefront service.
www.brand1.com → Javascript Storefront
www.brand2.com → Javascript Storefront
Configure endpoint-to-storefront mapping in JavaScript storefront service properties.
In the Cloud Portal, choose your environment, then select Service Configuration  View configurations  JavaScript storefront.
Add your properties in the following format: jsapps..severname.=.
For example:
jsapps.app1.servername.1=www.brand1.de
jsapps.app2.servername.0=www.brand2.com

Deploy multiple spartacus storefronts?


What do these squiggly arrows mean?

Question:
What does these squiggly arrows mean?
Comment: Does this answer your question? [What is the meaning of this squiggly vertical line symbol in guitar tablature?](https://music.stackexchange.com/questions/43391/what-is-the-meaning-of-this-squiggly-vertical-line-symbol-in-guitar-tablature)
Answer: Stagger the notes, so play them as an arpeggio, one after the other, top to bottom (as the arrow shows direction).
Comment: If there is no arrow you go bottom to top.

What do these squiggly arrows mean?


JBoss connection pool creating many connections to MySQL

Question: We are using a setup of JBoss 4.2.2.GA / Hibernate 3.2.4.sp1 / SpringMVC 2.5 / MySQL 5.0.27.
Below is the mysql-ds.xml file:
<datasources>
  <local-tx-datasource>
    <jndi-name>myDS</jndi-name>
    <connection-url>jdbc:mysql://127.0.0.1:3306/database?zeroDateTimeBehavior=convertToNull&useConfigs=maxPerformance</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>user</user-name>
    <password>password<password>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <min-pool-size>5</min-pool-size>
    <max-pool-size>100</max-pool-size>
    <blocking-timeout-millis>30000</blocking-timeout-millis>
    <idle-timeout-minutes>1</idle-timeout-minutes>
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>

Looking at the JMX-Console -> service=ManagedConnectionPool, we are using JBossManagedConnectionPool.
Now, the problem is that even with mediocre traffic (site attracted approx 5000 Visits / 15000 pageViews yesterday), there are 96 threads in sleep mode on MySQL (got using show processlist).
These do get reduced in time but my real question is, why is jboss creating so many connections? MaxConnections on MySQL = 250.
Any help appreciated!
Comment: MySQL just crashed due to 'Too Many Connections'. This is high-priority now so plz any help will do... Also, as per Zoltan's comment, isn't it the connection pool's job to manage my sessions?? How else will I be able to reuse connections? If it helps, I can give a brief view into how the code is setup in my app & is being used!!
Comment: hmm no replies so far??? We need to fix this asap!! Plz help....
Answer: When I experienced this, the problem was that some hibernate sessions were not closed and this cause connection leak. Check that your session close statements are in finally block.
Comment: I assure you we are only using `sessionFactory.getCurrentSession()` and not `sessionFactory.openSession()` so as per the link, sessions should be flushing & closing automatically!!
Comment: Thanks for replying. Yes, we are using try / catch / finally blocks like... `UserTransaction trans = null`, `trans = transactionManager.getUserTransaction();trans.begin();` in try, `trans.rollback()` in catch & `if (trans != null && trans.getStatus() == Status.STATUS_ACTIVE) {try.commit();}` in finally.
Comment: BTW.. we are injecting transactionManager into all our services & sessionFactory into our dao, but aren't explicitly using `session.flush() or session.close()`
Comment: The session won't be closed in every case if JBoss manages the connection. See: http://community.jboss.org/wiki/sessionsandtransactions
Answer: After much analysis, it was discovered that Hibernate was issuing too many queries in the back-end to load certain mappings, as mysqladmin status command gives 500 queries / sec.
Resolving this should resolve this problem as well.
Thanks to everyone who helped...


Dirichlet form of 2 Complex Functions is a conformal invariant

Question: Let complex functions $g,h$ be defined on a bounded domain $U$. The Dirichlet form of $g$ and $h$ is:
$$
D_U(g,h)=\int\int_U \left [ \frac{\partial g}{\partial x}\frac{\partial \bar{h}}{\partial x} +\frac{\partial g}{\partial y}\frac{\partial \bar{h}}{\partial y} \right ] dxdy
$$
I am trying to show that the Dirichlet form is conformal invariant: Let $z = f(\xi)$ be a 1-1 analytic function from a bounded domain $V$ to $U$, then:
$$
D_U(g,h)=D_V(g \circ f, h \circ f)
$$
I can see quite clearly the image of this theorem. However, I couldn't find a way to transform the integral from in $V$ to in $U$.
Answer: Expressing the partial derivatives as column vectors, we have $D_U(g,h)=\int\int_U\left[\left(\frac{\partial\bar{h}}{\partial (x, y)}\right)^T  \frac{\partial g}{\partial (x, y)}\right]dxdy.$
The Jacobian matrix of $f$ can be written as $f'=\frac{\partial(x,y)}{\partial(s,t)}=\rm{Re}(f') \left(\begin{array}{cc}
1 & 0\\
0 & 1
\end{array}\right) + \rm{Im}(f') \left(\begin{array}{cc}
0 & -1\\
1 & 0
\end{array}\right).$
Now $\left[\left(\frac{\partial\bar{h}}{\partial (s, t)}\right)^T  \frac{\partial g}{\partial (s, t)}\right]dsdt=\left[\left({f}'\frac{\partial\bar{h}}{\partial (x, y)}\right)^T  f' \frac{\partial g}{\partial (x, y)}\right]dsdt=\left[\left(\frac{\partial\bar{h}}{\partial (x, y)}\right)^T   \frac{\partial g}{\partial (x, y)}\right][(\rm{Re}(f')^2-\rm{Im}(f')^2)dsdt]=\left[\left(\frac{\partial\bar{h}}{\partial (x, y)}\right)^T \frac{\partial g}{\partial (x, y)}\right]dxdy.$


Music Cognition-Are people who play just by ear and intuition good in music cognition by natural talent?

Question: I am learning to play the harmonica. As with so many people around the world, the approach I use is to take a song and its notes somewhere from the internet and practice it until I can play it well.
But somehow I feel I'm missing something very important here. As I proceed further and deep into it I feel this thing can be briefly divided into two parts:

Learning how to play a instrument.
Learning what to play on the instrument.

The whole idea of practice is to do the first part. That is to learn the instrument, its behavior, its sounds and then getting so used to it that ultimately playing the instrument becomes a part of your muscle memory. I know that is no ordinary feat in itself but there is hardly anything special about it.
I am a programmer by profession, and I can type very fast. I know editor commands of a code editor called Emacs so well that I do some actions automatically. But none of this helps me in software cognition or code cognition. They sure help me in expressing ideas faster, but they are tools for when I solve the problem on paper so that I can quickly express it on the computer. In other words, typing quickly is not programming.
In the same way, I draw parallels between learning a instrument and learning typing. Currently I take song notes from the internet and just practice. This means that I am currently just learning the instrument, not music itself. I also see that a few people have the intuition to just figure out music by ear! I know there is some logical cognition involved which helps them do this.
My question is, how can I learn music cognition? What should I read and practice about music that helps in thinking and producing my own music and understand music produced by others? Is it possible to develop music cognition? Or is it only some sort of natural talent?
Answer: Playing by ear and "intuition" is related to the field of music theory, but more practically is related to ear training and aural skills. As you suspect, some people develop this innately from an early age, but it is a skill that can be developed by a novice later in life.
Here's the cliff notes version: You need to practice listening to music, singing what you hear, and identifying errors in your own playing. Can you tell when someone else plays a wrong note? Can you tell when you play a wrong note? Being able to play by ear is basically this: listen to what you want to play until you know how it sounds (and can sing it back), and then figure it out on your instrument. At first, this second part will be a lot of trial and error, so start simple. This is the skill that professional training and music theory can help with, but if you can identify when you play something that didn't match what you hear, it'll just take practice to develop the connection between what you hear and what you can play.
Improvising is basically the same, except instead of hearing music first, you're hearing it inside your head as you come up with it, and the link between your ear and your instrument is so strong that you are able to play that "fluently." It's kind of like learning how to type. At first you need to pick out each individual letter in each word or each sentence, but now you can just think in sentences and let your fingers do the work.
Answer: What you want to get into is music theory.  A big part of the music theory courses (at least the ones I have taken) is interval and harmony recognition. By understanding the theory and learning to hear the intervals it will be easier to play by ear. This is however something that takes a lot of practice and yes, for some it will be easier than for others. Another very important part is learning to play scales. Another thing you will want to learn is the relationships of chords and the circle of fifths (Wikipedia has a good guide here).
There is a lot more but these are a few pointers to start out with.
Answer: For ear-training you could follow the basic procedure used by Suzuki students. At first, play melody lines you already know really well, anything from nursery rhymes to pop songs to Christmas carols. Start with something simple like Twinkle Twinkle, pick a starting note and try to reconstruct the tune. Be kind to yourself and go a couple of notes at a time; once you have three or four correct-sounding notes in a row, practice them a few times before moving on. Try not to write anything down until you've got the whole simple tune by ear. Once you've really got it, try playing around with the tune by varying the rhythm, adding decorative extra notes, or transposing (picking a different starting note and playing the melody correctly from there). That helps you become more certain about your grasp of the notes, and it's also the beginnings of improvisation.
Then, move on to tunes you don't already know, but saturate your ears in a recording of the desired tunes for at least a week or so until you can sing along easily. Even better is if you can sing or mentally hear the tune (getting it "stuck in your head") without first being prompted by the recording. Once at this point, use the recording and trial-and-error to find the starting note on your instrument, and then try to figure out the notes as you did for the already-known tunes. Don't try to play along with the recording (it won't allow you enough time to think) -- rely on your knowledge of how it goes.
Do something fun with each tune. Try to resist the adult learner's lure of rushing through too many pieces too quickly without really understanding and enjoying each one.
After doing this for a while you will be able to hear certain patterns like going higher vs. going lower, moving by one or two notes vs. moving by a large leap, without having to test out every possibility on your instrument. The more patterns you learn to hear, the faster you will become at learning new pieces by ear. If you do invest time in studying music theory, you will know many more patterns and they will help.
Dr. Suzuki believed that musical ability can be learned and developed through practice in the same way as one's ability to speak one's mother tongue. This method of learning is through practice (making music and then playing around with it) instead of learning theoretical rules first and then applying them.
Hearing a piece once or twice and being able to identify all the notes is actually a pretty hard task -- college students have to do it for exams and they sweat and stress over it.
Answer: Listening to music and trying to play it (with or without sheet music) is a primary way to gain an understanding of music.  But I can't recommend enough reading about music theory and ideas.  Though I can't agree with or understand completely everything they say, the famous composers Paul Hindemith and Arnold Shoenberg have very interesting books on music fundamentals.  Try also reading Heinrich Schenker (of Schenkerian Analysis).  The common denominator of these three is probably the study of Western Harmony, which seems to instantiate the most challenging aspects of music that desire special concentration.
For a rather encyclopedic account, see Walter Piston's Harmony.
Try also reading history.  The story of how the West came to employee almost exclusively the twelve tone equal tempered scale is not just technically rich, but highlights the emphasis and understanding of Western Music's greatest minds.
If you haven't considered it already, I'd strongly recommend studying Bach (like the Well-Tempered Clavier).  Many consider his works supremely elegant and representative of the most significant musical ideas.
Answer: Not just "natural talent" by any means. Intuition is a subconscious process trained by experience. A big part of what intuition does is comparing an input to a database of familiar patterns. For instance, it compares the song you're hearing and its chord progression to the database of all songs you know and the harmonies used in those, and tells you which chord is likely to come next. If your database is empty (which is how you once started), then your intuition has nothing to work with. If you have a robust library in there, you're likely to get fairly good results.
It doesn't really run on logic and, being subconscious, it's not directly controllable. But it's definitely learned and can be trained on purpose.
How? Well, get it enough experience to feed on. Listen to music. Play music. Notice rhythms and harmonies and progressions. Listen and play some more. Broaden your horizons. Deepen your understanding. Listen. Play.
(And, yes, knowing some theory helps you properly annotate the patterns as you're saving them.)


When is the distribution of product of two normal distributed variables near normal distribution?

Question: It is clear the product of normal distributed variables is not normal distributed. For example, if $X \sim N( \mu_1,\sigma_1^2)$,  $Y \sim N( \mu_2,\sigma_2^2)$, then $XY$ does not has the distribution of $ N( \mu_1 \mu_2,\mu_1^2 \sigma_1^2+\mu_2^2\sigma_1^2)$.
I have been told that even if the distribution of $XY$ is not normal distribution, the distribution of $XY$ is near to normal distribution, when $\mu_1$ and $\mu_2$ are not so small, $\sigma_1$ and $\sigma_2$ are not so big. Is it true?
Try following R code:
<code>    n1 <- rnorm(10000,0,.005)
    n2 <- rnorm(10000,0,.005)
    n  <- n1*n2
    d  <- density(n)
    plot(d,lwd=2)
    x  <- par('usr')
    dn <- dnorm(d$x,mean=mean(n),sd=sd(n))
    x  <- seq(x[1],x[2],length.out=length(dn))
    lines(x, dn ,col=2, lwd=2)
    legend('topright', legend=c('Estimated density', 'Normal
    distribution'), lwd=2, lty=c(1,1),col=c(1,2))
</code>
$\sigma_1=\sigma_2=0.005$" />
It seems only when two conditions are both meet, the distribution is near normal. Is there any theoretical analysis?
Comment: Since $XY=(X/2+Y/2)^2 - (X/2-Y/2)^2$ and $X/2+Y/2\sim N(\mu_1/2+\mu_2/2,\sigma_1^2/4+\sigma_1^2/4)$ and $X/2-Y/2\sim N(\mu_1/2-\mu_2/2,\sigma_1^2/4+\sigma_1^2/4)$, it follows that $XY$ is a multiple of the difference of two non-central $\chi^2$ distributions, each with one degree of freedom. (They will be correlated when $\sigma_1\ne\sigma_2$, but that's not going to change the tail behavior of the difference unless one of the $\sigma_i$ dominates the other). That makes it apparent that $XY$ usually won't look at all Normal and provides a good source of counterexamples.
Comment: I have updated some R code in the question. As seen in the figure, even if the coefficients of variation are small, the final distribution still not near normal. It seems there are more restrictions.
Comment: Do you intend that X and Y be independent? [Your variance term looks wrong](http://en.wikipedia.org/wiki/Variance#Product_of_independent_variables). If they're more generally dependent, it looks even more wrong. But yes, Yes, if the coefficients of variation are small, the product of two independent normals is fairly normal.
Comment: Yes, they are independent.
Comment: Please check the definition of [coefficient of variation](http://en.wikipedia.org/wiki/Coefficient_of_variation#Definition) carefully, and try again with small coefficient of variation (yours aren't small!)
Comment: For example, with those s.d.s, try means of say 0.2 and 0.3. The coefficients of variation will be easily small enough then.
Answer: (this answer uses parts of @whuber's comment)
Let $X,Y$ be two independent normals.  We can write the product as
$$
   XY = \frac14 \left( (X+Y)^2 - (X-Y)^2 \right)
$$
will have the distribution of the difference (scaled) of two noncentral chisquare random variables (central if both have zero means).  Note that if the variances are equal, the two terms will be independent. Since chisquare distribution is a case of gamma, Generic sum of Gamma random variables  is relevant.  I will give a very special case of this, taken from the encyclopedic reference https://www.amazon.com/Probability-Distributions-Involving-Gaussian-Variables/dp/0387346570
When $X$ and $Y$ are independent, zero-mean with possibly different variances the density function of the product $Z=XY$ is given by
$$
   f(z)= \frac1{\pi \sigma_1 \sigma_2} K_0(\frac{|z|}{\sigma_1 \sigma_2})
$$
where $K_0$ is the modified Bessel function of the second kind.
This can be written in R as
<code>    dprodnorm  <-  function(x, sigma1=1, sigma2=1) {
       (1/(pi*sigma1*sigma2)) * besselK(abs(x)/(sigma1*sigma2),  0)
    }
    ### Numerical check:
    integrate( function(x) dprodnorm(x), lower=-Inf,  upper=Inf)
    0.9999999 with absolute error < 3e-06
</code>
Let us plot this, together with some simulations:
<code>    set.seed(7*11*13)
    Z  <-  rnorm(10000) * rnorm(10000)

    hist(Z, prob=TRUE, nclass="scott", ylim=c(0, 1.5),
            main="histogram and density of product of independent
                  normals")
    plot( function(x) dprodnorm(x),  from=-5,  to=5,  n=1001,
          col="red", add=TRUE, lwd=3)
    ### Change to nclass="fd" gives a closer fit
</code>

The plot shows quite clearly that the distribution is not close to normal.
The stated reference do also give more involved cases (non-zero means ...) but then expressions for density functions becomes so complicated that they only gives characteristic function, which still are reasonably simple, and can be inverted to get densities.


Mostrar uma div e esconder outra no Hover

Question: Tenho 3 divs que mostram 3 produtos:

E uma div com display:none que aparece só quando passa o mouse em cima da div produtosDestaqueBoxItem.

teste

Fiz isso com Jquery:
$(".produtosDestaqueBoxItem").hover(function () {
    $(this).hide();
    $('.produtoDestaqueBox').show();
});

Porém, isso funciona apenas no primeiro item. Teria que usar INDEX, ELEMENT?
Exemplo:
Comment: As divs `. produtosDestaqueBoxItem` e `. produtoDestaqueBox` são irmãs?
Comment: Eu não entendi muito bem o que você quer fazer, é algo semelhante a isso: http://jsfiddle.net/dieegov/p97BN/ ??
Comment: Basicamente o que eu estou tentando entender é se o seu HTML é o que está na resposta do Jader ou se é outra coisa. Por favor [sempre poste o HTML necessário para que os outros possam reproduzir o problema](http://pt.stackoverflow.com/help/mcve).
Comment: @FelipeStoker essa é meu último palpite, não entendi muito o que você deseja. http://jsfiddle.net/dieegov/p97BN/2/
Comment: isso mesmo @DiegoVieira
Comment: Isso resolve seu problema? pois pode fazer de mais de uma forma, sem mesmo utilizar jquery
Comment: Quase. No hover, ele aplica a classe que informei, mas quando está fora, ele volta ao normal
Comment: @bfavaretto não. A div `produtosDestaqueBoxItem` tem 3 iguais, a `produtoDestaqueBox` aparece somente no hover
Comment: Mas qual é a relação entre elas no HTML?
Comment: São 3 divs `produtosDestaqueBoxItemCentralizar`. Quando eu passo o mouse em cima de uma delas, o `produtoDestaqueBox` deixa de ser `display:none` e fica `display:block`, ele substitui a div. O Jquery que usei funcionou apenas no primeiro item.
Comment: Então tem um único `produtoDestaqueBox` para os 3 produtos?
Comment: @FelipeStoker http://jsfiddle.net/dieegov/p97BN/1/
Answer: Você esta ocultando o elemento que esta disparando o hover...
acho que deve ser algo assim:
jquery:
$( ".produtosDestaqueBoxItem" ).hover(
  function() {
    $( this ).children(".produtosDestaqueBoxItemCentralizar").hide();
    $( this ).children(".produtoDestaqueBox").fadeIn();
  },
  function() {
    $( this ).children(".produtosDestaqueBoxItemCentralizar").show();
    $( this ).children(".produtoDestaqueBox").fadeOut();
  }
);

HTML:

teste

obs.: Se quiser, style="display:none" pode ser incorporado na classe .produtoDestaqueBox
Comment: acabo de editar, mas como eu disse, você não pode ocultar o elemento que dispara o hover, pois assim vai imediatamente disparar o "mouseout", e anular a ação, ao invez disso, oculte todo o restante do conteúdo, mantendo o div que esta disparando o hover visível.
Comment: Sim funciona do mesmo jeito, a diferença é que o find procura até dentro dos filhos sem limite de níveis, e o children apenas nos filhos do elemento pai.
Comment: Show de bola, só que ele não esconde a div `produtosDestaqueBoxItem` e mostra a div `produtoDestaqueBox` no lugar dela.
Comment: Entendi @Jader, muito obrigado, funcionou! :P
Comment: Só uma outra dúvida @Jader, eu poderia ter usado o `find` no lugar do `children`?


Uso do "print()" vazio em vez de "\n"

Question: É errado utilizar print() para dar um espaço em vez do caracter \n?
Exemplo:
idade = int(input('Quantos anos você tem?'))

if idade > 0 and idade < 10:
    print('Você é uma criança.')
elif idade >= 10 and idade < 20:
    print('Você é um jovem.')
elif idade >= 20 and idade < 40:
    print('Você é um adulto.')
elif idade >= 40 and idade < 60:
    print('Você está na meia-idade.')
elif idade > 60:
    print('Você está na velhice.')

Colocando um print() antes das condições:
idade = int(input('Quantos anos você tem?'))

print()

if idade > 0 and idade < 10:
    print('Você é uma criança.')
elif idade >= 10 and idade < 20:
    print('Você é um jovem.')
elif idade >= 20 and idade < 40:
    print('Você é um adulto.')
elif idade >= 40 and idade < 60:
    print('Você está na meia-idade.')
elif idade > 60:
    print('Você está na velhice.')

Colocando um \n no começo de todos os prints:
idade = int(input('Quantos anos você tem?'))

if idade > 0 and idade < 10:
    print('\nVocê é uma criança.')
elif idade >= 10 and idade < 20:
    print('\nVocê é um jovem.')
elif idade >= 20 and idade < 40:
    print('\nVocê é um adulto.')
elif idade >= 40 and idade < 60:
    print('\nVocê está na meia-idade.')
elif idade > 60:
    print('\nVocê está na velhice.')

Opto por usar o print(), pois acho mais simples. Mas isso seria válido? Outros programadores fazem o mesmo? Ou o ideal seria colocar \n em cada print para dar um espaço, mesmo após um código com várias condições?
Comment: O colega já respondeu de forma adequada. Gostaria de salientar que não existem perguntas "besta", besta é quem não faz perguntas. As dúvidas são inerentes ao processo de aprendizagem e não importa se é um iniciante ou um senior developer, dúvidas sempre existirão.
Answer: De fato não tem problema. Outra alternativa seria você apenas definir o valor de uma variável com as suas condições e chamar a função print apenas uma vez. Isso seria outra aplicação do que o Maniero comentou na resposta dele sobre a repetição de código. Hoje você está enviando o resultado para a saída, mas se precisasse alterar isso para salvar em um arquivo, por exemplo, seriam vários lugares do código para fazer a mesma alteração; fazendo apenas uma chamada seria apenas uma linha alterada:
idade = int(input('Quantos anos você tem?'))

if idade > 0 and idade < 10:
    mensagem = 'Você é uma criança.'
elif idade >= 10 and idade < 20:
    mensagem = 'Você é um jovem.'
elif idade >= 20 and idade < 40:
    mensagem = 'Você é um adulto.'
elif idade >= 40 and idade < 60:
    mensagem = 'Você está na meia-idade.'
elif idade > 60:
    mensagem = 'Você está na velhice.'
else:
    mensagem = 'Não sei o que fazer com este valor.'

print(f'\n{mensagem}')

Nota: adicionei o else para garantir que mensagem seja sempre definida independente das condições (idade negativa, por exemplo).

Vale citar também que em Python não necessita fazer a condição:
idade > 0 and idade < 10

Você pode fazer:
0 < idade < 10

Que fica muito mais legível aos humanos. Desta forma, ficaria:
idade = int(input('Quantos anos você tem?'))

if 0 < idade < 10:
    mensagem = 'Você é uma criança.'
elif 10 <= idade < 20:
    mensagem = 'Você é um jovem.'
elif 20 <= idade < 40:
    mensagem = 'Você é um adulto.'
elif 40 <= idade < 60:
    mensagem = 'Você está na meia-idade.'
elif idade > 60:
    mensagem = 'Você está na velhice.'
else:
    mensagem = 'Não sei o que fazer com este valor.'

print(f'\n{mensagem}')

Answer: Não tem problema algum. Na verdade você está pensando como um programador e evitando repetições desnecessárias. Talvez não veja muito isso porque algumas pessoas não pensam como programadores e outras só copiam códigos de outros ou de si mesmo, então a cópia cria sem querer repetições. Não digo que este caso faça tanta diferença assim, mas se a semântica é "pular uma linha independente de qual condição caia". Em uma situação diferente talvez a decisão seria outra. Não existe regra mágica, tem que entender o problema e fazer o que ele pede.
Faça um exercício, pense em que problemas esperaria ter se fizer de um jeito ou de outro. Saber o porque é mais importante que saber o que fazer.
Dá para simplificar as condições dos ifs.
idade = int(input('Quantos anos você tem?'))
print()
if idade < 1:
     print('Não sei o que fazer com este valor.')
elif idade < 10:
   print('Você é uma criança.')
elif idade < 20:
     print('Você é um jovem.')
elif idade < 40:
     print('Você é um adulto.')
elif idade < 60:
    print('Você está na meia-idade.')
else:
     print('Você está na velhice.')

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

Uso do "print()" vazio em vez de "\n"


Extension of smooth maps at a cusp

Question: There is a short remark in deCarmos "Riemannian Geometry" (p. 67)

and I wonder about the condition that the vertex angles must be $\neq \pi$. If $s_1$ and $s_2$ are two differentiable maps on an open set containing $A$ and if $p$ is a cusp point in $\partial A$, then how is it possible that $ds_1|_p \neq ds_2|p$?
Taking the first open set $U$ in the above quote, what about a sequence $x_n$ in $U$ sucht that $x_n \rightarrow p$ and then by continuity  $ds_1|_p = ds_2|p$? Where does the condition about the angle $\neq \pi$ enter the discussion?
Comment: Don't confuse it with an angle of $0$ (or $2\pi$), it is a cusp at this vertices.
Comment: I don't...  I confuse it with a straight line because it is a straight line.  In particular, I can take an *analytic* curve and announce that every point on it is a vertex with angle $\pi$.  This is not a profitable announcement.
Comment: How are two segments meeting with a vertex angle of $\pi$ different from a single line segment?  (I.e., vertices of angle $\pi$ are completely superfluous.)
Comment: Hm, the angle is defined via the metric as usual, so an angle of $\pi$ means opposite direction, between the left and right velocity vectors of our piecewise smooth curve at a vertex.
Comment: Are you certain they are not taken as limits of directions approaching the vertex along each curve?
Comment: this is what i meant with left/right. if $\gamma$ is smooth on $[t_1,t_2]$ and smooth on $[t_2,t_3]$, then the angle is the angle between $\lim \gamma'(t)$ as $t\rightarrow t_2, tt_2$
Answer: The question is whether the values of $s$ on $A$ determine $Ds_p$ for all $p \in A$. Knowing  $Ds_p$ is equivalent to knowing $Ds_p (v)$ for two linearly independent $v$. Knowing $Ds_p (v)$ is equivalent to knowing $s(p + t_n v)$ for some sequence $0<t_n \to 0$.
If $p \in U$ then there is no issue - we can take an open ball around $p$ contained in $A$. If $p\in \partial A$ is not a vertex, then exactly half the vectors $v \in T_p M$ have rays $p + t v$ that stay in $A$ for some positive time, and thus the values of $s$ on $A$ easily determine $Ds_p$.
When $p$ is a vertex with turning angle $\theta$, there is a cone of vectors with angle $\pi - \theta$ with rays staying in $A$ for a bit, so as long as $\theta < \pi$ there are two linearly independent such vectors.
The issue when $\theta = \pi$ is that the values of $s$ on $A$ only determine $Ds_p (v)$ for a single direction $v$ - in every other direction there is a short time for which the rays are disjoint from $A$, and thus the behaviour of $Ds_p$ in these directions is not determined by $s|_A$. I don't have time to work out a specific example but it shouldn't be too hard.
I believe your argument using sequences rules out this possibility if you assume that $s$ is continuously differentiable.

Extension of smooth maps at a cusp


Configuração de permalink no Wordpress

Question: Tenho o seguinte link:
http://bettercallsaul.com.br/saiu-novo-teaser-de-better-call-saul/
Que leva para um post, esse post está na categoria vídeos que criei, gostaria de saber como faço para incluir a categoria no link?
Por exemplo:
http://bettercallsaul.com.br/videos/saiu-novo-teaser-de-better-call-saul/
Answer: No ADM do Wordpress vá em Configurações -> Links Permanentes e crie uma estrutura personalizada como: /%category%/%postname%/
Comment: O `category` vai pegar qual categoria? por exemplo, se no post eu marcar 3 categorias, qual será a que irá aparecer?
Answer: Felipe,
Desculpa criar uma nova resposta, mas como sou noobinho no stackoverflow pt, ainda não posso comentar.
O /%category%/%postname%/ vai pegar TODAS as categorias que você tiver atribuído ao post. É por isso que é recomendado usar uma só categoria e várias tags (caso a estrutura seja igual a essa).
No entanto, recomendo que você continue com o permalink anterior. Pois além de ser mais SEO-friendly, ele também é menos "pesado" para o servidor.
Comment: Obrigado. Uma dúvida: por padrão ele pega qual categoria? pois dessa forma ele pega apenas uma.
Comment: Geralmente, a primeira associada. :)

Configuração de permalink no Wordpress