Axiomatization of physics

Question: I'm studying mathematical physics and I often suffer from the fact that "big theories" in physics never have explicit axioms (quantum mechanics, QFT, GR, ...), or at least fundamental rigorous principles.
I am not talking about the fact that physics aims to describe the real world, but about the fact that the mathematical models used are often not well defined (at least to my actual knowledge).
Is this really the case? Is there some area of math that aims to axiomatise some physical models? Could you recommend some literature?
Comment: Hilbert's sixth problem was to axiomatize physics (or at least parts of physics). So at least we know great minds have given this question a lot of thought.
Comment: Tangential comment, but Terence Tao once made some comments about how physical models work that I thought were enlightening. I recorded the comments here: https://math.stackexchange.com/a/2238425/40119
Comment: I believe [Carnap](https://en.wikipedia.org/wiki/Rudolf_Carnap) did a lot of work on logic and science that may be relevant to you.
Answer: This is far from a complete answer, but it illustrates the basic fact that such axiomatization is very much a work in progress.
One Millennium Prize problem asks us to prove each compact simple gauge group is associated with a certain theory that would be of great interest to physicists. Reading that article, you'll find out about the Wightman axioms, which are one of several choices for axioms that such a theory ought to satisfy. We're not entirely sure which axioms are a sensible choice. If the problem is ever solved, it will likely involve saying, "Let's go with this list of axioms instead".
Why is physics in this situation? I'll only mention one contributing factor.
When a physical theory is shown with either empirical evidence, a thought experiment or a calculation to have a serious problem, physicists patch it to address this problem. Mathematicians aren't generally familiar with a need to do this. They arguably should be, but only in a historical sense; nowadays, "use these axioms and you'll be fine, and never mind the false starts before we got there" is a standard approach in undergraduate or higher mathematics education. When physicists have to "compromise" their axioms (if they even think of it in those terms; to be fair, mathematics itself largely didn't before about 1900, despite Euclid's influence), it's kind of like when Russell's paradox forced mathematicians to patch set theory. How to patch it has been the subject of some controversy ever since!
Mathematical theories often have equivalent choices for their axioms, such that which you'll use depends on what's convenient in your context, especially from the standpoint of pedagogy. In physics, the way problems historically evolve the subject compound this issue. Let's pretend it's 1800 for a second, so electromagnetism, special relativity, quantum mechanics etc. aren't an issue. Do you use Newtonian, Lagrangian, Hamiltonian or Jacobian mechanics? Horses for courses, but they're equivalent. As new physics is added, you often have to jump around between different choices of standpoint for further insights. This is an awkward analogy, but if a choice of axioms were like a basis of a vector space, it would be as if you had to rotate to another basis to get a now useful perspective.
Having said all that, I think you'll be interested to read about specific examples of axiomatisation, though I don't recommend specific texts. You'll want to read about the examples I've mentioned so far, Haag-Kastler and Mach.
Comment: Your answer is much much better and more more complete than mine.(+1). you deserve (+2) but not allowed.
Comment: +1 for Haag-Kastler. Algebraic QFT is a nice example, as are TQFTs (check out e.g. the Atiyah-Segal axioms). Both communities have a healthy composition of mathematicians and physicists alike.
Answer: In Mathematics, you start by axioms. then you choose good definitions and then you prove theorems. in general the result you get don't change with time.
In Physics, you start by Principles. Then you check the result you can predict by experience or test. In some cases, you have to change the principle if some experience give unexpected result.
In Philosophy, you start by Postulates. But every one has own postulates and own conclusions.

Axiomatization of physics


Better in AUC and AUC PR, but lower in the optimal threshold

Question: Suppose we have two models; model A and model B.
Model A outperforms both AUC ROC and AUC PR to model B.
However, when we compare the two models with their optimal threshold values, model B outperforms in both the F score and ROC.
In this case, which model should I pick?
(I'm in the medical diagnosis field.)
Thanks a lot.
Answer: Welcome to the community. While asking questions, it is recommended to provide complete details in order to get specific answers.
Broadly, you're asking about model selection in classification problem while comparing two different models based on some model evaluation metrics.
Model selection depends on many trade-offs:

Interpretation Vs Prediction accuracy: Do you need a simple model that is more interpretable OR a less interpretable model with better performance?
Selecting appropriate model evaluation criteria: depending upon your objective, you can take a call on what is riskier for you False positives or Falses negatives (a trade-off again). Based on the confusion matrix, we compute different ratios (sensitivity/specificity/precision/etc.)
I recommend going through my posts here and decide.
Comment: Thank you for your reply. I understand that it depends on the trade-offs with what I want to convey. However, my question was whether we should prefer the fine-tuned sensitivity/specificity, etc. or threshold-free metrics.
Comment: There's no one size fit all metric. Different metrics have their own pros and cons.


How are three input speakers wired?

Question: I had a gig last week and played (guitar) over a shared 2x12" speaker. After plugging in my stereo amp the sound was "strange" and delayed for about half a second. The sound guy blamed my effect board, but after some investigation I noticed that the speaker had three inputs labeled input, parallel and serial. I accidentally plugged in my amp in the serial and parallel sockets. Taking no chances I switched to a mono setup and plugged into the input input. Sound was back to normal.
Now I am wondering: how is such a three input speaker wired? And how can the strange delay effect be explained?
Comment: How were you plugged in before you made the change? I'm pretty sure the "parallel" and "serial" jacks were actually *outputs*, not inputs.
Comment: @ToddWilcox Into the parallel and serial sockets. From my point of view they were the only ones visible and I assumed them to be the "normal" connections. I actually have not considered them to be outputs ... that's probably correct.
Comment: *Shared* as in one band provided the speaker, all bands used it.
Answer: Ok, I think here's what happened:

I'm 99% sure the "Parallel" and "Serial" jacks are actually outputs, and they are mutually exclusive options one would use to chain an additional speaker cabinet. Chaining a second cabinet in parallel would lower the total impedance of the system, and chaining one using the serial output would raise the impedance. As impedance matching is important, both options were available.
Even though they are outputs, they are connected to the input in a certain way, so you could accidentally use them as inputs and get some sound from the speaker.
Because of how you originally plugged in and how those jacks are probably wired, I suspect any audio that was the same in both the left and right channels (i.e., panned center) would be cancelled out, and audio that was different between the two channels (i.e., panned left or right) would still be heard.
If you had a delay effect on your rig with the dry sound panned center and delay taps to the sides, then you might have cancelled out the dry sound and only heard the delayed sound, hence the delay in hearing your sound.

Here's how a serial output jack is wired:

Here's how you can have both jacks in one cabinet (imagine the parallel in not being there and the serial out being a switched jack as above):

Images Source
Note that if the input is wired a certain way, the outputs can be used as inputs instead, depending on how you plug in. Even with that in mind, it's better to consider the "Parallel" and "Serial" jacks to be outputs, in general.
Comment: I would guess the parallel and serial jacks are neither inputs or outputs but alternate ways to connect speakers in series. As such they could function as inputs or outputs depending on which of two connected speakers is receiving the input from the source.  They simply allow for chaining two speakers together either in parallel or serial mode.  They are probably not designed to be used at the same time and are certainly not for left and right stereo input.

How are three input speakers wired?


Showing that the absolute value of |X| converges almost surely.

Question: Here is my question and my solutions. I am just curious if this makes sense.

If something is wrong, then it will be nice if you can correct it for me or provide another solution. Please and thank you!
Comment: It is fine, but there is a simpler answer, if $A=[X >10]$ has positive measure, then $A_m=[X > 10+{1 \over m}]$ has positive measure for some $n$. Then $|X-X_n| \ge {1 \over m}$ on $A_m$ which contradicts convergence in probability.
Comment: Ok, thank you for that information. I am guessing it has to do with measure theory. What I have learned so far never really covered this.
Answer: To elaborate on copper.hats comment, if $\mathbb P(X>10)>0$ then there exists some integer $m$ such that $\mathbb P\left(X>10+\frac1m\right)$. But this implies that $\mathbb P\left(|X-X_m|\geqslant \frac1m\right)$, and contradicting the assumption that
$$
\lim_{n\to\infty}P\left(|X-X_n|\geqslant \frac1n\right) = 0.
$$


Where does the addition property for matrices come from?

Question: About an hour ago, I asked this question: What is Matrix?
I was confused (and to a certain extend, still am) about where the properties of matrices come from. My question was marked as a duplicate of this other question: What's a matrix?, which I can certainly understand why.

In the latter question, the repliers explained that matrices are usually used to represent a transformation in vector spaces.
For example, one could represent the set of equations:
$3x+2y+5z $
$9x-4y+z$
$-15x+2z$
as the following matrix:
$$
        \begin{pmatrix}
        3 & 2 & 5 \\
        9 & -4 & 1 \\
        -15 & 0 & 2 \\
        \end{pmatrix}
        \begin{pmatrix}
        x \\
        y\\
        z\\
        \end{pmatrix}
$$
If I understood correctly, the addition rule for matrices, in which we add each corresponding entry of two matrices, could be seen as a way of representing the sum of some sets of linear equations, or, more generally, some sets of vectors.
For instance, if we wanted to add $(3x+2y+5z)+(4x+6y-8z)$, one could write
$$
 \begin{pmatrix}
        3 & 2 & 5 \\
        \end{pmatrix}
\begin{pmatrix}
        x \\
        y\\
        z\\
        \end{pmatrix}+
 \begin{pmatrix}
        4 & 6 & -8 \\
        \end{pmatrix}
\begin{pmatrix}
        x \\
        y\\
        z\\
        \end{pmatrix}=
 \begin{pmatrix}
        7 & 8 & -3 \\
        \end{pmatrix}
\begin{pmatrix}
        x \\
        y\\
        z\\
        \end{pmatrix}
$$
...right?
Specifically,  if we have two matrices, $A$ & $B$, each one with $n$ rows and $m$ columns, the addition rule states that each entry $a_i,_j$ ($i$th row, $j$th column) of $A$ should be added with each entry $b_i,_j$ of $B$, creating a new matrix, $C$, in which each entry $c_i,_j=a_i,_j + b_i,_j$.

Q1. Could this addition rule of matrices be simply seen as a way of adding some sets of vectors?
Q2. If this is the case, why is it that, in order to add two matrices, we need both of these to have the same number of rows and columns? Is it because if we have a different number of rows/columns, then we wouldn't know which vectors correspond with each other?

Any thoughts/ideas would be really appreciated.
Comment: You use the word "sets" here which has some deep mathematical significance which I don't think your usage here intends.  If you prefer to think of the columns as vectors, sure... that's fine but not necessary.  If you *do* think of it that way, then remember that only vectors from the same space have a well defined addition leading you to needing the same number of rows, and the necessity of having each column having a partner to be added to makes it so they need the same number of columns.
Comment: Personally, I dislike trying to justify the *why*'s of why matrix addition/multiplication/etc... are defined the way they are, and instead prefer to take the definitions as exactly that, *definitions*.  It so happens that the way matrices and the operations surrounding them are defined happen to be useful and coincide with other mathematical objects, but at the time of their creation they didn't yet have such a deep theory surrounding them that was well known or understood.
Answer: Matrices represent linear transformations. If $f$ and $g$ are linear transformations, then so is $h$ defined by
$$h(u)=f(u)+g(u).$$
It is natural to denote $h$ by $f+g$.
If $f$ and $g$ are represented by matrices $A$ and $B$, then $f+g$
is represented by $f+g$.


Javascript push data on Firebase

Question: This is my HTML page:
<!doctype html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

<link rel="stylesheet" href="css/style.css">
<title>Nuova offerta</title>

        <button id="button_toggle" class="navbar-toggler" type="button" data-toggle="collapse" data-target="#menu_start" aria-controls="menu_start"
                aria-expanded="false" aria-label="Toggle navigation" onclick="onCollapseMenuClick()">

        </button>

               Home

                    Offerte

                    Gestione

Crea nuova offerta:

 <form>

    Titolo
      <input id="title" name="title" placeholder="es: segretaria" type="text" class="form-control here" required="required">

    Descrizione
      <textarea id="desc" name="desc" cols="40" rows="5" class="form-control" aria-describedby="descHelpBlock" required="required"></textarea>
      Inserire mansioni da svolgere, titoli di studio richiesti ed eventuali requisiti linguistici.

    Reparto

      <select id="dip" name="dip" class="custom-select" required="required">
        <option value="admin">Amministrazione</option>
        <option value="comm">Commerciale</option>
        <option value="mgz">Magazzino</option>
        <option value="trap">Trasporti</option>
      </select>

      <button  onclick="sendOffer()" id="myButton" class="btn btn-primary">Pubblica</button>

</form>

Given that Firebase parameters are corrected, you can clearly see that when I press the button I call the following javascript function:
function sendOffer(){

var database = firebase.database();
// Create a new ref and log it's push key
alert('function called');
var obj = {name: "sample_data"}
database().ref("offers/").push(obj);

}

Right now, my Firebase db is empty but, according to the code, I am expecting to see one parent node called 'offers' and then 'sample_data' as child. However, everytime I click on the button the related 'sendOffer()' function is called (I can see the alert) but no data are written on the database. I tried to debug it and I saw that I got this error when it comes to push data: TypeError database is not a function.
How can I write data to Firebase db?
Comment: https://firebase.google.com/docs/database/web/read-and-write (remove `()`, it's not a function.)
Comment: The documentation states it should be used as `firebase.database().ref(...)`, but you're doing `firebase.database()().ref(...)`
Comment: @KevinB even if removing () it still does not work:
Comment: With the same error? i don't believe you.
Comment: Actually I don't get any error @KevinB .. My firebase db is still empty. I am logged into the system and config parameters are correct.
Comment: What kind of collection are you pushing to?
Comment: Collection? I just want to push a simple string, I am not using any array/list/set etc. Thanks for helping me anyway @KevinB
Answer: You're using database().ref
Try without parenthesis after 'database' since your variable already contains the parenthesis for the method firebase.database():
    database.ref("offers/").push(obj);

And declare the variable 'database' outside of your function, making it a globla variable, since it should always be available to your database configuration.
Comment: Sorry, I forgot the fact that you are pushing a new object. The formula then should be `db.ref('items/').push(object);` Then, I would try declaring the variable 'database' outside of your function, to begin with, to make it a global variable and not a local one.
Comment: This is an error sure, but after removing brackets it's still not working.
Comment: try using 'set' instead of 'push'
Comment: I tried with set but it's still not working. By what I understood reading firebase documentation 'set' is used to updated a node that already exists, while push if it's not.
Comment: Yes it works! Thank you a lot Alejandro G. So the point was to make the variable global..I'll keep in mind
Comment: That's right. Otherwise, it is only available inside the function and therefore can be prevented from accessing the firebase configuration.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165918/discussion-between-alejandro-g-and-giacomo-bartoli).

Javascript push data on Firebase


MSSQL query select top by weighting

Question: Please refer a table below. Each Targeted_Product_Id has 100 Recommended_Product_Id's. I want to select top 6 by Weighting. I was trying to achieve it using HAVING but unfortunately failed. Could you please help me construct such query?

Thanks!
Answer: ;WITH RemoveDuplicatesCTE AS
(
    SELECT   Targeted_Product_Id,
             Recommended_Product_Id,
             Weighting
             ROW_NUMBER() OVER(PARTITION BY Targeted_Product_Id,Recommended_Product_Id ORDER BY Targeted_Product_Id,Recommended_Product_Id) AS rn
    FROM     Targeted_Product
)
,ProductsCTE AS
(
    SELECT   Targeted_Product_Id,
             Recommended_Product_Id,
             Weighting
             ROW_NUMBER() OVER(PARTITION BY Targeted_Product_Id ORDER BY Weighting DESC) AS rn
    FROM     RemoveDuplicatesCTE
    WHERE    rn = 1
)
SELECT   Targeted_Product_Id,
         Recommended_Product_Id,
         Weighting
FROM     ProductsCTE
WHERE    rn<=6
ORDER BY Targeted_Product_Id,
         rn DESC

Comment: You probably want to add an ORDER BY at the very bottom as well. Otherwise you may see weird results like row numbers 4 and 5 appearing before rows 1 thru 3.
Comment: Thanks for amazing query! Should I add `ORDER BY Weighting **DESC**` in order to select top weighted products?
Comment: @WildGoat Indeed, if you want the most weighted you should order by desc. I will update my post.
Comment: Also, in my data I've duplicates sometimes as `recommended_product_id`. Is there are any way I can filter them out so that mapping between `Targeted_Product_Id` and `Recommended_Product_id` would be at most 1?
Comment: How do you want ties to be handled? ROW_NUMBER will pick one at random unless you ensure that its ORDER BY clause is unique. If you want to return all ties, even if this means 7+ records, then use RANK instead. (There is also DENSE_RANK, but you don't want that for this use case.)
Comment: @WildGoat Sure, just use a GROUP BY subquery. You'll need to figure out how to handle Weighting, maybe MAX or AVERAGE.
Comment: @GiannisParaskevopoulos, thanks! but unfortunately duplicates still in the results.
Comment: I would like to see an example in SQL Fiddle please.

MSSQL query select top by weighting


$p(T) = 0$ with $\deg p \le n^2$

Question: Let $V$ be a vector space with $\dim V = n$, and let $T \in \mathcal{L}(V)$. I need to prove that there is a non-zero polynomial $p(x)$ of degree no more than $n^2$ such that $p(T) = 0$.
Any help or hints would be splendid.
Comment: Observe that the space $\mathcal{L}(V)$ has dimension $n^2$. Then, the elements $I$, $T$, $T^2$,...$T^{n^2}$ are necessarily linearly dependent. From this it is easy to conclude.
Answer: This result is more elementary than Cayley-Hamilton, and it is not required for the proof.
Note that
$\dim \mathscr L(V) = n^2;  \tag 1$
note further that the set
$\mathscr S = \{T^k, \; 0 \le k \le n^2 \} \tag 2$
satisfies
$\vert \mathscr S \vert = n^2 + 1; \tag 2$
thus a linear dependence must hold amongst the elements of $\mathscr S$, that is, there exist $n^2 + 1$ scalars $p_0, p_1, p_2, \ldots, p_{n^2}$, not all zero, such that
$\displaystyle \sum_0^{n^2} p_iT^i = 0; \tag 3$
$T$ then satisfies the polynomial
$p(x) = \displaystyle \sum_0^{n^2} p_i x^i, \tag 4$
and
$\deg p(x) \le n^2. \tag 5$
$OE\Delta$.
Answer: An linear transformation $T$ from $V$ to $V$, with $dim(V)=0$, is represented by a $n \times n$ matrix $A$
So by finding the characteristic polynomial $p$ of the matrix $A$  we know by Cayley-Hamilton theorem that $p(A)=\Bbb{O}$
Then degree of the polynomial is $n$

$p(T) = 0$ with $\deg p \le n^2$


Existence of basis for $L^2(\mathbb{S}^1,\mu)$, where $\mu$ is arbitrary, for which Riemann-Lebesgue lemma is true.

Question: Consider the unit circle $\mathbb{S}^1 \subset \mathbb{R}^2$. Let $\nu$ be the uniform measure on $\mathbb{S}^1$. Then there is an orthonormal basis for $L^2(\mathbb{S}^1,\nu)$, namely $\{1,z,\overline{z},z^2,\overline{z^2},\ldots\}$ for which the Riemann-Lebesgue lemma is true. That is, if $g\in L^2(\mathbb{S}^1,\nu)$, then we have
$$
\lim_{n \rightarrow \infty} \int_{\mathbb{S}^1} f_n(z)~ g(z)~ d\nu(z)
=0, $$
for $f_n(z) = z^n$ or $\overline{z^n}$.
My question:  Suppose $\mu$ is an arbitrary Borel probability measure (whose support is not a finite set) on $\mathbb{S}^1$. Is it possible to find an orthonormal basis for $L^2(\mathbb{S}^1,\mu)$, namely $\{f_n\}_{n\geq 1}$, such that for every $g\in L^2(\mathbb{S}^1,\mu)$
$$
\lim_{n \rightarrow \infty} \int_{\mathbb{S}^1} f_n(z)~ g(z)~ d\mu(z)=0?
$$
Remark: For $\mu$ supported on a countable set $\{a_n\}_{n\geq 1}$ with $p_n = \mu(a_n) >0$, the natural choice of ONB, namely $\{\frac{1}{\sqrt{p_n}}\delta_{a_n}\}_{n \geq 1}$ works.
Thanks!
Comment: Can you elaborate your remark, please?  Suppose $g(a_n)=g_n$; then $g\in L^2(\mu)$ implies $\sum_n p_n g_n^2<\infty$, so $|g_n|\sqrt{p_n}\to0$,but you seem to say that $p_n g_n/\sqrt{p_n}\nrightarrow0$.
Comment: In fact, if $\{f_n\}$ is _any_ orthonormal basis of $L^2(\mu)$, then for  $g\in L^2(\mu)$ we have $\sum_n| \langle g_n,f\rangle|^2=\|g\|^2<\infty$, so $\langle g_n,f\rangle\to 0$.
Comment: @kimchilover: Thanks! You are right, I will edit the question.
Comment: @kimchilover: Thanks! You are right.
Answer: Since $\mathscr{B}(\mathbb{S}^1)$ is countable generated, $L_2(\mathbb{S}^1,\mathscr{B}(\mathbb{S}^1),\mu)$ is separable. Once you have a countable dense set $\{\phi_n:n\in\mathbb{N}\}$, you can obtained an orthonormal basis by Gram-Schmidt orthogonalization. In fact, as $\{e^{-\pi n\theta i},n\in\mathbb{Z}\}$ is uniformly dense (by the Stone Weierstrass theorem), it will also be dense in $L_2$. You can then use GS-method to find an orthonormal basis.
Riemann-Lebesgue will follow from Parseval's theorem.


What's the best way to see cpu usage breakdown for a given process?

Question: I'm trying to find the bottlenecks and I'm currently logging the time in the script but it seems to be random times for certain operations. Is there a tool that will allow me to see the breakdown of what's going on during a certain [apache] request to track down if the CPU is just burning the whole time or if it's waiting for something else?
Comment: Missed a tiny detail...what operating system?
Answer: This is a question of profiling; you need to hook up a profiling tool to the process and get it what's really going on.  For really poor-man's profiling, I just attach to it using strace; using the timing flags (<code>-T -r</code>) usually gives me a good idea of what system calls are taking the time, and whether the process itself is just grinding along.  There are better things out there, but they're more developer-oriented.
Answer: If you're using a windows OS, then the free tools from SysInternals might be the best place to start. The Process Explorer tool is pretty good at watching the active processes, what's calling them, and what actions are taking place. SysInternals makes it pretty easy to download the SysInternals Suite of tools. It's kinda like an American Express Card, don't leave home with it.
Hope this helps some.
Answer: Something else to check, If you're able, is to monitor the server's performance.
Maybe your disk queues are spiking, maybe you have a failing drive in the RAID, maybe you are running out of memory, etc...
Answer: You can see some more detail with a tool like procstat.  You feed it a PID and it decodes the /proc/$pid/stat file which can tell you some interesting internals stuff, like number of CPU jiffies it has used, or its children have used.


Bridging two (a physical ethernet with a virtual ethernet) different subnets on linux?

Question: I am thinking if it's possible to create  a bridge while allowing each bridged network to exist in it's own subnet.
Network 1 - Say, I have a physical ethernet based network eth01 - with subnet 192.168.x.x/16.
Network 2 - I want to create another virtual network veth01(based on virtual interface) with subnet 172.16.x.x/12.
Now is it possible to create a linux bridge (virtual not physical) between Network1 and Network2, such that even after bridging the above two networks have there on subnets and there own DHCP.
Any reference or steps/commands on how to create this setup (if possible) are highly welcomed.
Comment: You do not bridge different networks. You bridge on the same network, but route between networks. That is the purpose of a router.
Comment: "a bridge can be used to segment networks" That is about VLANs. To get traffic from one VLAN to another VLAN, you need a router. VLANs will segment a bridge (a switch is a bridge) into multiple, logical bridges that do not talk to each other.
Comment: Switches do not route, they bridge. The term "switch" started out as a marketing term for high-density bridges. Switches/bridges forward frames based on the layer-2 address on the same layer-3 network. Routers route packets between networks.
Comment: Ron, if someone says - **"a bridge can be used to segment networks"** are they right.
Comment: Ron, my understanding:  Switches - "only route traffic towards their addressed destinations using mac(L2)".  Bridges - "send the traffic to every device on the other side if the traffic is meant to go to the other side" **???**. Am I understanding bridges right?
Comment: " Switches do not route" - Agree.   What I am trying to point is - like hub (L1) does bridges(L2) repeat the message to every MAC or only to the destined address.
Comment: No. Hubs repeat the electrical signals our every other interface. Bridges will create a Mac address table and only send frames to the interface where the MAC address is connected. Switches do that too, because switches are bridges, albeit with more interfaces than the original bridges.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/109931/discussion-between-samshers-and-ron-maupin).
Comment: @samshers you already asked about the difference between bridge and switch and were told they were the same: https://serverfault.com/questions/1022779/in-virtual-networking-how-does-a-virtual-switch-differ-from-a-linux-kernel-brid . Now you still consider there's a difference. Why did you ask then?
Comment: The discussion was leading there  - if you are referring to chat discussion. :-(. So double checked.
Answer: You are thinking wrong on several levels.

A bridge is a layer 2 device. If you connect two networks by a bridge, you are creating a single layer 2 network comprising both of the connected networks - in your case, the physical Ethernet based network connected to interface eth01 and the virtual network connected to interface veth01. Any layer 3 network carried on one of these network will then also be carried on the other one.
There is no one-to-one relation between layer 2 and layer 3 networks. So in your scenario, the bridged network comprising the physical Ethernet and the virtual network can carry both the subnet 192.168.x.x/16 originally carried by the physical Ethernet on eth01 and the subnet 172.16.x.x/12 originally carried by the virtual network on veth01, without the two interacting in any way. (Except possibly competing for bandwidth.)
DHCP is not "owned" by a network. You can run several DHCP servers on one layer 2 network if you do it carefully, and you can also run a single DHCP server serving several layer 2 network.

From your question, it seems what you want to do is configure two DHCP servers so that one of them serves only clients on the physical network and the other one only clients on the virtual network. This is something that cannot be easily done if you install a bridge between the two, as the bridge effectively removes the distinction between the two. If you need that, you should either reconsider your decision to use a bridge, and go for routing instead, or you need to find a distinguishing attribute for your DHCP server to decide from which layer 3 network it should take the IP address to assign to a given client.
Comment: Tilman,  (1) addresses my Q. ". If you connect two networks by a bridge, you are creating a single layer 2 network comprising both of the connected networks" :-)


Unique characterization of convex polygons

Question: Question
I am looking for a unique characterization of a convex polygon with $n$ vertices, relative to a feature point $p$ in the interior of the polygon. This characterization would be a vector of numbers. Suppose a polygon is described by its feature point and vertices $P=(p,v_1,\ldots,v_n)$, then the characterization function is $C(P)$ such that $C(P)=C(Q)$ if and only if $P$ is congruent* to $Q$. The most important thing I need is that for two polygons which are "almost" congruent, their characterization vectors should be "close" (like, say, small 2-norm difference). The question then is what is a simple definition of the characterization function $C(\cdot)$ which satisfies my requirements?
*Here I define congruent as identical up to rotation and translation (reflections are not allowed), cyclic permutation of vertex indices, as well as identical feature point locations. If $P$ is congruent to $Q$, then any cyclic permutation of the vertices of either polygon should still leave $C(P)=C(Q)$ (thus $C$ should be invariant to cyclic permutations of the vertices). If two polygons are congruent, then when they are overlaid, the feature points of both polygons must also match up (this is why I originally stated that the polygon is defined relative to the feature point).
An illustration of what I mean is shown below. The dots inside are the feature points of the surrounding polygon.

Things that don't work
Most characterizations of polygons usually calculate the 2x2 moment of inertial tensor relative to the center of mass of the polygon. This is not good enough because first of all, the moment tensor is not enough to completely define the shape, and second, the feature point of a polygon must also match for two congruent polygons.
Ideas

A vector of higher order moments relative to the feature point. (Is this unique?)
A vector of displacements from a regular $n$-gon vertex positions. (Does this satisfy the nearness aspect?)
Comment: The list of distances to the vertices, and the angles determined by the segments joining your point to them. Does that work?
Answer: As described below, any $n$-gon is a "sum" of regular $\left\lbrace\frac{n}{k}\right\rbrace$-gons, with $k = 0, 1, 2, \cdots, n-1$. This can give rise to a vector of complex numbers that serves to characterize the shape of the polygon.
Given polygon $P$, we start by choosing a "feature point" in the form of a distinguished starting vertex, $v_0$, as well as a preferred tracing direction --in the universe of convex polygons, we can unambiguously take that direction as "always counter-clockwise"-- to get a list of successive vertices $v_0, v_1, \dots, v_{n-1}$. Write $[P]$ for the vector whose $j$-th element is the point of the Complex Plane at which the $j$-th vertex of $P$ lies.
Define the "standard regular $\left\lbrace\frac{n}{k}\right\rbrace$-gon", $P_k$, as the polygon whose $j$-th vertex coincides with the complex number  $\exp\frac{2\pi i j k}{n}$. (As shapes, $P_k$ and $P_{n-k}$ (for $k \ne 0$) are identical, but they are traced in opposing directions.)
Now, any $n$-gon is the "sum" of rotated-and-scaled images of the $P_k$s, in the sense that we can write
$$[P] = r_0 [P_0] + r_1 [P_1] + \cdots + r_{n-1} [P_{n-1}]$$
with each complex $r_j$ effecting the corresponding rotation-and-scale. (Determine the $r_j$s by reading the above as $n$ component-wise equations. The solution is, clearly, unique.) Therefore, the vector $R(P) := (r_0, r_1, \dots, r_{n-1} )$ exactly encodes the polygon as a figure in the plane.
Note that, for $k > 0$, polygon $P_k$ is centered at the origin, while all the vertices of polygon $P_0$ coincide at the complex number $1$. Consequently, the $P_0$ component of the decomposition amounts to a translational element, identifying the centroid (average of vertex-points) of the figure. As we are concerned about shape without regard for position, we can suppress (or just ignore) the $r_0$ component of $R(P)$. Since a polygon's shape is independent of the figure's rotational orientation, we choose to normalize $R(P)$ by rotating the elements through an angle that would align $v_0$ with the positive-real axis, arriving at our $C(P)$:
$$C(P) := \frac{1}{\exp(i\arg{v_0})} R(P) = \frac{|v_0|}{v_0} (r_1,r_2,\dots,r_{n-1})$$
If polygons $P$ and $Q$ are congruent (with compatible distinguished vertices and tracing directions), then we have $C(P) = C(Q)$. When $P$ and $Q$ are nearly-congruent, $|C(P)-C(Q)|$ will be small, and vice-versa.
Note: When $P$ and $Q$ are similar  (with compatible distinguished vertices and tracing directions), we have $\frac{C(P)}{|C(P)|} = \frac{C(Q)}{|C(Q)|}$.
Edit
As noted in comments, this $C(P)$ isn't invariant under cyclic permutations of the vertices. It's worth investigating exactly what effect a cyclic permutation has.
Consider the triangle $P$ with $[P] = ( v_0, v_1, v_2 )$. The corresponding regular $P_k$ figures are given by
$$[P_0] := ( 1, 1, 1 )$$
$$[P_1] := ( 1, w, w^2 )$$
$$[P_2] := ( 1, w^2, w )$$
where $w = \exp\frac{2\pi i}{3}$.
We can easily solve the decomposition equation to get
$$R(P) = (r_0, r_1, r_2) = \frac{1}{3} \left( v_0+v_1+v_2 \;,\; v_0 + v_1 w^2 + v_2 w \;,\; v_0 + v_1 w + v_2 w^2 \right)$$
If $P'$ is identical to $P$, but with cyclically re-ordered vertices, $[P'] = ( v_1, v_2, v_0 )$, then
$$R(P') =  \frac{1}{3} \left( v_1+v_2+v_0 \;,\; v_1 + v_2 w^2 + v_0 w \;,\; v_1 + v_2 w + v_0 w^2 \right) = ( r_0 \;,\; w r_1 \;,\; w^2 r_2 )$$
Observe that $w r_1 [P_1] = r_1 ( w, w^2, 1 )$ yields the same polygon as $r_1 [P_1] = r_1 ( 1, w, w^2 )$, except that its vertices have been cyclically re-ordered. Likewise for $w^2 r_2 [P_2]$ (and $w^0 r_0 [P_0]$, for that matter). The same holds for arbitrary $n$-gons.
Thus, as a family of polygonal shapes, the decomposition into regular components is independent of cyclic permutation, as is the correspondence between the vertices of the components and the vertices of the polygon. That is, in our triangles $P$ and $P'$, we have $v_0 = r_0 + r_1 + r_2$, and $v_1 = r_0 + w r_1 + w^2 r_2$, and $v_2 = r_0 + w^2 r_1 + w r_2$, regardless of where each $v_k$ appears in $[P]$ or $[P']$. Unfortunately, the $R(\cdot)$ vector doesn't suffice to capture this invariance; and $C(\cdot)$'s dependence on the distinguished vertex doesn't help matters.
$R(\cdot)$ and $C(\cdot)$ aren't entirely useless, however. The moduli, $|r_k|$, which yield the radii of the regular components, are invariants for the polygons.
Edit 2. Perhaps my $C(\cdot)$ provides a workable, comparable, characterization, after all ... with the caveat that we don't require equality between $C(P)$ and $C(Q)$ for congruent $P$ and $Q$, but, rather, an appropriate notion of equivalence.
To incorporate the feature point, we'll assume that our polygons are positioned with feature point at origin; the translational component, $P_0$, then becomes significant, so we won't suppress the corresponding element from $C(\cdot)$.
Let $r = C(P) = \frac{|u_0|}{u_0}(r_0, r_1, r_2, \dots, r_{n-1})$ and $s = C(Q) =
\frac{|v_0|}{v_0} (s_0, s_1, s_2, \dots, s_{n-1})$ be two $C$-vectors with respect to starting vertices $u_0$ and $v_0$ in polygons $P$ and $Q$, respectively. Define "$r \equiv s$" iff, for all $k$ and some fixed integer $m$, we have $\frac{|v_0|}{v_0} s_k = \frac{|u_0|}{u_0} r_k w^{km}$, where $w = \exp \frac{2 \pi i}{n}$. That is, $|s_k| = |r_k|$, and $\arg(r_k) - \arg(s_k) + 2 \pi k m/n \equiv \arg(u_0) - \arg(v_0) \mod 2 \pi$. (I suspect there's a cleaner way to express this.) Then $P \cong Q$, with compatible feature points, if and only if $C(P) \equiv C(Q)$. (If we don't need feature points, we can position our polygons with their average-of-vertices centroids at the origin and suppress the $0$-th components of $C(\cdot)$.)
With this, we just need to determine the best way to measure the degree of non-equivalence for incongruent figures.
Comment: Given that the OP has apparently allowed the feature point to be any interior point in the polygon, if you add it to the polygon as a distinguished vertex, you will end up with a non-convex polygon. As a result, there may not be a unique counter clock-wise ordering of the vertices. Won't that be a problem? Alternatively, if you deal the featured point separately from the polygon, you have to choose a distinguished vertex of the polygon in such a way that you always choose equivalent vertices in congruent polygons.
Comment: @Eric: I would have the distinguished vertex take the place of an interior feature point, since the distinguished vertex (and preferred tracing direction) is (are) all you really need to achieve a workable correspondence between convex polygons. If it's absolutely necessary to consider a separate feature point, one could, say, append to $R(P)$ (and normalize in $C(P)$) the value $f-c$, where $f$ and $c$ are the complex numbers associated to the feature point and (average-of-vertices) centroid; such appended components would match for congruent figures, and be close for nearly-congruent ones.
Comment: @Eric: One can actually do a decomposition of the polygon-plus-feature-point figure into "sum" of symmetric versions of that figure, as I did with polygons alone. The collection of symmetric figures is slightly different than before, however. I think you get "$\lbrace n/k \rbrace$ polygon plus origin" for $k\ne 0$, but the counterpart of $P_0$ is different, and there's a brand new component; they're the "spectral realizations" of the wheel graph. (Here's info on such realizations: http://daylateanddollarshort.com/math/pdfs/spectral.pdf) We then encode the shape in a complex vector as before.
Comment: @Don: If you add the feature point as a vertex, it is arbitrary between which two vertices you put it. So you must choose a second vertex. If you treat the feature point separately, you must choose a first vertex for your polygon. Unfortunately, cyclic re-orderings of vertices change your $C(P)$. For example $P=(\sqrt{2},e^{i\frac{3\pi}{4}},e^{i\frac{5\pi}{4}})$ and $P'=(e^{i\frac{3\pi}{4}},e^{i\frac{5\pi}{4}},\sqrt{2})$ are the same polygon, but $C(P)\neq C(P')$. So either way, you need to choose a first(second) vertex in a way that you always choose equivalent vertices in congruent polygons.
Comment: @Eric: I don't have a complete solution to OP's question, so I'm just offering partial solutions that might be helpful. It's true that my $C(P)$(s) is (are) not invariant under cyclic permutations, which is a problem. That said, it *is* (almost-always) possible to unambiguously identify the necessary distinguished vertex: take the 1st vertex counter-clockwise from where the perimeter is met by the ray from the centroid ($c$) through the feature point ($f$). Although (again) an imperfect soln ($c = f$ isn't covered), it makes my $C(P)$ an intrinsic property, rendering cyclic re-ordering moot.
Comment: I've only now gotten time to look over your answer briefly, and I find it full of interesting ideas. I will have to think about this more, but you are likely onto an answer I can work with. I like the way your solution is sort of a moment/Fourier decomposition.
Comment: @Victor: "Fourier decomposition" isn't far off. My soln derives from two facts: (1) any $n$-gon is a "sum" of affinely-regular $(n/k)$-gons, $k=0,1,..,\lfloor n/2\rfloor$; and (2) the affine image of a plane figure is the "sum" of two similar images of the figure, in opposing orientations. Fact (2) is a theorem of Barlotti, which extends to any dimension. (See http://daylateanddollarshort.com/math/pdfs/extendedbarlotti.pdf ). Fact (1) comes from Fourier-esque investigation of eigenmatrices of a polygon's adjacency matrix. (See "Spectral" paper in prev comment.) These facts apply to any graph.
Comment: @Eric (and myself): My method of "unambiguously identify[ing] the necessary distinguished vertex" is sensitive to perturbations of the feature point, which makes it problematic for comparing nearly-congruent polygon-plus-feature-point figures. Suppose, for instance, that $P$ is a polygon with centroid-feature-point ray that meets a vertex, $v$, which would be named $P$'s starting vertex; if $Q$ is an identical polygon with feature point nudged epsilon-slightly counter-clockwise from $P$'s, then $Q$'s ray misses the vertex $v$, so that the "next" vertex becomes $Q$'s starter. So much for that.
Comment: @Don: You may want to look at the second and third section of my answer. Section two is a very simple approach to selecting a distinguished vertex. Section three is an more complete (but not quite finished) version of the centroid approach to selecting a first vertex. You are right the centroid approach is a bit unstable. It is also very complicated to apply to all cases.
Answer: You might explore the Fréchet Distance.
In any case, here is a useful survey paper:

"Shape matching: similarity measures and algorithms,"
Remco C. Veltkamp
SMI '01 Proceedings of the International Conference on Shape Modeling & Applications, 2001.

And here are two references specifically on convex polygons:

"Optimal matching of convex polygons,"
Pedro Coxa, Henri Maitrea, Michel Minouxb and Celso Ribeiro.
Pattern Recognition Letters
Volume 9, Issue 5, June 1989, Pages 327-334.
"A simple algorithm for the unique characterization of convex polygons,"
P.K Harveya.
Computers & Geosciences
Volume 7, Issue 4, 1981, Pages 387-392.

(I see that the latter paper was already linked by PEV.)
Answer: Perhaps this(article about characterizing convex polygons) will help.
Comment: I already saw that paper. It only uses the ratio of moments to characterize the overall shape, which is not unique.
Comment: The link to `sciencedirect.com` is broken. I'm also unable to find any snapshot saved on the Wayback Machine.


Does this drumming technique have a name?

Question: I just discovered the track "I Got The..." by Labi Siffre and am blown away by it. One quite appealing technical detail is around the 3.25 mark the drummer starts repeating a kind of two bar sequence where each of the two bar sequences starts with a small maybe syncopated flurry and the start of the next bar gets maybe an extra off beat snare hit or something. Is there a technical term for this pattern ? It sounds great anyway.
Link to track on youtube:
Comment: the little flurry is a drag.
Comment: Sounds more like a simple single-handed roll or a buzz (dead) stroke.
Answer: As b3ko already said in the comments, the "syncopated flurry" is a drag. It consists of hitting twice quietly with the left hand right before a note in the right hand (for right-handed people), as this guy explains. In this case, the left hand notes are snare, and the right hand note is hi-hat + kick drum, the first beat of the bar.
As for this part:

the start of the next bar gets maybe an extra off beat snare hit or something

there is not such thing IMO, the next bar is very "well behaved", so I think the pattern we are seeing here is just the drag.
Comment: there is that little open hit hat, syncopated snare action before the end of the second bar, maybe that is what the OP means??
Comment: Extra snare at 3.54 for example, extra open high hat at 4.06, several other occassions where i think there are additional less obvious differences.
Comment: @user467257 Aah, I see. It's between beat 4 and beat 1, in the second bar after the drag. Anyway, I don't think it's part of a pattern, nor has a name.....


Why is css transition not working when adding class using javascript / jQuery?

Question: I have a message box which I want to slide down on click. I do this by adding a css class through Angular (and jQuery in my example). But my CSS transition does not take effect.
Is there any obvious mistake I'm doing?
Here's my fiddle: http://jsfiddle.net/mBKXn/
and my code:
// jQuery
$('.test').on('click',function(){
  $('#msgContainer').toggleClass('msgShow');
});

// HTML

Message here

T2

T4

    Test text

<button class="test">Click</button>

// CSS
.container{
    position: relative;
    height: 200px;
    width: 400px;
    border: solid 1px #222;
}

.msg{
    position: absolute;
    top: 0;
    background-color: #FEEFB3;
    height: 0;
    width: 100%;
    overflow: hidden;
    -webkit-transition: height 0.8s linear;
    -moz-transition: height 0.8s linear;
    -o-transition: height 0.8s linear;
    -ms-transition: height 0.8s linear;
    transition: height 0.8s linear;
}

.msgShow{
    height: auto;
}

Comment: possible duplicate of [CSS transition height: 0; to height: auto;](http://stackoverflow.com/questions/3508605/css-transition-height-0-to-height-auto)
Comment: possible duplicate of [jQuery duration for toggleClass issue](http://stackoverflow.com/questions/6817233/jquery-duration-for-toggleclass-issue)
Answer: you need to set a defined height. Height:auto won't work as this is the default height value.
see the specs for the height property here:
http://www.w3.org/TR/CSS2/visudet.html#the-height-property
http://jsfiddle.net/mBKXn/7/
.msgShow{
    height: 100%;
}

Comment: you could set the height to 100%
Comment: I tried, but it filled the entire div. But, if I set a max.height, using 100% works perfectly :) Fiddle: http://jsfiddle.net/mBKXn/8/
Answer: To animate height from 0 to auto you have to use max-height instead:
.msg{
    position: absolute;
    top: 0;
    background-color: #FEEFB3;
    max-height: 0;
    width: 100%;
    overflow: hidden;
    -webkit-transition: max-height 0.8s linear;
    -moz-transition: max-height 0.8s linear;
    -o-transition: max-height 0.8s linear;
    -ms-transition: max-height 0.8s linear;
    transition: max-height 0.8s linear;
}

.msgShow{
    max-height: 1000px;
}

Seems to work: http://jsfiddle.net/mBKXn/3/
Also take a look at this question.
Comment: This does work, but it's problematic because once the max-height value exceeds the height, there are no further *visual* changes even though the browser continues "animating". When you click again, there's a noticeable pause while the value animates *down* to the actual height.
Comment: `max-height: 100%;` should be enough ;)  http://jsfiddle.net/mBKXn/6/ But Pointy makes a good point
Comment: @A.Wolff yes but that's 100% of the *parent* element height, so you still get the pause when toggling back to 0.
Comment: @Pointy ya, that's correct and can be an issue. Do you know how to solve it?
Comment: Yes, it's true. So when using this method, one should set reasonable max-height (not 1000px like in my example) to reduce animation delay on back toggle.
Comment: I set the max-height in `.msg` and height: 100% in `.msgShow` and it works great. Even with a very long list, it does not take extra time to slide up. See fiddle: http://jsfiddle.net/mBKXn/9/
Comment: I can't think of anything better, but I'm really bad at CSS transform puzzles.
Comment: @Steven but you set `max-height: 100px`. This is not the same as `auto`.
Comment: @Pointy Doesn't work for me Chrome 31.0.1650.63, Linux.
Comment: @Pointy you give me the idea of animating top instead (if element height < container height): http://jsfiddle.net/mBKXn/10/  PS: damn, still not really working :(
Comment: @dfsq transform should be vendor prefixed but i'm unable to make it works either
Comment: Yes it probably needs a vendor prefix. The reason "transform" is useful is that percentages in the "translateY()" function are relative to the *element* bounding box. Both "top" and "margin-top" have the problem of percentages being relative to something else.
Answer: Another (older IE compliant) way to do this is through slideToggle.
Updated Fiddle that works  and another Fiddle where I removed some of your transition css and it makes the animation smoother in my opinion.
your code needs a slight change:
$('.test').on('click',function(){
  $('#msgContainer').slideToggle('slow');
});

and your class needs a slight change:
.msg{
    display:none;
    position: absolute;
    top: 0;
    background-color: #FEEFB3;
    height: auto;
    width: 100%;
    overflow: hidden;
}

Comment: He's doing a css transition from height `200px` to height `auto` (`auto` is the cause)
Comment: Wrong. I'm using CSS transition which is the animation. As both Kevin and Kasper points out, css transition does not work with `auto` height.


Show that the product of nonzero elements of $\mathbb Z_p$ ($p$ prime) is nonzero.

Question: This is the second part of an assignment in which the first part was the following:
Show, if $n \in \mathbb{N}$ is not prime, then there exists $[a],[b] \in \mathbb{Z}_n$ such that $[a] \neq [0] \neq [b]$ , but $[a] \cdot [b] = 0$.
Now, I solved this pretty easily by letting $n = ab$ and moving on from there.  But I really have no idea how to approach the problem in the title, namely: Show that the product of nonzero elements of $\mathbb Z_p$ ($p$ prime) is nonzero.  I know that $p$ can only be an odd number or 2, but I'm not sure if that's relevant here.  Should I prove it in two cases, one where $p$ is odd $(p = 2k + 1)$ and one where $p = 2$?
I know that the statement is clearly true, and it is especially obvious when you draw out a multiplication table of $\mathbb{Z}_p$.  But I just don't know how to translate that into a formal argument here.  Any help is appreciated, thank you!
Comment: Look up Euclid's lemma
Comment: This is, arguably, the most important property of primes.
Comment: Do you already know that $[a][b]=[ab]$ in $\Bbb Z / n \Bbb Z$?
Answer: You do not have to consider separate cases for $2$ and odd primes.
According to Euclid's lemma, if a prime integer $p$ divides the product of integers $a$ and $b,$
then $p$ divides $a$ or $b$ (or both).  In symbols, $p|ab\implies p|a \lor p|b.$
(This is not necessarily the case for a composite integer;
for example, if $a,b>1$ and $n=ab,$ then $n$ divides $ab,$ but $n$ divides neither $a$ nor $b$.)
Stated in modular arithmetic, if $ab\equiv0 \pmod p,$ then $a$ or $b\equiv0 \pmod p.$
The contrapositive also holds:  if $a\not\equiv0$ and $b\not\equiv0\pmod p$, then $ab\not\equiv0 \pmod p.$
That is, $\mathbb Z/p\mathbb Z$ is an integral domain (has no non-zero zero divisors; has the cancellation property).
Comment: any finite domain is a field, so $\mathbb Z/p\mathbb Z$ is actually a field, where non-zero elements have multiplicative inverses
Comment: Thank you, this is very helpful!
Comment: You're welcome!


What is the preferred order of practicing Bach Sonatas and Partitas for solo violin?

Question: As a violinist, it's always been hard for me to come up with an order of practicing Bach Sonatas and Partitas (BWV 1001-1006).
I also know that it's not all about playing, and expression is the key to playing (especially) Bach pieces.
So please:

Guide me through each of these 6 Sonatas and Partitas by their parts and tell me their challenges individually (regarding expressions and techniques, ideally by separation of bow and fingering).
Present a practice (or possibly performance) order by which I can make my way.
Answer:
What is the preferred order of practicing Bach Sonatas and Partitas
  for solo violin?

There was a similar thread many years ago on Violinist.com.
This response was the most helpful and comes closest to answering the relative difficulty part of your question:

The Royal Conservatory of Music Violin Syllabus (1999 edition) lists
  the solo Bach pieces by grade, as follows:
Grade 8:
Partita number 2 in d minor--Giga
Partita number 3 in E major--bouree or Minuets I and II or Gigue
Grade 9:
Partita number 1 in b minor--courante
Partita number 2 in d minor--Allemande or Corrente or Sarabanda
Partita number 3 in E major--Gavotte and Rondeau
Sonata number 1 in g minor--adagio
Sonata number 3 in C major--Allegro assai
Grade 10:
Partita number 1 in b minor--Allemande and Double or Sarabande and
  Double or Tempo di bourree and Double
Partita number 3 in E major--Preludio or Loure
Sonata number 1 in g minor--Siciliana or Presto
Sonata number 2 in a minor--Andante or Allegro
Sonata number 3 in C major--Adagio or Largo
Performer's ARCT:
Partita number 2 in d minor--Chaconne
Sonata number 1 in g minor--Fugue
Sonata number 2 in a minor--Fugue
Sonata number 3 in C major--Fugue
Comment: I want to know challenges regarding to each part too.
I was also aware of this thread on that site, but thanks anyways
Comment: Nathan Cole, First Associate Concertmaster of the LA Phil, has been working through some of these works on his YouTube channel (https://www.youtube.com/user/natesviolin/videos) and Facebook page under the generic title "Bach on the Road" on Mondays, Wednesdays, Fridays at 2pm Pacific. As part of what he does he goes through some of the challenges these pieces present and how to tackle them. Next one (C Major fugue) starts in 5 minutes as a livestream.


How do I use the onBeforeUnload event with Script#?

Question: I'm using the Script# library with ASP.NET. I want to listen and respond to the onBeforeUnload browser event.
I am currently intercepting the event like this:
Window.AttachEvent( "onbeforeunload", OnNavigateAway );
...
private void OnNavigateAway()
{
    Script.Alert("You're leaving.");
}

But the second parameter to Window.AttachEvent is a DOMEventHandler, which has a return type of void. To use the onBeforeUnload event, I need to be able to return a string value, which the browser uses as the confirmation message.
Is there any way to do this without emitting a script literal or hand coding JavaScript? I would really prefer to stay in the compiled C# -> JavaScript as much as possible.
In case it matters, I'm using version 0.5.5 of the Script# library, which isn't the latest version, but I am restricted to this for now.

UPDATE: DuckMaestro answered my question perfectly, but it still didn't work for me. It is the correct answer to my question in that the compiled JavaScript is exactly what I was expecting and wanting. But it doesn't have the desired effect of causing the browser to issue a warning prompt.
I do have a work-around, though, in case someone else stumbles across this answer and wants to know how I initially hacked it into working. Instead of this:
public delegate string BeforeUnloadDelegate();
...
Window.AttachEvent( "onbeforeunload", (DOMEventHandler) (Object)
    new BeforeUnloadDelegate(OnNavigateAway) );

I did this:
Script.Literal( "window.onbeforeunload = this._onNavigateAway" );

This is bad form for a number of reasons. This will only work on the .debug.js class that Script# generates; Script# changes the names in the release version, so the script emitted by the Script.Literal statement won't match up. Also, it negates a lot of the benefits of using Script# in the first place. (For example, using Visual Studio's refactoring tools to rename OnNavigateAway to something else will leave an orphaned reference in the string.) Also, the C# code declares the method as OnNavigateAway, whereas the Script.Literal has to refer to this._onNavigateAway.
Still, if, like me, you're on a deadline and looking for a hack, this is a place to start. If I make any more progress on a more correct version, I'll update this question with the details.
Thanks again to DuckMaestro for answering the question I asked.
Answer: I would declare a new delegate type
public delegate string BeforeUnloadCallback();
and then change your attachEvent code to
Window.AttachEvent( "onbeforeunload", (DOMEventHandler)(Object) new BeforeUnloadCallback(OnNavigateAway) );
I'm not positive that will work on 0.5.5, but it's the kind of trick I use from time to time in 0.6.x.
Comment: Wow, neat trick! That emitted exactly the Javascript I was looking to emit. The return value still isn't being interpreted by the browser, but I suspect strongly the issue is with the way AttachEvent is called by Script#. I'll keep looking for an answer. Thanks so much for your help, though -- that will come in handy down the road!


Decrease the memory of my app

Question: I am almost finished with my first app (long way but fun times)
I am trying for a week to decrease my memory usage of the app but if that does not work i want to make sure it dealloc's a view after its been used but i see that that doesnt happen...
I dont have a memory issue with the searchviewController its more the DetailsViewController that uses 100 mb ram.
I will try to show how my app is build up in a summary:
Searchview controller

The main screen --> UIViewController with tableview

in the didSelectRowAtIndex i have:

    DetailsViewController *controller = [[DetailViewsController alloc]initWithNibName:@"DetailsViewController" bundle:nil];

    SearchResult *searchResult = [searchResults objectAtIndex:indexPath.row];
    controller.searchResult = searchResult;

DetailsViewController

The details screen, is called when select a row, its a UIview that has a subview (a custom scrollview) the custom scrollview has the icarousel (custom uiview)
.h

@property (nonatomic,weak) SearchResult *searchResult;

.m

@property (nonatomic, retain) iCarousel *carousel;
@property (nonatomic, retain) UINavigationItem *navItem;

Implementation:
    MGBox *tablesGrid, *table1;

ViewDidLoad:
//Add barButton
UIBarButtonItem *reactButton = [[UIBarButtonItem alloc]..];
carousel = [[iCarousel alloc] init..];

//Add Tablesgrid
tablesGrid = [MGBox boxWithSize:tablesGridSize];
tablesGrid.contentLayoutMode = MGLayoutGridStyle;
[self.scrollview.boxes addObject:tablesGrid];

//Add Table
table1 = MGBox.box;
[tablesGrid.boxes addObject:table1];

after this i have functions that add the searchResult to a label and fill the icarousel (that has max 6 items), icarousel is a uiview that i added as a subview to scrollview etc..
When i push back on the navigationBar and go back to the main view controller it doesn't dealloc the view, why ? (nslogged the dealloc but is never called). After memory warning it calls the ViewDidUnload and makes some memory free but still no dealloc....
I have no reference to other objects right ? except for the searchResult but i set it on weak so it should not be a reference right ?
Some info:
After a search on the mainview i have :
Live bytes: 5,75 mb Living: 27.342  Transistory: 68.200 Overall
   bytes: 25.30 mb
After selecting a row and going into the detailsViewController i have:
Live bytes: 5.4 mb
Living: 32.498
Transistory: 76.488
Overall bytes: 29.55 MB
After dragging the subview row of icarousel (watching the pictures):
Live bytes: 5.5 mb
Living: 32.798
Transistory: 122.850
Overall bytes: 36.41 MB
After selecting some tables in the custom table view
Live bytes: 5.7 mb
Living: 33.508
Transistory: 161.80
Overall bytes: 40.12 MB
after opening a link in app and going back (opens in modal view and dismiss it again)
Live bytes: 6.7 mb
Living: 43.821
Transistory: 371.761
Overall bytes: 144.95 MB
After clicking on the pictures and make the photos in fullscreen and coming back in detailscreenview again (opens modal and dismiss)
Live bytes: 6.76 mb
Living: 43.798
Transistory: 400.850
Overall bytes: 155.69 MB
And if i go back to another row it never gets less it just adds
Dont be to hard on me or just shut the topic down for no reason..
Give me some tips or advice or if you dont know what the "problem" is just explain me what these are:
Live Bytes - #living - #Transitory - Overall Bytes - # Overall
And i would like to thank this website for all the information that it has because without it i would never got so far
Answer: In answer to your question:

You said "when I push back" on the navigation bar. I hope you meant that you "popped" back. You push to go to a secondary controller/scene. You pop to go back. See popViewControllerAnimated. Likewise, every time you presentViewController, you should have an associated dismissViewControllerAnimated.
If using storyboards, make sure you don't have circular segues in your storyboard (e.g. segue from A to B and another from B to A). See memory not releasing with ARC and storyboard in iOS 5.1 for a brief discussion on this topic.
The other possibility is a "strong reference cycle" (a.k.a. "retain cycle"). See the Advanced Memory Management Programming Guide. Anything that could be maintaining a strong reference to your controllers could cause this problem. Less obvious examples include things like repeating NSTimer objects.

Update:
Some general counsel regarding memory management

If you're having memory issues, you should always run your code through the static analyzer. This is especially important if you don't use ARC, or if you use any Core Foundation calls, but it's generally a good first step when encountering any memory issues.
See Finding leaks with Instruments for guidance on how to use Instruments to find leaks in your app.
Sometimes, when you have a spike in memory allocations, it's useful to determine what's causing the spike. For specific advice how to go from you allocations, to a more meaningful analysis of the source of those allocations, see point #4 of this Stack Overflow answer. In short, highlight one of your unexplained jumps in allocations, set the bottom window to show you the call tree, hide system libraries, and see in which of your routines the memory is being consumed.
Comment: i didnt use storyboard...is it a good idea to refactor everything to storyboard ?
Comment: @user1876006 No, not necessary. But the same principle applies with NIBs. If you push from A to B, you just need to make sure you never push from B to A, but rather that you pop from B back to A. This is the logical equivalent to making sure that one's storyboard doesn't have circular references. I've tried to clarify my answer.
Comment: the navigationbar that i added in the appDelegate "makes" the back button, i assume thats popping the view or not ?
Comment: @user1876006 Yes, if you're just tapping on the system generated "back" button, then you're popping fine. If you added your own manual button that does `pushViewController` or `presentViewController`, then that's problematic. FYI, I've added some additional general counsel for (a) analyzing code; (b) finding leaks; and (c) identifying allocations (if, for some reason, you were unsure as to what they were being caused by).
Comment: i will read the things you posted and try to find the answer why it doesnt dealloc ! tnx m8!

Decrease the memory of my app


Calculate the duration from the table which has logon time and logoff time as different rows

Question: I have a table(ADR) with agent login information. It has a row for each time agent is logged on or logged off. An agent can login and log off multiple times a day. EventID =11 means logged on and eventid=21 means logged off. The output required is a single row for every logon and logff with the logon and logoff time and duration. If the first event of the day is logged off that means agent has logged on the previous day and logged off today. So the duration would be calculated from the beginning of the day to the time he logged off. Similarly, If the last event is logged on that day, duration is calculated from that time till the end of that day.
Data:

I tried to use case statement and then select only the rows that are needed. Haven't fully developed the query yet. Posting what I was going to try.
select a.AgentID,a.QueueID,case when a.rownum =1 and  a.laststateduration=0 then a.EventTime
                        else when a.rownum =1 and a.laststateduration<>0  then CAST(CAST(a.EventTime as date) as datetime) end as LogonDatetime,
                        case when a.rownum=1 and  a.laststateduration=0
then a.EventTime ....
from (select *,ROW_NUMBER() over (order by EventTime asc) as rownum from ADR
where EventID in (11,21)
and convert(date,EventTime) = '2021-02-02'
and AgentID =1006
and QueueID in (6017,6018)) a

Comment: @DaleK It was never mentioned that I had to put what I had tried in the guide lines or atleast I didnt know since I'm posting for first time. You could definitely ask me if you want me to make it clear for you.
Anyway I have updated my post.
Comment: its all here https://stackoverflow.com/help/how-to-ask
Answer: This problem becomes much harder if the logins and logout are not fully interleaved.  Assuming they are, I might suggest lead() and filtering:
select t.*,
       datediff(second, eventtime, next_eventtime) / (60.0 * 60) as decimal_hours
from (select t.*,
             lead(eventtime) over (partition by agentid, queueid order by eventtime) as next_eventtime
      from t
      where eventid in (11, 21)
     ) t
where eventid = 11;

Comment: Thanks a lot for sharing this. I didn't get the expected result. But with the lead function i can see how to achieve my result.
Comment: @Krish . . . You can set up a db<>fiddle of some sort.  I'm not sure what your "expected' result is, but this should be doing what you want.
Comment: @GordanLinoff, Sorry if I wasn't clear in the question. With your solution I can only achieve last 2 rows but not the first row in my output. But thank you for your answer, I understood lead and lag functions and modified your answer a bit to get what I wanted.
Comment: I'm not sure where to post my answer so I edited yours. Let me know if that is ok. If not, Kindly tell me where I can post my answer
Comment: @Krish . . . If the solution is based on this solution, you should add the a note such as "EDITED by OP" and add your additional comments and codes after that.  You probably shouldn't change the code that is there, other than to fix typos and the like.
Answer: I would write it in below manner if environment is suitable for temp table.
if object_id('#temp.#Rep') is not null drop table #Rep
Select O.AgentID, O.EventTime as Logon,
(Select Top 1 EventTime from ARD i where i.AgentID = O.AgentID and i.EventTime > o.EventTime and i.EventID=21 Order By i.EventTime) as Logout,
Into #Rep
 from ARD O
where EventID = 11

select r.*,
(case when Logout is not null then datediff(second, Logon, Logout) else 0 end) as DurationSecs
from #Rep r

Answer: No matter the proposed solution you need to handle cases where people leave without logging off (leave workstation open, crash, plug pulled...), multiple login log off that overlap. So, I would loop through the records and use a small FSA for each user with two states (logged in / logged off) and the state transition caused by a login, logout event, timeout. Along with the event the time information is important (what to do with a lift or timeout that happens after hour.
Unless, you have a perfect system, whatever quick query or whatever won't cut it. I have gone through this a couple of times handling the exact same problem.
Comment: Thanks a lot for the information. I'll keep that in mind. In my case, this is not a problem as the agents will be logged off after a threshold.
Answer: I built up on the solution by Gorden Linoff. Used if condition to check if the first row is logon/logoff and used LAG function with default value to get the logon time and similarly used LEAD function with default value to get logoff time. Finally removed duplicates using where condition.
select a.*, datediff(second, a.Logon, a.Logoff) as Duration
from (
                select  AgentID, QueueID,eventid, iif(eventid =21, lag(eventtime,1, cast(cast(EventTime as Date) as datetime)) over (partition by convert(date,EventTime),agentid, queueid order by eventtime),
                                    EventTime) as logon ,
                                iif(eventid =11, lead(eventtime,1,DATEADD(Minute, -1,cast(cast(EventTime+1 as Date) as datetime))) over (partition by convert(date,EventTime),agentid, queueid order by eventtime),
                                    EventTime) as Logoff
                from ADR
                where eventid in (11, 21)
        ) a
where a.eventid =11 or (a.eventid =21 and CAST(a.logon as time)='00:00:00.0000000')


divide a web page to two pages

Question: I know how to divide a web page using
s
, but I want each divided section to have its own back and forward and address bar. Is it possible? How can I do that?
Comment: So... You want to add a browser inside a div?
Comment: Oh dear, no, I was being a bit silly to be honest. I don't know what you need a browser in a browser for, but I'd advise against it - or, use iframes as I suggested in my answer.
Comment: ok, how I can have two browsers in one page?
Comment: If you use Firefox, then chrome://browser/content/browser.xul
Comment: I use IE 7. Is it possible for that?
Comment: let's explain more maybe you have a better solution for me. I have number of buttons in my page. when one of them is clicked a webpage should be displayed. I want this webpage be displayed in the same page that the button exits.
Answer: You can't do it using one physical web page and have 2 sets of the browser's default controls, no.
You could create two HTML pages, each representing half the original page and then display them in two browser windows, sized identically and positioned adjacent to each other.
Otherwise use - ugh - iframes!
EDIT: If you really want a browser in a browser, then open Firefox and visit
chrome://browser/content/browser.xul
Comment: I use IE 7. Is it possible for that?

divide a web page to two pages


Relationship between negative binomial distribution and Bayesian Poisson with Gamma priors

Question: I am studying the negative binomial distribution and it seems it models overdispersion in a poisson process using a gamma distribution (a mixture or something, but I may be wrong).
In parallel, I am studying about Bayesian inference and it caught my attention that when modelling a Poisson process the prior is drawn from a gamma distribution. From my beginner understanding Bayesian statistics are particularly useful to study cases with overdispersion (few observations). Hence, I was wondering whether there is a relationship between the neg-bin distribution and the Bayesian modelling of a Poisson process. I am just trying to get a deeper understanding. Thanks!
Answer: (Note that in the following I am quite careful about when to use capital $\Lambda$ and when to use lower-case $\lambda$, and when to use capital $X$ and when to use lower-case $x$.)
Suppose the distribution of $\Lambda$ is the Gamma distribution:
$$
\frac 1 {\Gamma(\alpha)} \left( \frac \lambda \beta \right)^{\alpha-1}  e^{-\lambda/\beta} \left(\frac{d\lambda}\beta\right).
$$
And suppose the conditional distribution of $X$ given $\Lambda$ is the Poisson distribution
$$
x \mapsto \frac{e^{-\Lambda} \Lambda^x }{x!} \text{ for } x = 0,1,2,3,\ldots
$$
Then you have
\begin{align}
& \Pr(X=x) \\[10pt]
= {} & \operatorname{E}(\Pr(X=x \mid \Lambda)) = \operatorname{E}\left( \frac{e^{-\Lambda} \Lambda^x}{x!} \right) \\[10pt]
= {} & \int_0^\infty \left( \frac{e^{-\lambda}\lambda^x}{x!} \right)  \frac 1 {\Gamma(\alpha)} \left( \frac \lambda \beta \right)^{\alpha-1} e^{-\lambda/\beta} \left(\frac{d\lambda}\beta\right) \\[10pt]
= {} & \frac 1 {x!\Gamma(\alpha)\beta^\alpha} \int_0^\infty \lambda^{x+\alpha-1} e^{-\lambda(1\,+\,1/\beta)} \, d\lambda \\
& \qquad \qquad \text{(We pulled out the factors that do not depend on $\lambda$).}\\[10pt]
= {} & \frac 1 {x!\Gamma(\alpha)\beta^\alpha} \cdot \left(\frac \beta {\beta+1} \right)^{x+\alpha} \int_0^\infty \left( \lambda \left( 1 + \frac 1 \beta \right) \right)^{x+\alpha-1} e^{-\lambda(1+1/\beta)} \left( d\lambda \left( 1 + \frac 1 \beta \right) \right) \\[10pt]
= {} & \frac 1 {x!\Gamma(\alpha)\beta^\alpha} \cdot \left(\frac \beta {\beta+1} \right)^{x+\alpha} \int_0^\infty u^{x+\alpha-1} e^{-u} \, du \\[10pt]
= {} & \frac {\Gamma(x+\alpha)} {x!\Gamma(\alpha)\beta^\alpha} \cdot \left(\frac \beta {\beta+1} \right)^{x+\alpha} \\[10pt]
= {} & \frac {\Gamma(x+\alpha)} {x!\Gamma(\alpha)} \cdot \left( \frac 1 {\beta+1} \right)^\alpha \left(\frac \beta {\beta+1} \right)^x
\end{align}
and this is a negative binomial probability mass function with $p$ and $q$ equal to $\dfrac 1 {\beta+1}$ and $\dfrac\beta{\beta+1}$, not necessarily respectively (depending on which convention you follow). This is the probability that the number of failures before the $\alpha$th success is $x$, when the probability of success on each independent trial is $1/(\beta+1).$
So a Gamma mixture of Poisson distributions is a negative binomial distribution, and that is the connection between Poisson and negative binomial.
Comment: Thanks to both, Student T and Michael Hardy! So, could we say that the negative binomial is both a frequentist approach and a Bayesian approach? Could we say that in this case frequentist and Bayesian approaches match each other?
Comment: @Federico : A mere probability distribution is not Bayesian or frequentist, even if it is used more often in one of those approaches than the other. Bayesianism is about assigning probabilities to everything that is uncertain, regardless of whether it is random. The probability that there was life on Mars a billion years ago may be $0.6$ regardless of whether it is true in $60\%$ of all cases.


Can I Read/Write google spreadsheets using GET/POST methods

Question: I want to know is it possible to read/write google spreadsheets using GET/POST methods with UIWebView?
Answer: There are two Google API's that might interest you:

Google Spreadsheets - Used read/manipulate spreadsheet data
Google Documents - To create/organize documents (spreadsheets)

Unless you actually want to display a web page, I would advice against using UIWebView. HTTP requests against API's are usually made using NSURLRequest and NSURLConnection. They give you complete control over the request and response handling.
While a custom implementation written yourself against the documents/spreadsheets API could suffice, most Google API's are an implementation of the Google Data protocol. This protocol has multiple libraries available that take care of the actual implementation on top of NSURLRequest.
A client library and sample code is available to access the spreadsheets API using Objective-C.
Comment: I could not find anything on Accessing google docs using objective c using the link you have provided.


How to download base64 pdf files from website on iOS

Question: I'm struggling with this issue that I can download documents on chrome but not on iOS devices
Whenever I try, I get "Not allowed to navigate top frame to data URL" error.
Is there a way to do this with JS?
Extra question:
Is getting base64 encoded pdf to client and then downloading is a good solution or do you have any other suggestions? Please bear in mind that there are a lot of documents so adding every doc to assets is not possible.
I tried the code below and it worked on desktop devices but not on iOS.
<code>        const a = document.createElement("a");
        a.href = "data:application/pdf;base64,BASE_64_PDF";
        a.download = "file.pdf";
        a.click();
</code>
Comment: I can't test on iOS but maybe if you turn the base64 data URI into a `Blob` object using `fetch` and then download that Blob it may work.
Comment: Thanks for the tip! Found a code that will help me turn it into a blob and then integrated that to my own code. It seems like it works
Answer: So after Danny mentioned Blob, i found a code that helps me to transform my b64 pdf to a Blob (Blob transformation). And it seems like it works on iOS aswell.
<code>   const b64toBlob = (b64Data, contentType = "", sliceSize = 512) => {

    const byteCharacters = atob(b64Data);
    const byteArrays = [];

    for (
      let offset = 0;
      offset < byteCharacters.length;
      offset += sliceSize
    ) {
      const slice = byteCharacters.slice(offset, offset + sliceSize);
      const byteNumbers = new Array(slice.length);

      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      const byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }

    const blob = new Blob(byteArrays, { type: contentType });

    return blob;
  };

  const contentType = "data:application/pdf";
  const b64Data = "BASE_64_DOC";

  const blob = b64toBlob(b64Data, contentType);
  const blobUrl = URL.createObjectURL(blob);

  const a = document.createElement("a");

  a.href = blobUrl;
  a.download = "file_name.pdf";
  a.click();
</code>
Comment: you just have to do a get request with the data URI using `fetch` and get a `Blob` from it, like `fetch(dataURI).then(response => response.blob()).then(blob => /* do something with the blob*/)`
Comment: It's so good you managed to solve it. But with `fetch` it would be much easier. Unless somehow the Content Security Policy of the website does not allow it.
Comment: Hi @Danny can you give a sample code for how to fetch it if you don't mind?
Comment: fetch works great, thanks for the tip, it was exactly what I was looking for. Only downside is it's asynchronous


Porque este servidor está crashando?

Question: from socket import*

Host = "localhost"
Port = 255

sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.bind((Host, Port))
sockobj.listen(5)

while True:

    conexão, endereço = sockobj.accept()
    print('Server conectado por', endereço)

while True:

    data = conexão.recv(1024)

    if not data:break

        conexão.close()

O Python simplesmente trava e não imprime nenhum erro
Comment: Trava sem imprimir erros? será porque o servidor está a funcionar?
Comment: Coloca o codigo todo sff. Qual é o erro?
Comment: Esse é o codigo
Comment: Faltam os imports etc... "localhost is not defined", "ame 'AF_INET' is not defined"... etc
Comment: Ele trava... por bug ou porque está esperando eternamente o cliente enviar uma mensagem? Note que o seu programa trata uma conexão por vez, e como ele fica lá parado esperando, pode ser que você só não esteja percebendo que a falha na verdade está no cliente. Note também que os seus laços não está propriamente identados.. Vc tem um `while` infinito só para aceitar conexões! (e, esse, é provavelmente o seu problema: o seu server aceita a primeira conexão, imprime a mensagem "conectado..." e volta a aceitar conexões, ficando "aparentemente" travado)
Answer: Corrigido, devo começar por dizer que variáveis com caracteres especiais (ç, ã ...) não é de todo aconselhado, e com maiuscula na primeira letra também não é convencional.
Estavas também a fazer dois ciclos while True: sem qualquer break no primeiro, todos sabemos em que é que isto resulta, quando na verdade é apenas no ultimo (segundo) que precisas que fique "eternamente" a rodar, outra coisa que podes fazer é usar context manager, para "abertura das sockets" desta maneira para além de ser atualmente a mais aconselhada, também escusas de fechar as sockets, tal como o seu uso na abertura de um ficheiro:
from socket import*

host = "localhost"
port = 9003

with socket(AF_INET, SOCK_STREAM) as sockobj:
    sockobj.bind((host, port))
    sockobj.listen(5)

    conexao, endereco = sockobj.accept() # esperar ate que cliente se ligue
    print('Server conectado por', endereco)

    while True:
        data = conexao.recv(1024)
        if not data:break

Nota que quando estive a testar um dos erros que me deu foi:

ConnectionRefusedError: [Errno 111] Connection refused

Isto por causa do port que estava a ser utilizado por outro processo qualquer
Comment: Claro @LuizVieira, basta ser de outro país para nem perceber bem aquilo hehe
Comment: no Linux (e provavelmente no Windows também) as portas menores que 1024 podem ser usadas como servidor apenas por processos privilegiados (root, administrator); assim, no exemplo do OP além de todos os erros havia a questão da porta 255 utilizada
Comment: "devo começar por dizer que variáveis com caracteres especiais (ç, ã ...) não é de todo aconselhado [...]". Totalmente verdade. Entre outras dificuldades, pense que alguém que for usar ou dar manutenção no seu código pode não ter um teclado com cedilha (ç).
Comment: exato @JoséX, correto

Porque este servidor está crashando?


Objectify 5 save an embedded List of List or array of arrays?

Question: I'm converting code from objectify 4 to 5.
Previously I was saving an @Entity containing a class that contained
List<List<String>> listOfListOfStrings;

With version 5 I get a SaveException:
com.googlecode.objectify.SaveException:
Error saving com.timmacp.server.OfyEntityClass@3d627804:
listOfListOfStrings: java.util.ArrayList is not a supported property type`

same problem with arrays of arrays.
Here is some code I've used to test, MemberClass just contains a String.
@Entity
public class OfyEntityClass {
    @Id
    private Long ID;
    List<List<MemberClass>> memberClassObjects;
    public OfyEntityClass(){
        memberClassObjects=new ArrayList<List<MemberClass>>(8);
        List<MemberClass> l=new ArrayList<MemberClass>(8);
        MemberClass memberClassObject=new MemberClass();
        l.add(memberClassObject);
        memberClassObjects.add(l);
    }
}

A workaround seems to be to put each List level in its own class, but this seems strange as the docs state that "Many limitations of Objectify4 no longer apply to Objectify5: Nesting of collections of embedded objects is unrestricted."
Update: some of the fields were annotated with @Serialize in the ofy4 version. I'd removed these thinking they were not required in ofy5 so that explains the difference. Still wondering if its possible to do this without @Serialize. Wrapper classes seem to work to simulate a  List<List<String> but not for more complex nesting.
Update 2:
with v5,  won't work with a recursive class? ie if Thing has a field  of type
List<Thing> then (so far) register fails: stack trace looks like infinite repetition of:
    at com.googlecode.objectify.impl.translate.Translators.create(Translators.java:138)
at com.googlecode.objectify.impl.translate.Translators.get(Translators.java:117)
at com.googlecode.objectify.impl.translate.CreateContext.getTranslator(CreateContext.java:27)
at com.googlecode.objectify.impl.translate.CollectionTranslatorFactory.create(CollectionTranslatorFactory.java:38)
at com.googlecode.objectify.impl.translate.Translators.create(Translators.java:138)
at com.googlecode.objectify.impl.translate.Translators.get(Translators.java:117)
at com.googlecode.objectify.impl.translate.CreateContext.getTranslator(CreateContext.java:27)
at com.googlecode.objectify.impl.translate.ClassPopulator.<init>(ClassPopulator.java:88)
at com.googlecode.objectify.impl.translate.ClassTranslatorFactory.createEmbeddedClassTranslator(ClassTranslatorFactory.java:75)
at com.googlecode.objectify.impl.translate.ClassTranslatorFactory.create(ClassTranslatorFactory.java:50)
at com.googlecode.objectify.impl.translate.ClassTranslatorFactory.create(ClassTranslatorFactory.java:36)

Or maybe there's a way to specify the number of recursion levels for the translators?
Answer: Primary Objectify author here.
Objectify4 should not be able to save a field of type List<List<String>>. I can't even imagine what that would do, or why it would work. There are no tests around it. Historically, GAE only allowed storing a simple collection of scalar values in entities. At some point they expanded that by providing EmbeddedEntity, but that is something different. I haven't tried storing a List<List<String>> manually with the low-level api, but if it works, that's something new that Google has not announced nor have they documented it. Nor does there appear to be any way of defining structures like this in GAE/Python (db or ndb).
So I don't know what to tell you. If you tell me you have a working application which stores and retrieves a List<List<String>> field - then this is something new. How long have you had this deployed?
Comment: I just reverted to Objectify4 & checked, yes it does work deployed. Anyway, to save a List of Lists for  Objectify5 I need to  put each List level in its own class and nest these within the enitity?  This is definitely supported?
Comment: First: Your code doesn't do what you think it does. I just added a couple tests around List> in the Objectify v4 branch and no, it doesn't work. I couldn't tell you why your code isn't failing, but I'm quite certain you cannot save and load a two dimensional list.

Second: Yes, with v5, if you have a field of type List and the Thing has a field of type List, it works. You can nest collections indefinitely this way. This only works in v5, not v4. It is supported and documented.
Comment: Can I do this for a recursive class ? (see update 2 above)
Comment: Not at present, but it's certainly a reasonable feature request (and is at least possible). Add it to the github issue tracker?


Google Cloud Storage: Output path does not exist or is not writeable

Question: I am trying to follow this simple Dataflow example from google cloud site.
I have successfully installed the dataflow pipeline plugin and gcloud SDK (as well as Python 2.7). I have also set up a project on google cloud and enabled billing and all the necessary API's - as specified in the instructions above.
However, when I go to the run configurations and change the Pipeline Arguments tab to select BlockingDataflowPipelineRunner, after entering creating a bucket and setting my project-id, hitting run gives me:
Caused by: java.lang.IllegalArgumentException: Output path does not exist or is not writeable: gs://my-cloud-dataflow-bucket
    at com.google.cloud.dataflow.sdk.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:146)
    at com.google.cloud.dataflow.sdk.util.DataflowPathValidator.verifyPathIsAccessible(DataflowPathValidator.java:79)
    at com.google.cloud.dataflow.sdk.util.DataflowPathValidator.validateOutputFilePrefixSupported(DataflowPathValidator.java:62)
    at com.google.cloud.dataflow.sdk.runners.DataflowPipelineRunner.fromOptions(DataflowPipelineRunner.java:255)
    at com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner.fromOptions(BlockingDataflowPipelineRunner.java:82)
    ... 9 more

I have used my terminal to execute 'gcloud auth login' and I see in the browser that I am successfully logged in.
I am really not sure what I have done wrong here. Can anyone confirm if this is a known issue with using dataflow pipeline and google buckets?
Thanks!
Comment: Can you try running `gsutil ls gs://my-cloud-dataflow-bucket` on the command-line? (I'll give a generic answer first, and the follow up with a more specific one once we figure out the root-cause.)
Answer: I had a similar issue with GCS bucket permissions, though I certainly had write permissions and I could upload files into the bucket.
What solved the problem for me was acquiring roles/dataflow.admin permission for the project I was submitting the pipeline to.
Answer: When submitting pipelines to the Google Cloud Dataflow Service, the pipeline runner on your local machine uploads files, which are necessary for execution in the cloud, to a "staging location" in Google Cloud Storage.
The pipeline runner on your local machine seems to be unable to write the required files to the staging location provided (gs://my-cloud-dataflow-bucket). It could be that the location doesn't exist, or that it belongs to a different GCP project than you authenticated against, or that there are more specific permissions set on that bucket, etc.
You can start debugging the issue via gsutil command-line too. For example, try running gsutil ls gs://my-cloud-dataflow-bucket to attempt to list the contents of the bucket. Then, try to upload via gsutil cp command. This will perhaps produce enough information to root-cause the issue you are facing.
Comment: How did you solve the problem ? I am having the same issue, I can `gsutil cp` on CLI but have the error on the Java code side. Thanks.
Comment: Hey Davor. In the gcp storage section ui, I changed both the bucket permissions and default bucket permissions so that owners, editors and viewers all have 'owner' permissions set. I also added a new entry for my specific email address. Via the terminal I executed: gsutil cp somefile.txt gs://my-cloud-dataflow-bucket. I saw that the file was uploaded - so the permissions seem ok. However, when I run my eclipse program, I still get the error: the bucket does not exist or is not writeable :(
Comment: I ran the following commands in my terminal:
Your current project is [rosh-test].  You can change this setting by running:
  $ gcloud config set project PROJECT_ID
Roshs-MacBook-Air:~ RoshPlaha$ gsutil ls gs://my-cloud-dataflow-bucket
AccessDeniedException: 403 Forbidden

I should point out, in the eclipse dataflow plugin, when creating the project, I specified the name of the bucket and then clicked 'create'. Eclipse told me the creation of the bucket was successful. However, when I check on gcp to see if the bucket exists, it says it doesn't.
Comment: Furthermore, when I try to manually create the same bucket - it says that I cant have two buckets with the same name! Whilst in gcp, I started up gsutil and ran: gsutil acl ch -u firstname.lastname@example.com:W gs://my-cloud-dataflow-bucket. However that also gives a 403 forbidden error.
Comment: A few things to check: make sure your account is at least an Editor on the project, don't forget to run `gcloud auth login`. Also, when creating the bucket, make sure the project name is specified. If this fails, I suggest creating the bucket manually in the Developers Console and just using it in Eclipse.
Comment: You seem to have made progress on the issue. Before you were getting 403 for all actions; now you seem to be successfully copying files --> definite sign of progress. Could it be that your Eclipse environment somehow cannot access your home directory and/or command-line environment variables?
Comment: Anyone found solution on this issue, i am also seeing this error.
Answer: Try to provide zone parameter, it works in my case with similar error. And of course export GOOGLE_APPLICATION_CREDENTIALS environment variable before running your app.
 ...
 -Dexec.args="--runner=DataflowRunner \
 --gcpTempLocation=gs://bucket/tmp \
 --zone=bucket-zone \
 ...

Answer: Got the same error. Fixed it by setting GOOGLE_APPLICATION_CREDENTIALS using the key file with write permissions in ~/.bash_profile on Mac.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32038798)
Answer: I realised I needed to use a specific acl command via gsutil. Setting my account to have owner permissions did not do the job. Instead using:
gsutil acl set public-read-write gs://my-bucket-name-here

worked in this case. Hope this helps someone!
Comment: We should not encourage users to set `public-read-write` on their buckets. This is not necessary. Editors of the project needs to have a write access, as well as the service accounts. Then, you need to authenticate as one of the editors, and that should be enough.


Matlab display a variable from function

Question: I'm new to Matlab and I have a function and I need to display a variable from running the main file (but the main file does access the function)...
I have tried to use fprintf(n);
Thanks :)
Comment: This is not very clear - can you give more details?
Comment: @mathematician1975 His question is clear, I am worried about how you interpret questions :/
He needs to display a variable(which has been set) in the console.
Comment: @KarlMorrison I find it unclear but of course you are entitled to your opinion. What do you hope to achieve though by commenting on a comment to a question that has an answer that was accepted over 2 years ago?
Comment: @mathematician1975 Trying to help you become a better person of course! Try and see things from a beginners perspective and not an  elitists perspective, not ruling you out as an elitist but a lot of people (especially from the mathematics community) always need perfectly formulated questions, a dangerous requirement which leads to discouragement. And individuals ask why people hate math for example!
Answer: MATLAB function fprintf() is very similar to fprintf() in C. If your variable n is an integer, then you should do
fprintf('%d\n', n);

An interesting feature is that you can also print multiple numeric values and literal text to the screen. For example
A1 = [9.9, 9900];
A2 = [8.8,  7.7 ; ...
      8800, 7700];
fprintf('X is %4.2f meters or %8.3f mm\n', A1, A2);

where %4.2f takes the element at the first column of A1 and %8.3f takes the second. In the sequence, it repeats for A2 printing its first line and later its second line. The output is

X is 9.90 meters or 9900.000 mm
X is 8.80 meters or 8800.000 mm
X is 7.70 meters or 7700.000 mm

If you want more details about the specifiers you can use with fprintf(), you should give a look at the MathWorks docs.
Comment: You could also use disp()

Matlab display a variable from function


Why won't Android Studio create my AAR file in release mode

Question: Using Android Studio, I have an Android library project which produces 'library/build/outputs/aar/MyLIB.aar" just fine in Debug mode, but does not do so in Release mode. I see no errors, just "BUILD SUCCESSFUL" in the "Gradle Console" window but no Release Mode artifact.
There was a similar question raised here, and I'm getting the same behavior as #user1624552 mentions in the link:
"gradlew clean" followed by "gradlew aR" resultd in my AAR being created and correctly placed in the directory above.  But using Android Studio and the "Release Mode" Build Variant does NOT create an AAR file.
Is there something configured in the Debug variant which is not configured in the Release variant?
Thanks,
ALF
Comment: 1. Are you using ProGuard?
2. If you have a demo app which uses the library, it may have been merged into the final APK
Comment: The following code is from my library's build.gradle file.  There is reference to proguard in the "buildTypes" section, but even after deleting that block I get the same results.  Note also that it says "cannot resolve symbol getDefaultProguardFile' when I hover over that function name.
[code]
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }[/code]
Comment: Ok so ProGuard seems to be off. Check if you can build a release apk of a real app using that library.
Comment: I can't build an app because this won't product an AAR file.  Also I apologies for the lack of formatting but I can't seem to get formatting to work in comments.
Comment: Yeah, but if you build with Studio using a library and a demo app which uses the lib, it should be automatically placed and merged later on into the APK. Maybe create another project with new gradle and try again? If that doesn't do the trick, I have no idea what else to try :/
Comment: Not sure I'm following. I have a library that I can currently build and link with an app that uses it.  I can build that library (.aar) with 'gradlew' on the command line in both debug and release modes without issue.  I can build that library with Android Studio, but only in debug mode -- it will not produce an AAR file using the "Build Variant" of 'release'.  You're saying build a demo app with the library and as you can see I've done that and it works -- except in this one case.  Thus my puzzlement...
Comment: Right, misunderstood that part. Did you maybe raise an issue on Android Studio bug report website? If so, did they respond at all?
Comment: I haven't reported a bug because I'm not yet certain this isn't something I'm doing wrong.
Comment: Yeah.. Update the thread if you find anything from them, it's an interesting problem at least
Answer: Right click the task you want and click "Run".
Answer: To get the aar, you can do the following

"View/Tool Windows/Gradle", to open the gradle window
From gradle window, run assembly Gradle task by double-click on My_Plugin_Android/:My_Plugin/Tasks/build/assemble