Error configuring 2 network interfaces on the same server

Question: I'm setting up a server with 2 network interfaces each one with it's IP address.
I have 2 different programs listening on port 8080 (each one on each IP address) and I'm using iptables to redirect traffic from port 80 to 8080.
The problem is that I'm unable to actually connect to the IP address of eth1 from another computer. If I try it from the same server it works as expected but from other computer the connection times out. I'm guessing the iptables is sending all the traffic to eth0 and because there's no program listening to that IP on that interface so the connection times out but I'm not really sure how to fix it.
Here is the output of my network config:
<code>→  sudo iptables -t nat -L
Chain PREROUTING (policy ACCEPT)
target     prot opt source               destination
REDIRECT   tcp  --  anywhere             anywhere             tcp dpt:https redir ports 8443
REDIRECT   tcp  --  anywhere             anywhere             tcp dpt:http redir ports 8080

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)
target     prot opt source               destination

→  ip route
default via 172.31.16.1 dev eth0
172.31.16.0/20 dev eth0  proto kernel  scope link  src 172.31.21.84
172.31.16.0/20 dev eth1  proto kernel  scope link  src 172.31.26.28

→  route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.31.16.1     0.0.0.0         UG    0      0        0 eth0
172.31.16.0     0.0.0.0         255.255.240.0   U     0      0        0 eth0
172.31.16.0     0.0.0.0         255.255.240.0   U     0      0        0 eth1

→  ifconfig
eth0      Link encap:Ethernet  HWaddr 02:bb:c3:cc:8b:47
          inet addr:172.31.21.84  Bcast:172.31.31.255  Mask:255.255.240.0
          inet6 addr: fe80::bb:c3ff:fecc:8b47/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:9001  Metric:1
          RX packets:6300 errors:0 dropped:0 overruns:0 frame:0
          TX packets:5564 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1095572 (1.0 MB)  TX bytes:1064691 (1.0 MB)

eth1      Link encap:Ethernet  HWaddr 02:71:e7:b4:bc:52
          inet addr:172.31.26.28  Bcast:172.31.31.255  Mask:255.255.240.0
          inet6 addr: fe80::71:e7ff:feb4:bc52/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:9001  Metric:1
          RX packets:238 errors:0 dropped:0 overruns:0 frame:0
          TX packets:11 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:11236 (11.2 KB)  TX bytes:1422 (1.4 KB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:63 errors:0 dropped:0 overruns:0 frame:0
          TX packets:63 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:43236 (43.2 KB)  TX bytes:43236 (43.2 KB)
</code>
Answer: I think you need to create individual rules for the 2 NICs. I'd try something like this:
<code>$ sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
$ sudo iptables -A PREROUTING -t nat -i eth1 -p tcp --dport 80 -j REDIRECT --to-port 8080

$ sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443
$ sudo iptables -A PREROUTING -t nat -i eth1 -p tcp --dport 443 -j REDIRECT --to-port 8443
</code>
Comment: This is probably a good idea, but after the change I'm seeing the same behavior.
Comment: I'd run a `tcpdump -nnvXSs0 -i eth0 port 80` and confirm that traffic is coming in properly. Do the same for the `eth1`. I believe you also need to add INPUT rules. Something like this - `iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT`.
Comment: Ran it, and traffic is coming in for both interfaces
Answer: I had to add individual rules for iptables as slm said and also I had to use 2 lookup tables for the rules for each interface, like this:
<code>sudo ip route add default via 172.31.16.1 dev eth0 tab 1
sudo ip route add default via 172.31.16.1 dev eth1 tab 2

sudo ip rule add from 172.31.21.84/32 tab 1
sudo ip rule add from 172.31.26.28/32 tab 2
</code>


eigen vectors and linear independence

Question: I know that it is the case that if we have eigenvectors $v_1....v_r$ that correspond to distinct eigen values $λ_1....λ_r$ of an $n$ x $n$ matrix, then {$v_1....v_r$} is linearly independent.
But is is it possible to have $a_1$ linearly independent eigen vectors corresponding to $λ_1$, $a_2$ linearly independent eigen vectors corresponding to $λ_2$... $a_p$ linearly independent eigen vectors corresponding to $λ_n$, and the set of all $r$ eigenvectors where $r=a_1+a_2+...+a_p$ be linearly dependent?
For example: consider a $3x3$ matrix. Imagine we have one vector(call it $v_1$) forming a basis for the eigenspace of a one eigen value, but two vectors(call them $v_2$ and $v_3$) forming a basis for different eigen value. are we guaranteed that {$v_1,v_2,v_3$} are linearly independent?
Comment: @TitoEliatron No, the first paragraph does not explain the case they are asking about. But this independence is still a standard result in every textbook.
Comment: Yes it does. Take $r=2$. and you'll get that ANY eigenvector associated to $\lambda_1$ is independent of ANY eigenvector associated to $\lambda_2\ne\lambda_1$. In fact, is what you say in your first commnet.
Comment: No, this is not possible. Eigenvectors from distinct eigenspaces are independent.
Comment: NO. Your first paragraph gives the explanation.
Answer: Suppose  is any field. For example, it could be ℝ or ℂ.
Suppose $M$ is an n×n -matrix.
Suppose $\lambda_1, \dots, \lambda_r$ is a list of distinct eigenvalues of $M$.
Suppose:

$v_{1, 1}, \dots, v_{1, k_1}$ is a linearly independent list of eigenvectors of $M$ corresponding to $\lambda_1$.
$v_{2, 1}, \dots, v_{2, k_2}$ is a linearly independent list of eigenvectors of $M$ corresponding to $\lambda_2$.
$\vdots$
$v_{r, 1}, \dots, v_{r, k_r}$ is a linearly independent list of eigenvectors of $M$ corresponding to $\lambda_r$.

Suppose $\alpha_{1, 1}, \dots, \alpha_{1, k_1}, \alpha_{2, 1}, \dots, \alpha_{2, k_2}, \dots, \alpha_{r,1}, \dots, \alpha_{r, k_r} \in \mathbb{F}$ are scalars such that
$$(\alpha_{1, 1} v_{1,1} + \dots + \alpha_{1, k_1} v_{1, k_1}) +
  (\alpha_{2, 1} v_{2,1} + \dots + \alpha_{2, k_2} v_{2, k_2}) + \dots +
(\alpha_{r,1} v_{r,1} + \dots + \alpha_{r, k_r} v_{r, k_r}) = 0.$$
Define $u_1 = (\alpha_{1, 1} v_{1,1} + \dots + \alpha_{1, k_1} v_{1, k_1}), \dots,
u_r=(\alpha_{r,1} v_{r,1} + \dots + \alpha_{r, k_r} v_{r, k_r})$.
Clearly, $u_1$ is either the zero vector or a $\lambda_1$-eigenvector of $M$. Analagously, $u_2$ is either the zero vector or a $\lambda_2$-eigenvector of $M$. And so on for $u_3, \dots, u_r$.
By the theorem you say you know, it must be the case that for each $i \in \{1, \dots, r\}$, $u_i$ is actually the zero vector.
But then for each $i \in \{1, \dots, r\}$, all the coefficients $\alpha_{i,1}, \dots, \alpha_{i, k_i}$ must be zero, because the vectors $v_{i,1}, \dots, v_{i, k_i}$ are linearly independent.
We have shown that any linear combination of $v_{1, 1}, \dots, v_{1, k_1}, \dots, v_{r, 1}, \dots, v_{r, k_r}$ equal to zero must actually be the trivial combination (i.e., with all coefficients zero). ∎
Comment: This answer is very helpful but my one I still don't understand why "it must be the case that for each i∈{1,…,r}, ui is actually the zero vector."
Comment: @bfff $u_1, \dots, u_r$ belong to eigenspaces of distinct eigenvalues. Suppose some of them are nonzero. By the theorem OP stated, those of them which are nonzero are linearly independent. Therefore their sum can give zero only if they are actually all zero. But their sum IS zero by my assumption. Contradiction.
Answer: We claim that the set of all $r$ eigenvectors is linearly independent. The main proof ideas are already provided in the comments. For each $i=1,\dots, p$ let $v_{i1},\dots, v_{ia_i}$ be linearly independent system of eigenvectors corresponding to the eigenvalue $\lambda_i$ and  $\mu_{i1},\dots, \mu_{ia_i}$ be scalars such that $$\sum_{i=1}^p \sum_{j=1}^{a_i} \mu_{ij} v_{ij}=0.$$
For each $i$ put $v_i=\sum_{j=1}^{a_i} \mu_{ij} v_{ij}$. Then $v_i$ is an eigenvectors corresponding to $\lambda_i$ and
$$\sum_{i=1}^p v_i=\sum_{i=1}^p \sum_{j=1}^{a_i} \mu_{ij} v_{ij}=0.$$
The linear independence property formulated in the first paragraph of the question implies that $0=v_i=\sum_{j=1}^{a_i} \mu_{ij} v_{ij} $ for each $i$. Then the linear independence property formulated in the second  paragraph of the question implies that $\mu_{ij}=0$ for each $j$.

eigen vectors and linear independence


Order By not working on joined and grouped MySQL tables

Question: What I'm trying to achieve: I'm trying to build a private messaging script. The part of the script which has me confused is the displaying of messages between two users. I'd like to show the last message that has been sent between them
My problem: When I perform 3 joins within one PHP/MySQL query and then use GROUP BY and ORDER BY DESC I expect the last message of that conversation to be shown...but the first one appears instead.
My code structure: I have three MySQL tables; Users (holding user login information), Messages (holding the contents of any messages) and Conversations (holding information about who the conversation is between):
USERS table:
<code> user_id | user_name
 1       | Dave
 2       | Bill
 3       | Rob
</code>
CONVERSATIONS table:
<code> conversation_id | user_one_id | user_two_id
 1               | 1           | 2
</code>
MESSAGES table:
<code> message_id | conversation_id | sender_user_id | receiver_user_id | message
 1          | 1               | 1              | 2                | Hey how are you?
 2          | 1               | 2              | 1                | Not bad. You?
 3          | 1               | 1              | 2                | Okay
</code>
and I have the following MySQL query:
<code> SELECT u.user_name, c.conversation_id, m.sender_user_id, m.message
 FROM conversations c
 JOIN messages m ON c.conversation_id=m.conversation_id
 JOIN users u ON u.user_id=m.sender_id
 WHERE c.user_one_id=$user_id AND m.sender_user_id<>:$user_id
 GROUP BY u.user_name
 ORDER BY m.message_id DESC
</code>
The output: When I supply $user_id=2 and echo user_name and message is:
<code> Dave: Hey how are you?
</code>
as opposed to displaying the last record:
<code> Dave: okay
</code>
Answer: Using group by in absence of aggregation will result in indeterminate order it will not guarantee you the latest or earliest order you can use a self join to pick the latest message per converstion
<code>SELECT u.user_name, c.conversation_id, m.sender_user_id, m.message
 FROM conversations c
 JOIN messages m ON c.conversation_id=m.conversation_id
 JOIN users u ON u.user_id=m.sender_user_id
JOIN (select max(message_id) message_id ,conversation_id
     from messages
      group by conversation_id
     ) m1
ON(m.message_id= m1.message_id and m.conversation_id = m1.conversation_id)
 WHERE .....
 ORDER BY m.message_id DESC
</code>
Demo


Throwing and catching IOException

Question:    inputFileName = "2.txt";
   outputFileName = "3.txt";

   inputFile = new BufferedReader(new FileReader(inputFileName));
   outputFile = new PrintWriter(new FileWriter(outputFileName));

   String lineOfText = inputFile.readLine();

   while (lineOfText != null)
   {
       if (lineOfText.contains("x"))
       {
           lineOfText = lineOfText.replaceAll("x"+ ".*", "");
       }
       outputFile.println(lineOfText);
       lineOfText = inputFile.readLine();
   }

   inputFile.close();
   outputFile.close();

Hello,
right now I have an input and output, does that mean I have two try and two catch blocks (there might be an error connecting to the previous file and writing to the second file). Or would I need only one try block?
If so, how/where would I implement the try and catch blocks?
Comment: It's up to you, but it'll definitely be easier to use a single try/catch around the entire snippet.
Comment: Ah I see. if I want to use two try blocks, how would they be implemented in this code?
Comment: You would need to surround any call that throws `IOException` in a try/catch block, and either return or set some boolean flag to indicate failure once you exit the block.
Comment: I would use try-with-resources, a single block, and initiate your BR and PR within the try parenthesis.
Comment: I caught the exception, now when I use my main method it is telling me to throw or catch the exceptions. In each method of the main method I catch the exception, why do I still receive this message.
Answer: I would only use one try/catch/finally-block by writing:
try {
    inputFile = new BufferedReader(new FileReader(inputFileName));
    outputFile = new PrintWriter(new FileWriter(outputFileName));
    String lineOfText = inputFile.readLine();
    while (lineOfText != null) {
        if (lineOfText.contains("x")) {
            lineOfText = lineOfText.replaceAll("x"+ ".*", "");
        }
        outputFile.println(lineOfText);
        lineOfText = inputFile.readLine();
    }
} catch(IOException ioe) {
        System.err.println("Caught IOException: " + ioe.getMessage());
} finally {
    if(inputFile != null)
        inputFile.close();
    if(outputFile != null)
        outputFile.close();
}

By using the finally block you can be sure that the Reader and Writer object are definitely closed.
Comment: `getMessage()` doesn't return the stack trace. Use `printStackTrace()` for that. Also, you should check for null in your `finally` block, in case it failed during construction. Or see @DarshanMehta's answer for a preferable approach.
Comment: Thank you! What does getMessage() do?
Comment: Basically returns the exact stacktrace of where the exception has occurred in your code. See more at [JavaDoc](https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getMessage())
Comment: You are correct. Sorry for the misleading information.
Answer: I would recommend using try with resources block of Java 7, as shown in the example below, it will take care of closing of resources as well:
public static void main(String[] args) throws Exception {
    String inputFileName = "2.txt";
    String outputFileName = "3.txt";
    try (BufferedReader inputFile = new BufferedReader(new FileReader(inputFileName));
            PrintWriter outputFile = new PrintWriter(new FileWriter(outputFileName));) {
        String lineOfText = inputFile.readLine();

        while (lineOfText != null) {
            if (lineOfText.contains("x")) {
                lineOfText = lineOfText.replaceAll("x" + ".*", "");
            }
            outputFile.println(lineOfText);
            lineOfText = inputFile.readLine();
        }
    }catch(Exception e){
        //Handle
    }
}

Here is the documentation for try with resources.

Throwing and catching IOException


Preencher uma lista com retorno do Json

Question: Queria preencher uma textarea ou qualquer coisa que se pareça uma lista, com os ítens que o cara seleciona a partir de um dropdow. Então eu pensei assim, mas não sei como alimentar a lista...
<textarea cols="1" id="lista">

</textarea>

Comment: Todos os dados que você irá adicionar na lista são retornados de uma vez só no post, ou conforme o usuário vai selecionando, chamadas diferentes vão sendo feitas?
Answer: Não sei como está o seu json, mas se todos os dados são retornados de uma única vez você pode usar um each para percorre-lo e adicionar linha por linha na tabela value deve retornar o valor dentro do each, se for uma string você usa só o value para mostrar, caso seja um array use value["Nome"]
$(document).ready(function () {
     $('#Chamada').change(function () {
          var id = $(Chamada).val();
          var url = '@Url.Action("MusicaAdc", "Chamada")';
          $.post(url, { id: id },
          function (data) {
               $.each(data, function(index, value){
                       $('#lista').append('
"' + value["Nome"] + '
');
                });
           }
      });
});

Preencher uma lista com retorno do Json


Integral basis for totally ramified extensions of $p$-adic fields

Question: Let $L/K$ be a totally ramified extension of $p$-adic fields of degree $n$. Write $v_L$ for the normalised valuation of $L$. If $a_0,\ldots, a_{n-1}$ are elements of $L$ such that $v_L(a_i)\equiv i\pmod n$, then they form a $K$-basis of $L$. Indeed, if a linear combination
$$\sum_{i=0}^{n-1} k_ia_i=0,$$
then its valuation is $\infty$, and as for all $i\ne j$,
$$v_L(k_ia_i)\ne v_L(k_ja_j)$$
(here we use the hypothesis on the ramification), we derive that there exists $j$ with $k_j=0$.
Now suppose that $b_0,\ldots, b_{n-1}$ are elements of the valuation ring $\mathcal{O}_L$ such that $v_L(b_i)=i$. I have seen in several places that this implies that the form an $\mathcal{O}_K$-basis of $\mathcal{O}_L$, but I cannot come up with a proof. The linear independence is clear, but at integral level is not enough. How can we show that if $x\in \mathcal{O}_L$ satisfies
$$x=\sum_{i=0}^{n-1} k_ib_i,$$
then $k_i\in \mathcal{O}_K$ for all $I$? An idea could be to use that in this case $\mathcal{O}_L=\mathcal{O}_K[\pi_L]$, where $\pi_L$ is an uniformiser of $L$. Note that for all $i$ there exists a unit $u_i$ of $L$ with $\pi^i=u_i b_i$, but $u_i$ is not necessarily in $K$...
Finally, what about the fractional ideals $\mathfrak{p}_L^h$? Is is true that elements  $c_0,\ldots, c_{n-1}$ of $\mathfrak{p}_L^h$ such that $v_L(c_i)=h+i$ form an $\mathcal{O}_K$-basis of $\mathfrak{p}_L^h$?
Comment: if $i$ is such that $v(k_i)$ is smallest, and if it happens that $v(k_i)<0$, then you'll see easily that $v(x)<0$
Comment: $v(k_i)$ is a multiple of $n$, while $v(b_i)$ is between $0$ and $n-1$, so if $v(k_i)<0$ then also $v(k_i b_i)<0$. Now I supposed that $i$ is such that $v(k_i)$ is the smallest, and if there are several $i$'s with the same $v(k_i)$ pick the smallest one (i.e. th eone with the smallest $v(b_i)$), from where you then get $v(x)=v(k_i b_i)<0$
Comment: A priori, with this kind of approach, I do not see why in your hypothesis, if $v(k_jb_j)$ is the smallest, then also $v(k_j)<0$... And it seems to me that it is a required step.
Comment: Ok, I got this, thank you!
Answer: Assume $x \in \mathcal{O}_L \backslash \{0\}$ is such that $x=\sum_{i}{k_ib_i}$ is a combination with minimal support where some $k_i$ is non-integral. By minimality, then every nonzero $k_i$ is nonintegral.
Now, as in your proof, the valuations of the $k_ib_i$ with nonzero $k_i$ are pairwise distinct, so there is some $i_0$ such that the valuation of $k_{i_0}b_{i_0}$ is minimal, and thus it is equal to that of $x$. Thus the (nonnegative) valuation $v$ of $x$ is congruent mod $n$ to the valuation of $b_{i_0}$ which is $i_0 < n$, so that $v=i_0+nk$ for some $k \geq 0$, and $k$ is the $K$-valuation of $k_{i_0}$ so that $k_{i_0}$ is integral – a contradiction.
The statement for $\mathcal{O}_L$ follows. For fractional ideals, just reduce to the $\mathcal{O}_L$ case by multiplying with a generator.
Comment: Sorry, what do you mean with about "combination with minimal support"? Isn't that combination unique, as the $b_i$ form also a $K$-basis of $L$?
Comment: Indeed. Every $x \in \mathcal{O}_L$ can be written uniquely as $\sum_{i=0}^{n-1}{k_ib_i}$ with the $k_i \in K$. I denote as $s(x)$ the number of $i$ such that $k_i \neq 0$ if some $k_i$ is nonintegral, and if all $k_i$ are integral then $s(x)=0$. I then choose the $x$ such that $s(x)$ is minimal nonzero – and I show a contradiction.


SQL Error in Docker

Question: My goal is to run some commands in my Dockerfile that will create an sql user and give him some privileges. So I do the following:
FROM ubuntu:18.04
...
RUN apt-get install -y apache2
RUN apt-get install -y mysql-server
RUN mysql -Bse "CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'testpass';"
RUN mysql -Bse "GRANT ALL PRIVILEGES ON *.* TO 'testuser'@'localhost';"

This crashes at the first mysql command
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

However, if found through StackExchange that if I remove the sql commands from Dockerfile and login with docker exec in a running container, the following solution will work:
service apache2 stop
service mysql stop
service mysql start
service apache2 start
mysql -Bse "CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'testpass';"
mysql -Bse "GRANT ALL PRIVILEGES ON *.* TO 'testuser'@'localhost';"

As I want all the commands to be in the Dockerfile, I tried the above service stop/start solution, but it will not work from Dockerfile, only after exec in an already running container. I suppose a different solution is required.
How can I automate these execution of these sql commands without having to run them manually with docker exec? Thank you
P.S. let me know if the question would be more suitable for another Stack Exchange site.
Answer: The problem is related to the fact that every RUN command is running in a different layer. The solution was to add all related commands into a bash script init_db.sh file and execute it in the Dockerfile.
#!/bin/bash

service apache2 stop
service mysql stop
service mysql start
service apache2 start

mysql -Bse "CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'testpass';"
mysql -Bse "GRANT ALL PRIVILEGES ON *.* TO 'testuser'@'localhost';"

ADD init_db.sh /tmp/init_db.sh
RUN /tmp/init_db.sh

source: https://stackoverflow.com/questions/25920029/setting-up-mysql-and-importing-dump-within-dockerfile

SQL Error in Docker


Terminology-wise, how do I differentiate between a "percentage percentage" gain, and a "additive percentage" gain?

Question: Sorry if the question title is confusing - I'll explain.
I often have to provide answers like "If we did X, than Y would be P% larger."  This is fine if the units of Y are "absolute units."  For example - "If the plant is given food twice a week instead of once, its expected height after 3 months is 12% higher."
However, I never know how to phrase it when the units of Y are already percentages.  For example, say I'm measuring how many people click on an ad.  Assume that currently, 30% of people click, but if we change the ad's wording, 42% of people click.
I could say that that is a 40% increase in click rate (because 42/30 = 1.4; this is my "percentage percentage" gain).  Or, I could say that it's a 12% increase in click rate (because 42% - 30% = 12%; this is my "additive percentage" gain).
At times, I'll want to give both values, but obviously this gets very confusing.  Is there correct terminology?  Concretely:

If I wanted to say that changing the ad wording causes a 12% increase, from X% to (X+12)%, how should I say that?

If I wanted to say that changing the ad wording causes a 40% increase, from X% to (1.4 * X)%, how should I say that?

Thank you!
Answer: I think you are describing Percentages (2) and Percentage points (1).
More details here.
Comment: In symbols it would be % vs %p.
Comment: Thank you!  This was driving me crazy.  I should have thought of that!


Homomorphisms of the group of affine trasformations

Question: I'm trying to prove the following theorem.

Let $\mathrm{Aff}(n)$ define the set of transformations $T: \mathbb{R}^n \to \mathbb{R}^n$ sending $x \mapsto Ax + b$ such that $A \in \mathrm{GL}_n (\mathbb{R})$ and $b \in \mathbb{R}^n$. Prove that (a) $\psi: \mathrm{Aff}(n) \to \mathrm{GL}_n (\mathbb{R})$ sending $T \mapsto A$ is a homomorphism of groups, but that (b) $\phi: \mathrm{Aff}(n) \to \mathbb{R}^n$ sending $T \mapsto b$ is not.

My key problem in (a) is formalism. I want to act on an arbitrary element of $x$, but I can't do that because inputs to $\psi$ are elements of $\mathrm{Aff}(n)$, not of $\mathbb{R}^n$, so I need to do the casework "outside" of the main equation chain, since it doesnt make sense for me to write $\psi((T_1 \circ T_2)(x))$ or $\varphi(T_1)(x)$. With that said, here is my attempt that I believe to be insufficiently formal.

Let $T_i \in \mathrm{Aff}(n)$ sending $x \longmapsto A_i x + b_i$ for $1 \leq i \leq n$. For any $x \in \mathbb{R}^n$, we h ave
\begin{align*}
(T_1 \circ T_2)(x) & = T_1(T_2 (x)) \\
& = T_1 (A_2 x + b_2) \\
& = A_1 (A_2 x + b_2) + b_1 \\
& = (A_1 A_2)x + (A_1 b_2 + b_1)
\end{align*}
So
\begin{align*}
\psi(T_1 T_2) = A_1 A_2 = \psi(T_1) \psi(T_2).
\end{align*}

The problem, again, is that I can't define the output of $\psi$ without referring to $x$.

I'm less sure on part (b), so this is more scratchwork than much else. Take $T_1, T_2$ defined as above. Then, using the above work, we get:
\begin{align*}
\phi(T_1 T_2) & = A_1 b_2 + b_1 \\
\phi(T_1) + \phi(T_2) & = b_1 + b_2
\end{align*}
But $A_1 b_2 + b_1 \neq b_1 + b_2$ in general. Indeed, we have:
\begin{align*}
A_1 b_2 + b_1 = b_1 + b_2 & \iff A_1 b_2 = b_2 \iff A_1 = I.
\end{align*}
So specifying $T_1$ with any $A_1 \neq I$ gives a counterexample.

This is not an explicit counterexample and I don't quite know how to construct one for every $n \in \mathbb{N}$.
Comment: For a group homomorphism $\psi\colon G\rightarrow H$ you also need to show that $G$ and $H$ are groups. Since you only know that ${\rm Aff}(n)$ is the **set** of affine transformations, you should show that it forms a group. The title was misleading here, so I changed it. You can change it back of course.
Answer: If I understand you correctly, you struggle to show that $\psi$ satifsies the homomorphism property
$$\phi (T \circ S) =\phi(T) \phi(S)$$
Suppose $T(x) = Ax + a$ and $S(x) = Bx + b$. We have
$$(T \circ S)(x) = T(Bx + b) = A(Bx+b)+a = (AB)x + (Ab + a)$$
Hence, $\psi(T \circ S) = A B = \psi(T) \psi(S)$.
Now, you see from the computation above why $\phi$ is not a homomorphism. Since
$$\phi(T \circ S) = Ab + a,$$
which in general does not equal $\phi(T) + \phi(S) = a + b$.
We give the following counter example: Let $T$ and $S$ be given by
\begin{align}
T(x) &= \begin{bmatrix}
0 & 0 \\
1 & 0 \end{bmatrix} x + \begin{bmatrix}
1 \\
0 \end{bmatrix} \\
S(x) &= \begin{bmatrix}
1 & 0 \\
0 & 0 \end{bmatrix} x + \begin{bmatrix}
1 \\
2 \end{bmatrix}
\end{align}
A simple computation shows that
$$(T \circ S)(x) = \begin{bmatrix}
0 & 0 \\
1 & 0 \end{bmatrix}x + \begin{bmatrix}
1 \\
1 \end{bmatrix}$$.
Hence, $\phi(T \circ S) = (1,1)^\top$, whereas $\phi(T) + \phi(S) = (1,0)^\top + (1,2)^\top = (2,2)^\top$.
Comment: There was a typo in part (b). I meant to say that $\phi$ maps into $\mathbb{R}^n$. Thank you for catching that.
Comment: No problem. I have edited my answer to explain why $\phi$ is not a homomorphism into $\mathbb{R}^n$.
Comment: It makes sense to me that $Ab + a \neq a + b$ in general, but I'm trying to find a canonical counterexample. Is it correct to say that $Ab + a = a + b$ if and only if $A = I$?
Comment: Not necessarily, $A$ may be a matrix with $b$ as an eigenvector with eigenvalue $1$. However, it is not difficult to find a counterexample in the case $n=2$. Try matrices with a lot of zeros and let the $a$ and $b$ not resemble each other too much.
Comment: Hmm, but this statement has to work for any $b \in \mathbb{R}^n$, then then we would have $b$ is an eigenvector of $A$ with eigenvalue $1$ for all $b$, so it must be a multiple of the identity matrix. So anything not of that form (e.g., an $n \times n$ rotation matrix, which is surely invertible) would work as a counterexample. Is that right?
Comment: I have now given a concrete counter example in the answer. If every vector is an eigenvector, the matrix is of course the identity, but that is not the point. The point is that there will be affine transformations for which $\phi(T \circ S) = \phi(T) + \phi(S)$, but it will not be true in general.


Inserir caracteres especiais em mysql e puxar esses valores idênticos na aplicação web

Question: Boa noite, Preciso adicionar valores ao banco de dados pelo mysql de forma que eles possuam caracteres especiais. Eu consigo adicionar, mas não consigo puxar os valores corretamente, eles acabam que vindo com símbolos no lugar dos caracteres especiais, por exemplo...
Informática
Inform�tica
Comment: Os dois charset estão iguais. Mas mesmo assim o problema persiste.
Comment: Da uma olhada na resposta da pergunta linkada no comentário, lá fala a respeito disso e mostra varias soluções.
Answer:
Certifique-se de que no banco de dados os valores estão corretos (com acentuação).
Você não especificou qual linguagem está usando, porém pelas tags acredito que seja PHP. Configure o charset das páginas corretamente. Ex:
header('Content-type: text/html; charset=ISO-8859-1');
Comment: Sim, sim php. O charset está correto.
Comment: Qual charset está usando?
Comment: Estou usando UTF-8
Comment: Altere para ISO-8859-1
Comment: Okay, deu certo, mas agora a página toda está vindo com simbolos diferente.
Answer: Consegui resolver da seguinte forma, Obrigado Fabiano Lira, Gato.
mysql_set_charset("utf8");


Hibernate @Formula for timestamp to date conversion in order by

Question: I already solved this but I didn't have much success just searching for what was my final solution and well maybe there is more than 1 way to do this but I wanted to share what I came up with and maybe it will be of some use.
My problem was with Hibernate I was performing a query that has paging and the result set needed to be sorted in a particular order. The sort was to use record creation date but that is a time stamp down to the millisecond and we wanted the day month year to be equivalent The timestamps could have been hours apart or a few milliseconds but if they were both on June 5 2000 they should be treated as equal. I found a lot of information on how to extract year month or day from a date but not actually do a conversion. How do I do this then?
Comment: JPA has no such `@Formula`, so suggest that you fix your title
Comment: confused by your comment. Title says 'Hibernate @Formula.... ' .    The import statement is: import org.hibernate.annotations.Formula;   You're mentioning JPA.
Comment: You had the title as "JPA @Formula", I asked you to change it. Nothing happened, so I changed it myself.
Answer: This ends up being a calculated field basically so in comes the @Formula annotation. I had discovered in SQL server the convert function which did what I wanted. Getting it into the Formula there was a bit of a trick. I came up with this:
<code>@Formula("convert( \"date\", Date_Time_Created ) ")
</code>
putting in date by itself ending up date being treated as member variable, just doing single quotes 'date' literally went to SQL as 'date', but adding the double quotes as being escaped resulted in "date" in the sql but that worked.


Should I practice minor scales by knowing relative major?

Question: Just doing some practice on minor scales. When I play minor scales, should I just know off the top of my head what the relative major scale is and then play the notes, or should I see the minor scale as its own scale pattern (ie W, H, W, W, H, W, W) and not even think about the relative major?
Note: I'm mainly focusing on natural minor.
Comment: You can also view scales by their **tetrachord** components. The first sheet of [this PDF (that will download when you click this link)](https://www.learnjazzstandards.com/wp-content/uploads/chord_charts/Using_Tetrachords_Make_Scales.pdf) defines the "minor" and "phrygian" tetrachords, then shows (at the bottom) that the natural minor is "minor + phrygian".
Answer: You don't practice scales in a spirit of harmonic analysis.  You practice them to gain fluency.   Work out the notes any way you want.  Then get them fast and clean!
Comment: We seem to spend a lot of time on this forum reminding less experienced players that although a scale defines a tonality, no special permission is needed to use notes and chords that aren't in the scale!  Perhaps if they read and played more existing music before jumping headlong into improvisation...
Comment: @LaurencePayne Honestly though, if our little site helps curious musicians jump out of the "paint by numbers and oh yeah learn some songs I guess" approach to understanding music theory far too prevalent on the internet, then it's already doing a lot of good.  Also, answerers tend to do it in a really positive way, and the OPs usually respond pretty well, so even if sometimes it can be a little repetitive I don't mind at all :)
Comment: Scales are wonderful! My point was that they are the framework of a tonality, not a restriction.
Comment: I did that for years to pass exams. It was only when I reached a point teaching that I realised that a vast majority of pieces in a certain key used the notes from the scale in that key. What a difference! Bit like 56 is in the 7x table, but 58 isn't.
Comment: @LaurencePayne perhaps, perhaps, perhaps
Comment: @Some_Guy - I agree, I think. Too many budding guitarists use the tab that's readily available to 'learn to play', but all they do is regurgitate those few songs - in the manner someone else dictates. Surely that's not understanding, thus being able to transfer musical skills. That's what I like about this site - most people try to help the OPs understand what's going on. And I still reckon that knowing scales is important to any player,and actually, despite what Laurence says, there's a heck of a lot of tunes out there that actually use those diatonic notes, so scales are useful - my opinion.
Answer: The minor scale you're considering is the natural minor, also known as Aeolian mode and descending classical melodic minor.
Of course it's better to think along the lines of its relative major, which is already known. In itself, it's used often while a piece is in a major key, to modulate into, seamlessly.
The other minors - harmonic and melodic - use some changed notes, which again can be seen to be related to other scales.
The harmonic only changes the leading note from the natural, so there's a semitone between the 7th and 8th notes. That gives a tone and a half gap between 6 and 7, which is 'compensated' for in the rising classical melodic, by also raising the 6th note. But if you know the natural and harmonic minor scales, it's just a matter of adapting the changed notes, which should make more sense than thinking along the lines of 'it's a completely new set of notes' - which it isn't.
You could also have the same mindset with modes, which use the same notes again as the major scale, but start and finish on other notes rather than the major root. As in D Dorian is an 'extension' of C major.
Comment: @Stinkfoot from a purely pedagogical standpoint, it's easier to teach major first, simply because songs in minor keys generally deviate more from the scale notes than those in major keys do. Perhaps that contributes. I suppose that the major chord is the most fundamental chord in the harmonic series has something to do with it as well (the major third is the sixth overtone, while the minor third is the 19th): I can't imagine using a bugle to teach minor chords.
Comment: _Of course it's better to think along the lines of its relative major, which is already known_ - If you've been weaned on jazz, blues and certain types of rock music, (like I was) IMO that's not necessarily so at all. Minor modes come much more naturally to me than major - my ear is far more accustomed to music that "leans minor", as is my playing style. I have to think more about what I'm playing when I have to stick to major chords and harmony - liberal use of _bIII's_ , _bVII's_ and dominants in tonic chords is my natural style of playing.
Comment: @Stinkfoot - fair enough, and three hundred or so years ago, music *was* minor lead. Now, everything is considered from the major datum point - when we say something's in Eb, no-one questions maj. or min., it's a given.I'm answering the question with the OP's experience - or lack of it - in mind. Most tend to learn maj. stuff first, then realise that the natural min. includes the same notes.Quite possibly guitarists will know min. pents and blues before anything else, but the OP quoted piano.One ought to be at home equally in maj. min. and all modes, to encompass all sorts of music effectively
Comment: _Now, everything is considered from the major datum point_ : Yes an outdated "vestigal" POV encouraged by poor music education at the elementary levels. Today do more people identify with the tunes  and harmonies of the Beatles, the Stones, BB King, Eric Clapton, Jimi Hendrix, Motown etc etc etc or with the tunes and harmonies of Mozart and Haydn?
Comment: @Stinkfoot - a good question! And one where 'it depends who one asks'. If it's people queuing for the Berlin Phil., the answers going to be somewhat different from that of those queuing for a Stones concert...And, to be fair, a lot of the tunes and harmonies from the Beatles, et al, have been orchestrated, and still sound good, as they may have been written by 'classical' composers. But we digress too much...
Comment: _I suppose that the major chord is the most fundamental chord in the harmonic series has something to do with it as well_ - No denying that there are good reasons why Ionian/Major is the "parent mode" with respect to others. The question is why single out Aeolian as "the relative minor". Dorian, for example, is a much more commonly used "relative minor", built on the second scale degree, than is Aeolian.
Answer: Yes, I think it is useful to know the relative major when practicing the minor scale, and not think of each scale as a separate pattern.
I have found that students do well when they begin to see the overall pattern of whole and half steps in the system, and and realize that the scale is determined by which tone in the pattern they are focusing on.
I think that understanding Modes becomes easier for some students when taking this approach as well.
Comment: @Stinkfoot - I know what you're saying, but doing it that way means in effect, seven *more* patterns to learn - when actually you already know them - from a different point of view. I find students understand modes as maj. scale notes from a different start point/home far easier and quicker. Instant success is often more effective than ' go home and learn this new pattern' which isn't new at all.
Comment: @Stinkfoot I'm not sure why students have difficulty with the concept, but there is often confusion in the beginning about how it is one pattern and the tonic changes the relative position of the half steps, even when demonstrating on the piano.  Usually I see an "ah ha" moment in the student after they have been playing relative maj/min enough times and the pattern becomes clear to them.
Comment: _I think that understanding Modes becomes easier for some students..._ I have never understood why understanding modes should be difficult for anyone, or why it's necessary to use such a crutch to introduce modes. Just go to the piano and play an octave on the white keys, starting with C (or maybe even A...) and moving through, starting on the next key each time and naming the mode: You have now perfectly illustrated the concept of modes in what I think is a very simple and comprehensible way.
Comment: @Tim - certainly you need a base mode. But my point is it's not really 6 new patterns - it's just one series, starting at different points. If you know the layout of the "base series" it's not really hard to count off from any given point in the series. It's an algorithmic approach - really uses intevals and numbers as opposed to letters.
Answer: You should know the connection between the minor scale you're playing and its relative major, but treat them as different. Since you are mainly focusing on natural minor the two might seem like the same thing, but the most common type of minor, harmonic minor, and also melodic minor are definitely different.
Answer: I agree with @LaurencePayne 's answer:

You don't practice scales in a spirit of harmonic analysis. You practice them to gain fluency. Work out the notes any way you want. Then get them fast and clean!

( Personally, I used an algorithmic/modal approach to scales and thought of variations as exceptions to the standard algorithms - there is already plenty of terminology out there to help - terms like Lydian Dominant or Locrian #2 or the Altered Scale. Eventually, the common ones became automatic. I'm not a full time pro - often enough I have think about things as I play, if it's not something commonplace. )

But I'll add this:
I don't think of natural minor as the relative minor of its major scale. I think that puts too much emphasis on the very conventional and not particularly relevant "Major vs Minor" mindset, which in modern music has been obliterated, IMO.
I think of natural minor simply as the 6th mode - Aeolian - the mode built on the 6th degree - of the Ionian "base" mode, known commonly as "The Major Scale": IMO, in modern music it's valid say that "all modes are equal", (although having a base mode still puts emphasis on major and there are good reasons for that) and we also find many scales in use - harmonic and melodic minor, various pentatonic scales, bebop scales... -  that aren't modes or relative major or minor to anything. (And what's without touching on other systems that are also becoming part of our musical vocabulary - Indian music for example.) In fact, the natural minor, Aeolian mode, occurs infrequently relative to those others.
So - why bind yourself to the "Major vs Minor" mindset implied by Major and Relative Minor, or vice-versa? It's not the correct way to think about contemporary music.
Comment: Aeolian shouldn't have been quoted, although it's only one note different from the oft used harmonic minor. And, let's face it, a vast majority of pieces use extra notes that aren't diatonic anyway, so it's not a simple matter to decide *exactly* what key/scale notes a piece uses.
Comment: 'All modes are equal' - except Ionian and Aeolian, which make up a heck of a lot of music, and Locrian, which seems to hardly work at all - for player and listener!
Comment: @Tim -  Aeolian? Where and when? Please elaborate... Dorian and Mixo are far more common in rock and and blues/rock, metal, etc,  AFAIK Dorian is "default minor" in jazz parlance. Lydian dominant, bebop scales and all sorts of altered scales are also well used in jazz from what I've seen (not all that much admittedly.)  - more than straight Aeolian. Where do you find straight Aeolian? 10th century plain chants?
Comment: _it's only one note different..._ And a tritone is "only one note different" than P5. :)
Answer: While it is useful to know the relationships between relative major and minor keys, your fingers don't care. I would not recommend that you use the same fingers on the same keys as you do on the relative major, starting a minor third lower, for your minor scales. (If that is what you are asking.) Minor scales have their usual fingerings, just as major scales do. Also, as others have said, the natural minor scale isn't the only one.
Most people practice the harmonic and melodic minor scales, as these often come up in music. The harmonic minor scale raises the 7th degree a half step to provide a leading tone. The melodic minor scale raises the 6th and 7th scale degrees a half step going up, and drops them again (uses the natural minor scale) going down.
If you want to see the usual fingerings of all the scales, you can find them here, starting on page 50.
Answer: Old post, but...

Just doing some practice on minor scales...Note: I'm mainly focusing on natural minor.

This is probably the more important point, rather than relative major/minor scales.
In terms of the major/minor system of harmony, there really isn't any music in a key of "natural minor." So practicing only natural minor will not adequately help prepare you for playing in minor keys.
You should practice scales with a sense of minor key harmony and use the various forms of raised/lowered ^6 and ^7 scale degrees, which will give you the various natural, harmonic, and melodic minor scales.
That will better reflect how minor scales are actually found in minor key music.
Getting back to the question of relative keys/scales. If the idea was that somehow knowing a major scale made playing the relative minor scale already covered by practicing major scales, you should see the mistake in that idea. In other words, something like: "I know how to play C major, so that means I already know how to play A minor, because all the pitches are the same." That's wrong.
Minor key music, minor key scales, don't work that way. You will need to learn to handle the ^6 and ^7 scale degrees flexibly. In the case of C major/A minor that will be the F and G natural changing to F♯ and G♯.
Answer: As an ultimate goal, we want to be able to think "I want to play an Fm scale" and the scale should be right under our fingers. We think "Let me play some notes of a Bbm scale now" and immediately our hand plays the right notes in any order. However, although a Bbm scale is a scale "derived" from the Db major scale, it has emphasis placed on Bb (and the other notes from Bb chord) and not on Db (This is part of the ingredients of a scale: a center of tonal gravity + a formula for subsequent notes. The first concept is not easily understood right away by beginners). So, when you think about the Bbm scale, your hand should visualize "Bb related notes" and if you need to make the brief mathematical analysis "What is the major scale from which Bbm is derived? Hm, it's Db. Ok, let me play the notes of Db but emphasizing the Bbm chord", then there is an unnecessary wasting of brain power.
Let me quote Gary Burton in a MOOC Berklee Coursera course (if you change Bm7b5 for Am, that's your question):
"Often students will ask this question about the seven modes: Since the same notes are used for seven mode scales (the B Locrian uses the same notes as the C Ionian, and so on), can we just think of the C Ionian, a more familiar scale, when we see a Bm7b5 chord symbol?
The answer is no. The reason the chord symbol is spelled as a Bm7b5 instead of a C major is to point us to the strongest notes, the chord tones, of the B minor harmony. The chord symbol is telling us more information than just the notes in the scale.
If the symbol says B minor something, then you will want to picture it, and think of it as B minor. If you have to first think of it as C major to find the scale notes, it creates an extra step in your thought process and distracts you from focusing on the important notes in the B minor harmony."
As an intermediate step, I am a proponent of learning 2 worlds that will serve as a basis for all basic structures: major and minor worlds. If you learn the G major scale, immediately learn Em and associate Em with the same key signature, although as a separate entity. Don't think of Em as a E scale with b3,b6,b7 and also don't use this kind of half-whole formulas (it's cumbersome if you want to skip notes). The idea of keeping these 2 scales in mind has the benefit of learning easily lots of other scales, changing just a few notes. If you want to practice the dorian scale, start with a minor scale and raise the 6th degree. If you want to practice the lydian scale, start with a major scale and raise the 4th degree. Most scales will be categorized as a part of the "minor world" or "major world". You can use a more fine-grained categorization and add the "diminished world", "dominant world", etc ... but now I digress :p
Answer: It is a good technique to know the minor scales fast but I reccommend you to really know the minor. It will be a lot harder and much more time to take but I think it would benifit you more if you know the relative but sticking more to the traditional way. You could combine them both, though. Anyway that is just my opinion. Do what you feel would suit you more and help you when it comes to music.


How can you tell what note someone is singing?

Question: As someone who sings for fun, how do you guys tell what note someone is singing? The reason I'm asking this is because with an instrument, you can easily tell as long as you memorize that note; however, in singing, each voice has a distinct color. So how can we tell? I can tell the relative position of notes to each other but that's it.
Comment: When someone asks me what note, the reply is 'the right one'...
Comment: @Tim - I hope you don't teach kids then.
Comment: @chasly-supportsMonica - why?
Comment: Why do you need to know the note?  For example, if you hear someone singing a song, you sing the same notes you hear.  Why do you care whether any given note is an E or an F?  If you're singing "for fun," it doesn't matter in the least.  Checking with a tuner seems contrary to the idea of doing it "for fun" unless you like playing with electronic gadgets.
Comment: Cause I'm OCD. When I commit to something, I like to do the best that I can; that for me is "fun". It's also easier to become better at something when you put in more effort. Simply singing, without any knowledge, is a waste of effort imo. Why put in more work and get less out?  The fun part is digging deeper into the art itself.
Comment: Ok, but how far do you take that?  You post on this site: do you know the character code for each letter?  Do you know the networking protocols used to send them back and forth?  Do you know the history of each letter's form and phonetic value?  Do you care whether the tonic pitch of your song is precisely 440 Hz or 370 Hz?  Why not 423.79 Hz or 380.41 Hz?  What does it matter whether 275 Hz is C sharp or D?  People made music for millennia without being able to quantify frequency; doing so has only been possible for the last two centuries or so.
Comment: You take it as far as you are comfortable with? We see this all the time in hobbies; some barely scratch the surface and are happy, while others become incredibly good; it's what ever makes "you" happy. Fun doesn't necessarily equate effortlessness. For example, many people spend years of their lives learning languages; I, my myself, learned to read a language, so I can read their web novels. Is it necessary? No, but its fun. I think most of us set goals for ourselves before we set out to do something because learning is a lifelong thing.
Answer: The "what note" question has at least two different dimensions to it: absolute and relative pitch. For simply singing the same notes you're hearing, you don't need to know either of these.
What absolute note am I hearing
You need to know the absolute named pitch in the following situations:

If you need to play the exact same note or accompanying notes on an instrument.
If you need to write a transcription of the notes.

And that's about it. I can't think of other reasons why you'd need to know the absolute pitch. For singing you don't need to know it, because most people can sing the same note they hear - perhaps in a different octave - and for the few who can't, knowing the absolute note name won't help their inability in any way.
How to identify the absolute pitch?

(A) You have perfect pitch,
(B) you play a reference tone on an instrument with known pitches and compare the note you hear to the known reference tone, or
(C) you use a tuner device that has a pitch display.

Playing a reference tone is like calibrating a tuner. People who have perfect pitch have a fixed factory A=440Hz reference built in the "tuner" in their head so they don't need to calibrate. But for everyone else, they have to first calibrate their tuner to a known fixed reference tone. If the reference tone is wrong, their pitch identification will be wrong too.
What relative note am I hearing
Relative pitch means, what is the heard note relative to a pitch (or chord) or scale, real or imagined. For me, this is much more useful for singing, because I can imagine the notes I hear on an instrument and "play" the notes as I'm singing. Maybe someone likes to see the notes on a music staff in their minds, but I don't do that. But anyway, knowing the relative pitch I can sing backing vocals by imagining intervals relative to the melody I'm hearing, and it doesn't matter if my imagined key is absolutely correct or not. And I can accompany the melody on instruments, floating in the stream of incoming notes, even if the instrument is randomly transposed or if a guitar has a capo somewhere.
Comment: @NickMatteo That would only include people who are *professional* musicians, i.e. people who list "musician" as their primary source of income.  The actual number of musicians is probably much higher.  I'm a computer programmer, but I play the piano (reasonably well, though not well enough to make a career out of it), does that make me a musician?
Comment: @J... No, it's way simpler than that. If it's claimed that 0.05% of all people have it, and yet 5% of musicians have it, by sheer arithmetic the number of musicians cannot be more than 1% of all people, **and** that still requires that *every single person with perfect pitch becomes a musician*. That is defying common sense. If the supported stats say multiple % of musicians have it, there's no way it's 1-in-1000+ in the general population.
Comment: Worth noting that in the general population, only about 0.05% of people have perfect pitch.  Among musicians estimates range somewhere between 1-10%.  Way more musicians have perfect pitch compared to the general public, but it's still quite a rare ability.  The vast majority of musicians still need a reference or a tuner.
Comment: I contest something as extreme as "1 in 2000", which is rarer than many genetic disorders like [Down syndrome](https://www.cdc.gov/ncbddd/birthdefects/downsyndrome.html). Besides, a 100-fold increase in musicians again defies common sense - are musicians 1 in 100 themselves? [A proportion of 1 in 10,000 is widely reported, but not supported by evidence](https://en.wikipedia.org/wiki/Absolute_pitch#cite_note-Bachem,_1955-5) according to the wiki summary. Additional pro-western non-tonal language country bias at work here.
Comment: @obscurans Whatever the number, the point is that it's small.  As for the defying of common sense, I think that only applies if you're willing to make the assumption that perfect pitch is strictly genetic (I don't think evidence supports this).  Nevertheless, amongst musicians the number is quite well known, so even if by training some minority of people can develop perfect pitch, the overwhelming majority of the rest of us just slog through with tuners and pitch references.  The point is that OP should not feel disadvantaged for not having perfect pitch - it's quite normal.
Comment: @obscurans We understand the finer points of arithmetic and the incomplete nature of disparate scraps of research data that constitute the supporting evidence for that sentence.  I would have added the (significant) uncertainty terms in the numbers of my comment above had I known this would inspire such irrelevant pedantry, but it is **not at all important to the point**, which is that, no matter which study you look at, even the highest reported numbers that you see in any of the sampled populations are *small*.
Comment: @obscurans: I'd expect the percentage of musicians to be way less than 1%. Why would you think otherwise? According the the [Bureau of Labor Statistics](https://www.bls.gov/oes/current/oes272042.htm), there are 41,130 musicians and singers in the US, which is 0.012% of the population.
Comment: @J... if that was your true point, then you would **not** have needed to repeat a baseless sensational claim about "0.05%", and stuck to "the highest reported numbers in any population, including musicians themselves, are small". "Pedantry" is not a defense against peddling clickbait. You made the claim, you're being challenged.
Comment: @obscurans I've made my point.  I think John Cleese offers arguments at an hourly rate if you're looking for a fight...
Answer: If you have perfect pitch you "just know". This is a skill partly inherent, partly trained.
If you don't have perfect pitch, then you find an instrument & play notes until you find the matching one, then you know because you know the name of that note on the instrument.
If you're just singing along & don't need to actually name the note, then it often doesn't matter what it's called, so long as you can hear it & reproduce it accurately…. 'playing by ear'.
Comment: Knowing what the note is called & 'feeling' what note to sing are two different skills. You don't actually need the first to be able to do the second.
Comment: As I'm still new to this, a lot of time I still need a tuner to help me know what note I'm and the artist is on. So knowing the note would make my life a lot easier-). I'm still working on the producing it by ear part as I tend to have trouble with the starting notes.
Answer: How do you 'memorise a note' played by an instrument?  You mean 'it's this fingering, so it's this note'?  Well yes, that works, to a point!
You listen.  You'll need a reference pitch - 'perfect pitch' is a rare skill, not something you can reasonably expect to develop.  A tuner or a keyboard instrument will let you put a name to a pitch, but that isn't all that important.  What you probably need is not the knowledge 'That's an A' but the technique to imitate it with your own voice.
If you have the notated music to a song and it starts on (say) A, use an instrument or a tuner to show you an A.
Comment: You can memorize instrument notes! I've played the violin enough to recognize what sound a note is. Same with the 440 A from a tuner. Maybe it's practice, maybe it's (very limited) perfect pitch.
Answer: Often times the main melody notes of a song are chord tones (roots, 3rd's and 5th's) of the underlying chord progression.  So if you play a piano or guitar along with the song as you sing it and are trying to figure out what note you're singing, if you start by just checking the chord tones of the current chord you're playing you're going to find it very quickly most of the time.  I do this all the time with new songs I'm learning from chord charts online.  I've been playing music most of my life, but only started singing 2 years ago, and this was a big ah-ha moment for me when I realized it.  I mean I guess it seems obvious when you think about it, but it seemed like magic to me when I figured it out, and it still does :)


Comparing Worksheet name in vba excel

Question: I'm trying to compare a name with worksheets that already exist to see if it has been created or not yet.
Private Sub Workbook_Open()
    Dim Ldate As String
    Dim Lweekday As Integer
    Dim Newweek As String
    Dim Sname As String

    Ldate = Date
    Lweekday = Weekday(Ldate)

    If Lweekday = 1 Then
        Newweek = DateAdd("d", 3, Ldate)
        Sname = Month(Newweek) & "-" & Day(Newweek) & "-" & Year(Newweek)
        Sheets.Add.Name = Sname
        Application.CutCopyMode = False
        Worksheets("Template").Select
        Range("A1:A2").Copy
        Worksheets(Sname).Select
        Range("A1").PasteSpecial
        Application.CutCopyMode = False

     End If
End Sub

Basically I want to check if the worksheet has been created and if it has then exit the code, if not then copy and paste a template in the worksheet.
Answer: You can simply add a function to check that.
Private Function IsWorksheetExist(sName As String) As Boolean
    Dim oWS As Worksheet
    On Error Resume Next
    Set oWS = ThisWorkbook.Worksheets(sName)
    If oWS Is Nothing Then
        IsWorksheetExist = False
    Else
        IsWorksheetExist = True
    End If
    On Error GoTo 0
End Function

Comparing Worksheet name in vba excel


Rails model validation with files

Question: I have been stuck on a particular part of my website-to-be for a few days and have been getting quite frustrated. I have code to upload a logo for a user (code below) inside the logo= setter in the user's activerecord model, but this prevents me from using the model's validations. Is there a way for me to rearrange the following code so it is both "pretty" and allows me to use model validations?
Thanks
models/developer.rb
require 'fileutils'

class Developer < ActiveRecord::Base
 has_many :games
 has_many :user_associations
 has_many :users, :through=>:user_associations

 validates_uniqueness_of :name
 validates_length_of :name, :in=>4...16
 #validates_filesize_of :logo, :in=>1.kilobytes..100.kilobytes, :message=>'Logo must be between 1 and 100 kilobytes'

 def logo
   @logo
 end

 def logo=(file)
   errors.add_to_base('Image should be a PNG, JPEG or GIF file') and return if !(['.gif', '.jpg', '.jpeg', '.png'].include? File.extname(file.original_filename).downcase)
  logo_format=File.extname(file.original_filename).downcase
  image_path=RAILS_ROOT+'/logos/'+to_param
  @logo=file.path
  FileUtils.mv(file.path, image_path)
 end

 def self.fetch(id)
   Developer.find_by_name(id.gsub(/_/, ' '))
 end

  def to_param
    return name.gsub(/[ ]/, '_').downcase;
  end

end

controllers/developer_controller.rb (the relevant bits)
class DeveloperController < ApplicationController
  before_filter :load_developer

  def index
   redirect_to :controller=>'developers', :action=>'list' if params[:id].nil?
 end

 def manage
 end

 def set_logo
  if request.post? and !params[:logo].nil?
   @active_developer.logo=params[:logo]
   @write=@active_developer.logo
   @active_developer.save
  end
 end

private

  def load_developer
    if !params[:id].nil?
      @active_developer=Developer.fetch params[:id]
   else
     @active_developer=nil
   end
 end

end

Answer: You may have some of the concepts confused.  As tadman mentioned above, an existing plugin is probably the best way to go, attachment_fu is another good one to try.  If you do decide to roll your own, you usually:

Save the uploaded file to a temp file
Remember to have :html => { :multipart => true } on your form
Create an attribute in the model (that's not associated with a database field) to hold the uploaded file data (name/temp file location)
Use after_validation :save_file_attachment (which runs after validation) to move the file to the right location, place the file name into the logo attribute.

Just some ideas, I hope that helps somewhat.  Unless this is a learning exercise, go with a plugin :)
Comment: Thanks, you're brilliant, I love you :D after_validation is exactly what I was looking for!
Answer: Instead of rolling your own attachment system, you might want to use a more robust one such as Paperclip which does all of this for you. There are methods to validate the type of file, the size, and many other things, as well as preparing thumbnails for you should that sort of thing be required.

Rails model validation with files


Is it possible to add a slider without any object with Dat.gui?

Question: I would like to have a shortcut for:
gui.add({zoom: 5}, 'zoom', 10, 200).name('Zoom').onChange(onChange)

something like:
gui.add(sliderType, name, min, max, onChange)

to handle the very common situations where I don't have any object to build the slider. On the opposite, I want to build new objects from the values of the sliders in my GUI.
For example, in a drawing app, the user needs to choose the parameters of the object he wants to draw/add, then he clicks to add it, and finally he wants to modify it by changing the sliders. This means that there is no object to build the slider, but all selected objects will be modified by the GUI on onChange events.
What is the best way to handle this?
Answer: Just use a JS object (POJO) as a go between to create and modify objects.
You don't always need to have a direct 1-1 relationship with the objects in the GUI and properties of objects in your application.
var objectProps = {x:0, y:0, radius:50};

GUI.add(objectProps, 'x', ...).onChange(changeSelected); //add sliders
...

function changeSelected() {
  //loop objects
  if (object.selected) //change props based on current values of objectProps
}

function createObject() {
  //use current values of objectProps as default props for new object
}

Comment: It is nothing I did not know already, but I did upvote your answer, thank you!
Comment: @mattdlockyer why do you bring up JSON? Don't you just mean a js object?


JOptionPane em primeiro plano

Question: Tenho uma app que usa um JOptionPane para mostrar uma mensagem de erro, porém eu gostaria que o JOptionPane sempre aparecesse em primeiro plano.
JOptionPane.showMessageDialog(null, "Usuário ou senha incorreto!", "Erro", JOptionPane.ERROR_MESSAGE);

Vi algo com trocar o null pelo this no primeiro parâmetro do Dialog, porém não funcionou.
Answer: Olá, pelo que vi a sintaxe está errado.
Teste o código abaixo:
JOptionPane.showMessageDialog(null, //frame de referêcia
    "Usuário ou senha incorreto!",  //mensagem para o usuario
    "Inane error",                  //icone de erro pode deixar em branco ou null se não quiser usá-lo
    JOptionPane.ERROR_MESSAGE);     //tipo de mensagem

Clique aqui para ir até a documentação do showMessageDialog().
Answer: Olá corrigindo uma pequena informação do colega:
    JOptionPane.showMessageDialog(null, //Qualquer Componente nao so Frame
    "Usuário ou senha incorreto!",  //mensagem para o usuario
    "Inane error",                  //icone de erro pode deixar em branco ou null se não quiser usá-lo
    JOptionPane.ERROR_MESSAGE);     //tipo de mensagem

Um pequeno exemplo de código ,no qual, sem fechar o JOptionPane é impossível clicar os outros componentes no Frame.
    JFrame frame = new JFrame("teste");
    JPanel painel = new JPanel(new GridLayout(2, 2));
    JButton button1 = new JButton("01");
    JButton button2 = new JButton("02");
    JButton button3 = new JButton("03");
    JButton button4 = new JButton("04");
    button1.addActionListener((ActionEvent e) -> {
        JOptionPane.showMessageDialog(button1, e.getActionCommand(),
    "Titulo: Mensagem Informação ",JOptionPane.INFORMATION_MESSAGE);
    });
    button2.addActionListener((ActionEvent e) -> {
        JOptionPane.showMessageDialog(button2, e.getActionCommand(),
    "Titulo: Mensagem Questão ",JOptionPane.QUESTION_MESSAGE);
    });
    button3.addActionListener((ActionEvent e) -> {
        JOptionPane.showMessageDialog(button3, e.getActionCommand(),
    "Titulo: Mensagem Atenção ",JOptionPane.WARNING_MESSAGE);
    });
    button4.addActionListener((ActionEvent e) -> {
        JOptionPane.showMessageDialog(button4, e.getActionCommand(),
    "Titulo: Mensagem Erro ",JOptionPane.ERROR_MESSAGE);
    });

    painel.add(button1);
    painel.add(button2);
    painel.add(button3);
    painel.add(button4);
    frame.add(painel);
    frame.setSize(400, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Agora, talvez você esteja atrás de um JDialog o mesmo tem uma opção chamada AlwaysOnTop que, quando true, mantém o mesmo sempre a frente de qualquer janela independe da qual selecione. Também pode ser usado para Substituir um JFrame.
    JFrame frame = new JFrame("teste");
    JPanel painel = new JPanel(new GridLayout(2, 1));
    JButton button1 = new JButton("01");
    JButton button2 = new JButton("02");
     button1.addActionListener((ActionEvent e) -> {
       JDialog dialog = new JDialog();
       dialog.setSize(200, 200);
       dialog.add(new JLabel("JDialog Teste"));
       dialog.setAlwaysOnTop(true);//Fica sobre todas as janelas
       dialog.setModal(true);//Impede que seja as janelas em segundo plano sejam acessadas
       dialog.setVisible(true);
     });
     button2.addActionListener((ActionEvent e) -> {
        JOptionPane.showMessageDialog(button2, e.getActionCommand(),
    "Titulo: Mensagem Erro ",JOptionPane.ERROR_MESSAGE);
     });

    painel.add(button1);
    painel.add(button2);
    frame.add(painel);
    frame.setSize(400, 400);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Comment: Muito bom. Só faltou colocar corretamente os imports das classes usadas no exemplo e despachar pra EDT.
Comment: Achei que nao precisava, sorry rs.

JOptionPane em primeiro plano


Registration error in Laravel

Question: I use the default auth/registration in Laravel 5.3.
When I try to register new user I get  error:
FatalThrowableError in RegistersUsers.php line 33:
    Call to undefined method Illuminate\Auth\TokenGuard::login()

I have made some changes in configuration Laravel:
'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],

So, by default I use api guard
Comment: in which configuration file you made changes ?
Comment: you probably defined an api guard which is not capable of logging someone in since apis work with tokens to ensure authentication - therfore your "TokenGuard" probably just doesnt have a login method as explained in the error
Answer: The authentication driver api you are trying to use is TokenBased. That means the server will issue your client a Token on successful authentication using credentials. Then, client can present this token to server while making the request to identify itself.
As given in laravel git, there isn't any method as login().
To use the TokenBased Authentication, here's the good guide
Comment: I know, but how can I register new user? This articles does not explain how to do that
Comment: @Babaev registration process wont change. It will remain the same... provide the registration form to user and add the data to your users table.. right ?
Comment: I think your data is inserting properly in the DB. But if you check the `register` method in your `AuthController` there must be a call to `login` method after data insertion.. You would need to change to return the token. You can always override the `postRegister()` method in your `AuthController` to implement this..
Comment: I use Laravel 5.3, It does not have `AuthController`, I need that user can register using RESTful mechanism and standart web form.

Registration error in Laravel


Constrained least squares estimation

Question: I need to fit a regression model using least squares in R with the constraint that the parameters are positive. they DON'T need to sum to one. because some times parameter sum exceeds one.
Can someone help me with the code pease
Comment: There is a blog showing how to do this using the nnls library at http://www.jameskeirstead.ca/blog/positive-coefficient-regression-in-r/ .  Someone with the time to check and paraphrase that could post it as an answer?
Comment: If the parameters need to be positive, try fitting the model $Y=e^{\beta_0}+\sum_{i=1}^{p}e^{\beta_i}X_i+\varepsilon$ instead of $Y=\beta_0+\sum_{i=1}^{n}\beta_iX_i+\varepsilon$.
Comment: @Max, why not turn that into an answer?
Answer: 1) You could fit it by putting box-type constraints to an optimizer that can deal with them - see ?optim and ?nlminb, for example.
2) You could use code like this: http://www.stat.colostate.edu/~meyer/constrparam.R
3) You could use a package designed to have positivity-constrained models, such as the package penalized
4) you can use nonlinear LS in various ways to ensure non-negative or strictly positive regressions.
Answer: One way to accomplish this task is to alter your model slightly. Rather than fitting the typical model of $$Y=\beta_0+\sum_{i=1}^{p}\beta_iX_i+\varepsilon$$ instead fit the model $$Y=e^{\beta_0}+\sum_{i=1}^{p}e^{\beta_i}X_i+\varepsilon$$ This can still be fit by least squares fairly easily in R and it has the effect of forcing the coefficients to be non-negative.
Edit
Here's some code to accomplish the model fitting. Using nls gives both parameter estimates and variances.
# generate data

set.seed(1)
x <- cbind(1, matrix(rnorm(900, 1:9), nrow=100))
beta <- runif(10, 0, 1)
y <- x %*% beta + rnorm(100)

# try using nls function

ests <- nls(y ~ exp(b0) + exp(b1)*x[,2] + exp(b2)*x[,3] + exp(b3)*x[,4] +
                          exp(b4)*x[,5] + exp(b5)*x[,6] + exp(b6)*x[,7] +
                          exp(b7)*x[,8] + exp(b8)*x[,9] + exp(b9)*x[,10],
            start = list(b0 = runif(1), b1 = runif(1), b2 = runif(1), b3 = runif(1),
                         b4 = runif(1), b5 = runif(1), b6 = runif(1), b7 = runif(1),
                         b8 = runif(1), b9 = runif(1)))

summary(ests)

exp(coef(ests))

Comment: The code you posted fails for me (`R` 2.15.2) at the `nls` call with a "step factor <> reduced below 'minFactor' of <>" message. Regardless, because you generate only positive betas to begin with, this is scarcely a difficult test of the procedure! The challenge is to get it to work reliably when one or more of the components of `beta` are *negative*.
Comment: @whuber I apologize for not responding earlier. I actually share your concerns. This method will absolutely fail if any of the coefficients are negative. In fact, my guess is this method will fail if any coefficients are small and positive. And now that I'm thinking more deeply about the situation, this method may perform worse than OLS even when all coefficients are positive depending on their magnitude.
Comment: can you give me an example code please?
Comment: @dav I've added code. I hope that helps.
Comment: This is clever, but I worry that it will fail in precisely those circumstances where it is most needed: if one of the coefficients is negative for OLS, then most likely the optimal solution with this approach occurs where its logarithm approaches $-\infty$.  That may cause instability in `nls`.  It would therefore be good to see this method solve a realistic example accurately.
Answer: This is a quadratic programming problem:
Let $\mathbf I\in\mathbb R^{n\times 9}$, be your design matrix ($n$ is the number of measurements, so each row contains one measurement with the investments $I_1,\ldots, I_9$), and $\boldsymbol \beta\in\mathbb R^9$ your linear coefficients, which you want to be nonnegative (at least some of them). Then you want to minimize the cost function $c(\mathbf I, \boldsymbol \beta)$, which is the sum of the quadratic residuals,  under the nonnegativity constraint on $\boldsymbol\beta$:
$$
\begin{align}
c(\mathbf X, \boldsymbol\beta) &:= \sum_{i=1}^n \left(\sum_{k=1}^9 I_{ik}\beta_k - Y_i\right)^2\\
\beta_i &\ge 0,\quad i=1,\ldots,9.
\end{align}
$$
Since $c$ is a quadratic function of $\boldsymbol \beta$ and you have inequality constraints on $\boldsymbol \beta$, this is a quadratic programming problem, and there is software for solving it.
Comment: hi frank, nice to meet you again. Are there any way to find a constraints which will let the coefficients be positive ?
Comment: @nobodyishere :) If you obtain a minimum with some $\beta_i = 0$, this just means that you should not do the investment $I_i$. Why do you need $\beta_i$ to be strictly greater than zero?
Comment: Hi frank, the problems is that is not easy to tell the customer that your some of investments are jerk, they are not making any extra sales. Therefore, I cannot try `penalize()` package which will give me some `0 coefficients` while these coefficients are used to be negative. So, I have to make all coefficients be positive. All `I` must be included in the model and with positive coefficients.
Comment: @nobodyishere Well then I would recommend using as constraints $\beta_i \ge b$ with $b$ the smallest positive value that you think will be tolerated.
Comment: Could you give me a brief `code  example` or something related to how to find the `smallest b`?
Answer: The pcls() function in the mgcv package does partially constrained least squares. You can include equality and/or inequality constraints on some or all of the parameter estimates, and in fact on linear combinations of them. (It also allows for quadratic penalties, which are probably not relevant in your case.)
An alternative (which I found by searching for "constrained least squares in R") would be cls() in the cols package (which I haven't used yet, but take a look).

Constrained least squares estimation


Problema na versão responsiva do site

Question: Boa tarde pessoal,
Desenvolvi um site para um cliente, em wordpress, o site é sgcsolucoes.com.br. O meu problema é que parece que o css responsivo não está pegando. O site para desktop está certinho. Quando abro no celular, abre a mesma versão do desktop, mas quando vou no menu personalizar e escolho o modo responsivo, no simulador fica certinho, mas quando abro no celular continua aparecendo a versão para desktop.
Já desativei todos os plugins, já escolhi outro tema e, mesmo assim não funciona.
O Site responsivo, deveria ficar como na imagem.

Obrigado!
Comment: É o seu Cash do navegador Aqui abriu normal responsivo olha ai: http://prntscr.com/lt790y
Comment: O site responsivo deveria ficar como na imagem.
Comment: Tem alguma coisa errada é no seu CSS que não está funcionando a questão do menu.
Answer: Seu problema é que talvez por algum motivo vc removeu essa linha do seu
<meta name="viewport" content="width=device-width, initial-scale=1">

Aqui tem mais detalhes sobre o que é e os valores dessa meta tag Media query não funciona em site não responsivo
Veja na imagem, quado eu insiro essa linha no seu head o estilo responsivo passa a ser aplicado:
Comment: Essa meta tag está incluída na função business_point_head, do arquivo hooks.php. Tentei incluir manualmente, mas não funcionou
Comment: @DanielBrito eu não sei como é o seu tema, cada um pode ser de um jeito, mas aqui seria assim... http://prntscr.com/lt832p vc tem que ver como é no seu.
Comment: Abri o arquivo header.php e adicionei essa tag......quando eu redimeciono a janela do navegador, o layout responsivo funciona, mas quando abro no celular, não pega o layout responsivo.
Comment: @DanielBrito agora deve ser o cash do browser mesmo... Tenta limpar ai. Ou então eh Pq se cel tem a resolução muito alta, maior que seu media query
Comment: Acredito que não, porque se eu apertar F12 no chrome, e selecionar a versão mobile, também não pega o layout responsivo. Quando vou na guia elements, a meta tag não está lá também.
Comment: @DanielBrito desculpe não poder te ajudar mais... o problema acredito ser essa meta tag ai mesmo, agora a forma como vc vai coloca-la no head que vai ser o problema...

Problema na versão responsiva do site


No viable conversion from returned value of type 'double' to function return type 'vector'

Question: I don't know how to convert the variable type int to vector.
vector<double> movingTiles(int l, int s1, int s2, vector<int> queries) {
double smalld, t;
for(int i=0;i<queries.size();i++){
    smalld = sqrt(2*queries[i]);
    if(s2>s1){
        t=(sqrt(2)*l-smalld)/(s2-s1);
        return t;
    }else{
        t=(sqrt(2)*l-smalld)/(s2-s1);
        return t;
    }
}}

Comment: Why is your return type `vector`, if you want to return just a single number? Simply use `double` as a return type.
Comment: vector isn't a data type - it is a container.
Comment: Use `return {t};` if you want for some reason return vector with one element.
Comment: I think he doesn't want to return a single value...
Comment: Here is the link to the problem: https://www.hackerrank.com/challenges/sherlock-and-moving-tiles/problem
Comment: The function `return` statements all return `t`, which is of type `double`.   As the error message says, there is no implicit conversion from a `double` to a `vector`.  I assume you have a `using` directive (not shown) in effect, so `vector` is actually `std::vector`.   `std::vector` does not have a constructor that accepts a single argument of type `double`.   If you want to return a vector with one element, where that element has the value of `t`, then do `return vector(1, t)`.
Comment: Turns out the boilerpalate code was wrong so I rewrote the code form scratch. Thank you for your answers.
Answer: You should return std::vector<double>(1, t) from the method if you want to return a vector
Answer: Wild guess, but that what you want is this I think:
vector<double> movingTiles(int l, int s1, int s2, vector<int> queries) {
    double smalld, t;
    vector<double> vec_t;
    for(int i=0;i<queries.size();i++){
        smalld = sqrt(2*queries[i]);
        if(s2>s1){
            t=(sqrt(2)*l-smalld)/(s2-s1);
            vec_t.push_back(t);
        }else{
            t=(sqrt(2)*l-smalld)/(s2-s1);
            vec_t.push_back(t);
        }
    }
    return vec_t;
}

Answer: From the link in your comment:

For each query of form qi, Sherlock has to report the time at which the overlapping area of tiles is equal to qi.

This leads me to believe that the output vector should have the same size as the input vector queries, so:
vector<double> movingTiles(int l, int s1, int s2, vector<int> queries) {
    double smalld, t;
    // the vector to return:
    vector<double> times;
    // reserve space to make push_backs quicker:
    times.reserve(queries.size());

    // you only need to calculate this once for each set of queries
    int rspeed = std::abs(s1 - s2); // the absolute diff in speed

    for(int area : queries) {
        // your formula:
        smalld = sqrt(2 * area);
        t = (sqrt(2) * l - smalld) / rspeed;
        // store the result
        times.push_back(t);
    }

    // and return the resulting vector:
    return times;
}

Comment: Better to use vector constructor that takes `queries.size()` as input, or use `reserve()`
Comment: @CinCout-ReinstateMonica for small datasets  I doubt it'll have any measureable effect, but I agree that it's a good habit. Edited.


Linear Algebra: Solving for $x$ and $y$ in terms of $k$.

Question: I'm really struggling to grasp this one:

Find conditions on $k$ that will make the following system of equations
have a unique solution. To enter your answer, first select whether $k$
should be equal or not equal to specific values, then enter a value or
a list of values separated by commas.
Then give a formula in terms of $k$ for the solution to the system, when
it exists. Be sure to include parentheses where necessary, e.g. to
distinguish 1/(2k) from 1/2k.
$\begin{cases}3kx+12y = 3 \\ 8x+2ky = 5\end{cases}$

I know how to find $k$, but I'm not so sure on how to find $x$ and $y$ (in terms of $k$).
Can someone explain, in detail on how to do this? Please and thank you.
Comment: Think of $k$ as though it were a constant.  Then solve for $x$ and $y$ just like you would if $3k$ and $2k$ were any other integers.  (For example: top equation gives us $y =\frac {3-3kx}{12}$ and plugging that into the bottom we get $8x + 2k(\frac {3-3kx}{12} = 5$ and solve for $x$ etc.... or we could multiply the top by $k$ and the bottom by $6$ and subtract.....
Comment: Use substitution method.
Comment: Just do it.

We solve $2x + 3y = 4$ and $5x + 6y = 7$ by doing:

$2x + 3y =4\implies$
$3y = 4-2x\implies$
$y=\frac {4-2x}3\implies$
$5x + 6(\frac {4-2x}3)=7\implies$
$5x +8 -4x = 7\implies$
$x=-1\implies$
$y = \frac {4-2\cdot (-1)}3=2$

So just do that... but use $3k$ instead of $2$ and $12$ instead of $3$ and $3$ instead of $4$ and $8$ instead of $5$ and $2k$ instead of $6$ and $5$ instead of $7$.
Answer: I'm sure you've found that k absolute value mustn't be equal to 4.
Now, your only parameter is k & x & y are unknown & we have AX = b. You simply need to calculate inverse of A & multiply it from the left side to the b. I can show you the answer by MATLAB programming.
A = [3k, 12;8,2k]
X = [x;y]
b = [3;5]
A inverse = [ k/(3*(k^2 - 16)),  -2/(k^2 - 16); -4/(3*(k^2 - 16)), k/(2*(k^2 - 16))]
Answer:
x = k/(k^2 - 16) - 10/(k^2 - 16) &
y = (5k)/(2(k^2 - 16)) - 4/(k^2 - 16)
If there's anymore question, please ask in the comments.


adding ManyToOne mapping with existing column

Question: I came across a situation where I have to establish a many to one relationship between two tables with precondition as below:
table A:
-----primary_key_a------------column_a--------column_x---------
example:
------1----------------------------2050--------ABC
------2----------------------------2050--------AAA
------3----------------------------9090--------ABC
------4----------------------------9090--------AAA
table B:
-----primary_key_B------------column_B--------column_C---------
example:
------2050----------------------------SSS--------KKK
------2090----------------------------YYY--------KKK
As shown in two tables, primary_key_B and column_a have same values but in existing table, they have different column names (primary_key_B for table B and column_a for table A). In existing records, there are cases where some value of primary_key_B may not be in column_a and vice versa but we want to populate that going further
My Existing POJO for table_a and table_b are as below:
<code>    @Entity
    public class PojoForA
    {

        @Id
        @Column(name = "primary_key_a")
        private Integer id;

        @Column(name = "column_a")
        private String b;
        @Column(name = "column_x")
        private String c;
       //getter/setters
}

@Entity
public class PojoForB
{

    @Id
    @Column(name = "primary_key_B")
    private Integer idB;

    @Column(name = "column_b")
    private String b;
    @Column(name = "column_c")
    private String c;
   //getter/setters
</code>
}
Then I added below changes in Pojo A for Many to one Mapping:
<code>@Entity
public class PojoForA
{

    @Id
    @Column(name = "primary_key_a")
    private Integer id;

    @Column(name = "column_a")
    private String b;
    @Column(name = "column_x")
    private String c;

 @ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "idB",nullable=false,referencedColumnName = "primary_key_B")
   //getter/setters
</code>
}
It did not establish the relationship that I wanted to build. Table A already has the column with different name with same data as primary key of Table B.
When I tried to run, I get below error:
<code>    Caused by: org.h2.jdbc.JdbcSQLException: Column "tablea0_.primary_key_B" not found; SQL statement:.........
org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
        at org.h2.message.DbException.get(DbException.java:179)
        at org.h2.message.DbException.get(DbException.java:155)
        at org.h2.expression.ExpressionColumn.optimize(ExpressionColumn.java:150)
</code>
how do I solve this problem? Basically, I do not want to change the table structure but have a many to one relationship between table_a and table_b
Comment: The `ManyToOne` belongs in table B since it holds the foreign key to table A. there will be many table B entries for one given table A entry.
Comment: not correct. ManyToOne should be in table A and for many table A records, there should be one record in table B. If you see the example
Answer: You have put the ManoToOne reference in the Table B. First try to map your entities ok. I can see in your log file that there is a column not recognized, the reference column named primary_key_b must have a foreign key to table A.
The way to reference is in the mapping is:
<code>@JoinColumn(name = "primary_key_b", referencedColumnName = "column_a")
@ManyToOne(optional = true) // This is because you can have null values I understood.
</code>


Difference in technical skills needed for Bach 2 part inventions vs. Clementi Op. 36

Question: I'm not too sure how popular Clementi's sonatinas are (Op 36: http://imslp.org/wiki/6_Piano_Sonatinas,Op.36(Clementi,_Muzio)) but they are all over the Canadian RCM books.
As my previous questions have alluded to, I'm struggling with playing through Bach's 2 part inventions, specifically Invention 1 in C major, although the general difficulty remains no matter which one I try.  I can slog my way through the invention at less than half speed, and am still making many mistakes.  (I know that means I should slow down, and I do.  That's not the point of the question :-) )
However, I can open up almost any of the Clementi sonatinas and play it much faster than the Bach invention and more or less from sight - I have only really thoroughly studied the F major and C major, but I've tried them all so it's not technically sight reading.
I know that Bach's inventions require the skill of hand independence and finger independence, but, looking at the Clementi pieces, don't they need the same thing?
Clearly I have a set of technical skills that makes the Clementi pieces fit within my skill set, and clearly I lack a set of technical skills that  makes the Bach pieces fit outside of my skill set.  I feel that if I can identify which skills I do have and which I'm lacking, I can better focus my practicing.  In particular, I'd like to look for pieces that allow me to leverage my current skill set in order to maintain my interest, but which also have passages that challenge my lack of skill in order to get better.  My problem is that I don't seem to be able to distinguish which technical skills are required for which pieces, and therefore I can't really focus my practice.
Comment: Do you use a metronome ? The key in Bach pieces, when learning them first, is to concentrate on playing both melodies on tempo, mechanically. Since they are two different melodies / voices, I confirm that Bach's pieces are much more difficult in this aspect, so I assume it's perfectly normal for you.
Comment: I don't usually use a metronome, no, but my actual *timing* is not an issue per se.  What I'm really struggling with is that I just can't seem to make the Bach pieces sound like music.  They sound instead like just a bunch of notes that happen to be played together in time.  When I listen to recordings of the pieces, they sound, obviously, musical and well played.  I'm confused as to why my playing doesn't sound even close to music (to my ears)
Comment: So, is your question more about _musical_ or _technical_ difficulty (I understood your question as being the latter) ?
Comment: Perhaps both? I hadn't considered a difference. Basically, I can't get them to sound right. However, I feel that's because I am having so much trouble actually paying them that I can't spare any mental effort for musicality.  I think that's why, anyway...
Answer: The Clementi sonatinas feature only one melody overall (usually in the right hand), and the Bach pieces are more or less independent melodies (written to go together, of course), so aside from hand independence you would need melodic independence to play them together. That happens in your mind as much as in your hands.
For context though, I too can play the Clementi sonatinas reasonably well from sight and cannot play the Bach, so while I speak from experience it may not be more than your own. :)
Answer: There is a lot more technical difficulty in the Bach than in those Clementi pieces.  You need far more independence of character in what you are playing in each hand for the Bach whereas in the Clementi the hands are working together for much of the time.
Nothing wrong with the Clementi - good pieces for developing tone and touch at speed but they are comparatively straightforward when compared to the counterpoint in the Bach.
Keep going - practice: it will get easier.
Comment: Basically the Clementi is using the left hand as an accompaniment to the right hand melody.  Rhythmically the two hands keep reasonably well together.  Also these pieces are fairly simple harmonically.  In the Bach you have to do with the left hand basically the same sort of thing as the right hand.  Sounds easy but actually it usually isn't.  In the earlier learning stages most pianists are better with their right hands, although I'm not sure why that is.
Comment: Left hand studies are fine but there may be other things that help more.  If you think that your left hand is simply not as good then yes, try some left hand studies.  But if your problem is the independent nature of the two hands then you need to work more on techniques for that, which is why I recommended the contrary motion scales in answer to your other post.
Comment: I noticed there is a lot more technical difficulties in the Bach, for sure.  But what are they?  Melodic independence has been suggested (and I hadn't thought of it at all, so thanks @Andrew Conkling).  Anything else, or is it just "they are harder pieces"?
Comment: So do you imagine a bunch of studies for the left hand would help? I've heard that one should study what they want to play, but I guess that can be interpreted different ways
Comment: So are Clementi sonatinas easier than even the easiest of Bach 2 part inventions? What are the respective levels or grades?
Comment: @GrandAdagio  In my view yes the Clementi is easier.  As to grades - actually I have no idea but they will be down among the lower gradings in any of the grading systems I think.
Comment: @JimM Thanks. I've learned a few easier Inventions, and plan to learn some Clementi.