File synchronization utility

Question: I'm looking for a file synchronization utility. Currently I'm using SyncToy, which works well most of the time. But on large large folders it get awkwardly slow.
There should be a file share (NAS) and multiple computers synchronize with it. Like a Windows Server.
So this are my requirements:

Should be reliable
Support of large files (~ 5GB)
Support of many files (~200.000)
Scheduleable background synchronization
File Share (NAS) support
Deletion support
No server required
Must work on windows. Linux and Mac support would be nice.

Could someone point me to a tool?
Comment: I'm assuming this is on windows, right?  Suggest you edit your question to make this clear, and/or add appropriate tags.
Comment: What does 'VPN support' mean?  If you have access to the network resource, then the tool should work.  Or are you expecting the application to have a built-in VPN system.
Comment: Synctoy does fit many of those requirements.  You should explicitly list speed in your list of requirements.  Also please tell us about what 'large folders' means to you.  Is that folders with a large number of files, or folders with a few files that are very large?
Comment: See also https://superuser.com/questions/69514/windows-alternative-to-rsync
Answer: good pointers in this discussion, although your question is not targeted for backup, we do use rsync for synchronization, although initial setup is little bit of work: Why hasn't rsync caught on in the Windows world?
Comment: Despite rsync might work well, I'd prefer a simpler solution. So if the other options fail, I'll try it.
Answer: Have you tried Richcopy, one of the latest incarnation of xcopy from Microsoft?
Comment: No, I need support for deletion. Thus when a file gets deleted one one side the sync tool deletes it on the other.
Answer: There is robocopy that comes with windows which does a good job then other one I have used is called Unison and it works on all platforms.  The one nice thing you can do with this is set it up so it will automatically sync files that get updated.  It can only do it between two locations but have a read though the doco and it will explain better than I can what its limitations is.
http://www.cis.upenn.edu/~bcpierce/unison/index.html
Comment: robocopy is not an option (see comment on Jmarki's answer). Unison sounds interesting. I'll have a look at it.
Comment: Unison does it.

File synchronization utility


fabric.js rotate a combined path

Question: I already searched for days and tried really a lot of things to get this right.
I want to use piecharts as progress pie. I created two fabric paths, which draws the pie chart and it works as it should.
Now I want to rotate the paths at the center point, but it doesn't work. It's actually a simple rotation. The main problem is, that the rotation point depends on the ratio of the chart. I have multiple charts and if I change one, all other charts changes as well.
I combined the two paths into a group, so every piechart is a group containing two paths.
Here are two of my piecharts. Selectable true to see what is selected.
https://i.stack.imgur.com/x6Uv1.png
https://i.stack.imgur.com/DfTnq.png
I want the selectable Rectangle to be evenly spaced out over the whole circle, so that the rotation point is exactly at the center. I don't understand why the selectable area is always the smaller part of the pie chart.
Can anybody help me out?
That's how I calculate the pie chart
for(var i = 0; i < sectorAngleArr.length; i++)
{
    startAngle = endAngle;
    endAngle = startAngle + sectorAngleArr[i];

    x1 = parseInt(left - (mainProgRad) * Math.sin(Math.PI*startAngle / 180));
    y1 = parseInt(top - (mainProgRad) * Math.cos(Math.PI*startAngle / 180));

    x2 = parseInt(left - (mainProgRad) * Math.sin(Math.PI * endAngle / 180));
    y2 = parseInt(top - (mainProgRad)  * Math.cos(Math.PI * endAngle / 180));

And thats how I draw it
if(i == 0 && sectorAngleArr[0] <= 180)
    {
        pathString = "M " +  (left) + "," + (top) + " L " + (x1) + "," + (y1) + " A " + mainProgRad + "," + mainProgRad + " 0 0,0 " + (x2) + "," + (y2) + " z";
        var path0 = new fabric.Path(pathString);

        path0.set(
        {
            fill:" rgba(80, 80, 220, 0.4)",
            stroke:"#0000cc",
            strokeWidth:"1",

        });
    }
    else if(i == 0 && sectorAngleArr[0] > 180)
    {
        pathString = "M " +  (left) + "," + (top) + " L " + (x1) + "," + (y1) + " A " + mainProgRad + "," + mainProgRad + " 0 1,0 " + (x2) + "," + (y2) + " z";
        var path0 = new fabric.Path(pathString);

        path0.set(
        {
            fill:" rgba(80, 80, 220, 0.4)",
            stroke:"#0000cc",
            strokeWidth:"1",

            });

    }
    else if(i == 1 && sectorAngleArr[1] <= 180)
    {
        pathString = "M " +  (left) + "," + (top) + " L " + (x1) + "," + (y1) + " A " + mainProgRad + "," + mainProgRad + " 0 0,0 " + (x2) + "," + (y2) + " z";
        var path1 = new fabric.Path(pathString);

        path1.set(
        {

            fill:" rgba(220, 80, 80, 0.4)",
            stroke:"#cc00cc",
            strokeWidth:"1",
        });
    }
    else
    {
        pathString = "M " +  (left) + "," + (top) + " L " + (x1) + "," + (y1) + " A " + mainProgRad + "," + mainProgRad + " 0 1,0 " + (x2) + "," + (y2) + " z";
        var path1 = new fabric.Path(pathString);

        path1.set(
        {
            fill:" rgba(220, 80, 80, 0.4)",
            stroke:"#cc00cc",
            strokeWidth:"1",
        });
    }
}

var progressGroup = new fabric.Group([path0, path1],
        {
            left: left,
            top: top,
            originX: "center",
            originY: "center",
            scaleX: -1,
            selectable:true
        });
        all.add(progressGroup);

I hope you can help me out!
EDIT: One good step forward was to use fabric.Pathgroup instead of fabric.Group...it reacts more as expected. But its still not working :)
Answer: OK, I find a workaround. The problem was, that the arc was ignored and the selecable area was around the 2 lines which were drawn. So I created more pieces of the pie to get the selectable area surrounding the wohle pie chart and the center, was now the center
You can see it here
https://i.stack.imgur.com/oKEzP.png
EDIT: After getting some problems with an odd amount of pieces I made it just easy and drew a rectangle behind the pie chart and made it invisible. It is necessary that the rectangle has an absolute position. Now everthing works fine! :)

fabric.js rotate a combined path


What is the relation between the high school definition of a vector and the abstract algebra definition?

Question: I'm studying linear algebra, and I've been getting to grips with the idea of groups and fields and vector spaces. From what I understand, to be a vector is just to be an element of a vector space, and all sorts of unusual (to the beginner) things turn out to be vector spaces. For example, the set of all real-valued functions is a vector space over $\mathbb{R}$. I take it this means that all real-valued functions (e.g. $\sin x$) are vectors over $\mathbb{R}$. But how does this abstract definition fit with the earlier account we are given of vectors as quantities with magnitude and direction or directed line segments?
Comment: I disagree that any of this has to be a "lie."  I can take the symbol ? and form an $\mathbb{R}$-vector space which has formal objects $x?$ for real $x$, which are formally added and scaled in the obvious way:  $x? + y? = (x+y)?$, etc.  This is a vector space by definition, but it has nothing to do with directed line segments, etc.  And it doesn't need to, because it meets the abstract definition.
Comment: It doesn't necessarily, because it is an abstraction.
Comment: Related (maybe duplicate?): https://math.stackexchange.com/questions/1937464/in-linear-algebra-what-is-a-vector
Comment: Then I think it has already been addressed upthread:  the abstract definition captures properties of the "standard" definition in an economical way.
Comment: The abstraction involves moving from the notion of "vector" to "linear" space, "linear" functions and "linear" algebra. Linearity is something that relates to Physics as well, because of principles of superposition in mechanics, electricity and magnetism, quantum mechanics, etc.. Don't get stuck at the "vector" level of abstraction.
Comment: Thanks, but there has to be some account we can give unless one of the characterizations is simply a lie or talking about different things. Perhaps, for example, when we're talking about vectors in calculus we're really just thinking about real valued vectors in a low-dimensional space, and that's what allows the characterization.
Comment: The more general definition includes the simpler examples of vectors that you learn about in high school such as $\vec{x}=(x_1, x_2, x_3) \in \mathbb{R}^3$.  The magnitude and direction are just properties of those particular examples.
Comment: That's missing the point. The question is about the relationship between the abstract definition and the standard definition.
Comment: If you want to stick with functions, it could be more natural to ask about normed vector spaces, for then you can draw more parallels between Euclidean norms and various functional norms.
Comment: OK, thanks guys
Comment: A similar question would be what does 5 apples take away 3 have to do with $-\frac{2}{3} + \frac{1}{5}$? The first is a pedagogically sound concrete realization of an abstract concept for beginners, and the second is an abstraction that answers questions you probably didn't think to have when you were studying the first. We tell pedagogical lies all the time in math. A valid question is whether your high school teacher should have said "a helpful example of a vector space is arrows with magnitude and direction" and not "a vector is an arrow with magnitude and direction."
Comment: I think as mathematicians we should always strive to be precise and accurate, but in practice I think it doesn't matter much how clearly we flag these pedagogical lies as lies. And since teachers are already pressed for time, I can't fault them for taking such shortcuts as they present themselves.
Answer: During one's original study of vectors, while thinking of them as "quantities with magnitude and direction" or as "directed line segments",  one slowly learns various properties of vectors involving the operations of arithmetic.
For example, one learns that two vectors in the same vector space (i.e. in $2$-dimensional space $\mathbb R^2$ or in $3$-dimensional space $\mathbb R^3$) can be added to produce another vector, using the parallelogram law of addition. Abstracting this slightly one simply says

Addition is a binary operator on vectors.

One also learns that it doesn't matter what order you add the two vectors in, the result of that operation will turn out the same. Abstractly,

Vector addition is commutative.

Just like with numbers, if you want to add three or more vectors, you have to do it two-at-a-time by inserting parentheses to group terms, but it doesn't matter how you insert those parentheses:

Vector addition is associative.

One next learns that there is actually an exception to the rule that a vector is a "directed line segment" or a "quantity with magnitude and direction", because there is a very special vector $\vec O$ which has no magnitude and points nowhere. You can still add this vector to other vectors, but the outcome is special: $\vec O + \vec V = \vec V$ no matter what $\vec V$ is.

There is an identity element of vector addition.

Now, I could go on in this vein, continuing with a slow explanation of how scalar multiplication works, and then writing down the abstract laws of scalar multiplication. But perhaps you have seen the pattern: the abstract laws that I am writing down are building up to be the abstract definition of a vector space. The above four laws are already about half of the definition of a vector space; I'm sure you can carry out the rest of this process with scalar multiplication.
Abstraction is a central process in the human development of mathematics. We look at familiar objects (e.g. vectors), we study their properties, if we're clever enough we abstract those properties, and then we notice: Hey! There are many other settings where those properties hold! I think I'll call those settings vector spaces!
Comment: Beautifully explained!
Comment: 'Abstracting properties' means 'eliminating some properties while keeping others', correct?
Comment: "To abstract" means to form equivalence classes and to talk only about properties which are well defined on that classes, i.e. invariant under/compatible wrt the equivalence relation.
In logics, there exists the notion of an "abstractor".
Comment: @ASlateff It sounds like your technical definition of "to abstract" is a kind of formal model for the natural language concept of "to abstract" which I am using in my post, although I don't think it can simply replace the natural language usage.
Comment: @LeeMosher : Most direct concepts have a counterpart in formalized logics. The method, which I used here, of "to abstract" something basically can be found in the (German) book of Rüdiger Inhetveen: "Logik. Eine dialog-orientierte Einführung." Although I do not follow his concept of logic, I use some of his concepts such as the "abstractor" and his ideas of how abstraction works. One can of course form equivalence classes of real objects, just combine them in classes. :-)
Answer: The "high school" vectors belong to finite-dimensional vector spaces, namely $\Bbb R^2$ and $\Bbb R^3$. The abstract definition of a vector space expresses some of the essential properties of addition and scaling in these spaces that make them behave according to our spatial intuition.
The fact that many things satisfy the requirements of the abstract definition (like $\Bbb R^5$, or sets of functions with suitably defined operations) means that some of our intuition about arrows, lines, planes, projections, distances, etc. are applicable to these spaces, even though the mental picture is a little less concrete (and e.g. things can happen in infinite-dimensional spaces that can't happen in finite-dimensional ones). Carefully studying the logical consequences of the abstract definition tells us how exactly we can extend the intuition in different applications.
By the way, I think your statement that "$\sin x$ is a vector over $\Bbb R$" reflects a slight misunderstanding. You should really say "there exists a vector space over $\Bbb R$ that includes the $\sin$ function as an element". That is, $\sin$ isn't a vector by itself - you need the whole space (with its specific addition and scaling operations) in order for "being a vector" to mean anything.
Comment: Actually, I think Lee Mosher answered my additional question: there needn't be, necessarily. There are exceptions to the 'directed line segment' idea, which we realize as we sift out the essential properties of vectors and vector spaces.
Comment: @DanÖz a directed line is basically just a $1$-dimensional vector subspace, so  if you are in the space of real-valued function, given  any function in that space $f$ then  $\{f  \mid \lambda \cdot f,  \ \lambda \in \mathbb{R} \}$ is your "line".
Comment: Saying that a vector "has a direction" is informal (because what is a direction?), but one way we can formalize the concept is by saying that two vectors "have the same direction" if one is a scalar multiple of the other, and this works in every vector space. If you want to measure angles between vectors or lengths of vectors, you need an [inner product space](https://en.wikipedia.org/wiki/Inner_product_space). Inner products can be defined for function spaces using integrals, so we can indeed measure the angle between two functions.
Comment: Yes, I take the correction on board! To take a concrete case of extending our intuitions, is there something analogous to a directed line in the case of, say, the set of all real-valued functions on R, i.e. the direction of a function? I think I pretty much am with you now though (and Lee Mosher)!
Answer: What you deal with in HS is not just a vector space but an inner product space.
What is that? Well it's a vector space with an additional structure of a dot product.
Why do I say only dot product? What about lengths and distances? Well the inner product is most fundamental. It implies all of the below structures. We define the length of vectors as:
$$ N(a) = \sqrt{ \langle a, a \rangle }$$
And, the distance between two vectors induce through the norm as:
$$ d(a,b) = || a-b ||$$
That is the norm of the difference vector.
An interesting question to ask is, in the abstract sense, when is it that a norm can be derived from an inner product? Well that's exactly when the parellogram law holds.
So, it's just an issue of HS abusing the mathematical naming a lot. Hope it is clear now.
In essence, what I want to say is, the HS idea of a vector space is actually much beyond the mathematical vector space. On a vector space level itself, even functions can take part.

Bonus!
You can make functions also into inner product space.  You can think about integration over an interval as an inner product:
$$  \langle f,g \rangle = \int_a^b f g dx$$
You can check that the inner product is commutative (Switch slot of f,g) , linear in each slot etc just like normal dot product. You can also show the Cauchy Schwarz Inequality:
$$ \int_a^b fg dx \leq \sqrt{\int_a^b f^2 dx } \sqrt{\int_a^b g^2 dx}$$
Of course, there is a whole lot of "fine print" that I am skipping out, but this is more or less the idea.
Also it is not that in a given vector space there is only one inner product we can put, there are probably many ways to define one.
Comment: $\langle x,y\rangle:=\sum_{i=1}^n\lambda_ix_iy_i$ where $\lambda_1,\dots,\lambda_n>0$ and $x,y\in\Bbb{R}^n$ defines an inner product. And once again, every inner product gives rise to a norm.
Comment: Regarding your comment: it should say *'It is a Hilbert space'*. Banach spaces are not necessarily inner product spaces (i.e the norm on a Banach space need not arise from an inner product). Also, in your last paragraph, you mention the $p$-norms, but they arise from an inner product if and only if $p=2$.
Comment: Every inner product gives rise to a norm. The converse is what fails. The 'usual' inner product gives rise to the 'usual' 2-norm. There are infinitely many inner products you can put on $\Bbb{R}^d$.
Comment: What point are you referring to?
Comment: I meant, a concrete example of inner product which gives a norm which maybe helpful is interesting other than the normal product @peek-a-boo
Answer: Recall the defintion for a vector space $V$:
Given a field $K$ and a set $V$ with the folowing operations:
$$+ :V \times V \rightarrow V, \quad (v,w) \mapsto v+w $$
$$\cdot :K \times V \rightarrow V, \quad (\lambda,w) \mapsto \lambda \cdot v  $$
Then $V$ is said to be a vector space if

$A_1$ : $(V,+)$ is a commutative group regarding the operation $+$.

$A_2$: The $\cdot$ operation must hold the following

$$(\lambda + \mu ) \cdot v = \lambda \cdot v + \mu \cdot v, \quad \lambda  \cdot ( v + w ) = \lambda \cdot v + \lambda \cdot w $$
$$\lambda \cdot (\mu \cdot v) = (\lambda \cdot \mu) \cdot v, \quad 1 \cdot v = v,$$
For all $\lambda, \mu  \in K$ and $v,w \in V$.
So basically this abstract definition gives a set $V$, that has the least amount of structure one would need to do basic linear algebra, what ever that means.
Now if you look at  the set $\mathbb{R}^n$ in highschool (mostlikely the case $n=3$ or $n=2$) which is a vector space, you are dealing with "vectors" such  as $\overrightarrow{a} = (1,2,3)^T$, where one would define vector addition and scalar multiplication column wise. This set comes naturally with a lot more structure than $V$. For example the inner-product $\langle \ , \ \rangle : \mathbb{R}^n \times \mathbb{R}^n \rightarrow K$ in $\mathbb{R}^n$ or the euclidian distance a.k.a  euclidian norm given by
$$\mid \overrightarrow{a}-\overrightarrow{b} \mid= \sqrt{(a_1- b_1)^2 + ... + (a_n - b_n)^2}$$.
Generally $V$ does not come with such structure's, but some do and they get different names such as normed vector spaces (if they have a norm see norm axioms) and inner product spaces if they have a inner product.
The motivation for this abstraction lies in that you able to state theorems for all vector spaces with certain property's or structures. Once one proved a theorem for certain vector spaces it becomes applicable for all vector spaces with the same properties. Now regardless how exotic you concerning vector space may be, the rules and theorem apply, and you are able to play with them as if they were element's in $\mathbb{R}^n $ (if they are same dimension etc.) and thats the beauty of it!
Now not all vector spaces have a visual interpretation like $\mathbb{R}^3$, but the same rules, for example the vector space of real valued continuous and  bounded functions does not have a geometric interpretation to it (at-least not that I know off) but you are able to define a norm on it and even a inner-product! see Banach spaces or Hilbert spaces.
Answer: The abstract algebra version took some properties of the "arrows" (or ordered pairs of points) or translations in affine space and defined vector spaces to be a set V which consists of objects that have these properties.
The main properties are:
Two vectors can be added ("there exists a 2-ary operation +").
Addition is commutative.
A zero vector changes nothing ("there exists a neutral element 0").
Every vector has an inverse.
Combined: (V,+,0) is an Abelian group.
Vectors can be scaled with real numbers
(more modern form, first variant: "There exists a commutative field (F,+,0,.,1) which operates compatibly from the left on (V,+,0)."
second variant: "Let End(V) denote the set of group endomorphisms V->V with pointwise addition + and composition °. Let (F,+,0,.,1) be a commutative field. There exists a ring homomorphism $\theta: (F,+,0,.,1) \to (End(V),+,0,°,id_V)$."
The ring homomorphism is called "homothety" and provides the scaling of vectors. Sometimes, in abstract algebra, this ring homomorphisms itself is called a "vector space", which is a little bit strange. Sometimes, it is called the "structure homomorphism", because it provides the Abelian group (V,+,0) with a vector space structure - an operation from the left of scalars.)
Vectors are elements of the set V which underlies the group (V,+,0).
F-Vector Spaces, together with F-vector space homomorphisms, form a category. (The set of) equivalence classes of ordered pairs of points in affine space, or of equivalence classes of arrows in affine space, or of translations in affine space, together with the usual operations, forms a particular instance in that category, i.e. such a set (with its operations) gives a particular object in this category.
In this sense, the high school definition of a vector in a vector space provides only a particular case of the modern definition of a vector space.


How to get thickness of a spherical shell based on radius and volume?

Question: I have a problem converting an equation. I want to flip an independent to dependent.
Volume of a spherical shell is:
$$V= \frac{4}{3}\pi\bigl[(R+t)^3-(R-t)^3\bigl]$$
Where R is radius, t is half of shell's thickness. It is important to me that it has a form of ± t rather than the most common $V= \frac{4}{3}\pi\bigl[R^3-(R-2t)^3\bigl]$
How to turn the equation to have the following form?: $$t(V,R) = ...$$
I know it must be simple but no matter what I do, I end up with R somehow tangled to t. Please, help. I am getting mad...
Comment: I'm not saying is the case here, but some times things like this may not have algebraic solution. For example given a capsule shape fuel tank with given height of fluid of constant density, it is not possible to give a closed form algebraic solution to the volume in the tank. Ie, measuring contents of pill shaped capsule fuel tank by dipping ruler in it. In fact it is similar to solving for eccentric anomoly in two body gravitation.
Answer: Starting from $$V= \frac{4}{3}\pi\bigl[(R+t)^3-(R-t)^3\bigl]=\frac{4}{3}\pi\left(6 R^2 t+2 t^3 \right)$$ and intoducing $$x=\frac t R \qquad\text{and}\qquad b=\frac{3 V}{8 \pi  R^3}$$ we end with a cubic equation $$x^3+3x-b=0\tag 1$$ Now, let $x=y-\frac 1y$ to get $$y^6-b y^3-1=0 $$ which is a quadratic in $y^3$ making the analytical real solution of$(1)$ to be
$$y^3=\frac{b+\sqrt{b^2+4}}{2}\qquad \implies \qquad\color{red}{x=\sqrt[3]{\frac{b+\sqrt{b^2+4}}{2}}-\sqrt[3]{\frac{2}{b+\sqrt{b^2+4}}}}\tag 2$$
Assuming that $t$ is small, you can also write $$t=\sum_{i=1}^n a_i\, b^{2i-1} \tag 3$$ which will give by identification $$a_1=\frac{1}{3}\qquad a_2=-\frac{1}{81}\qquad a_3=\frac{1}{729}\qquad a_4=-\frac{4}{19683}\qquad a_5=\frac{55}{1594323}\tag 4$$ and so on.
This is in fact the Taylor expansion of $(2)$ built around $b=0$.
In order to check, we can use $(1)$ for given value of $x$ to deduce $b$ and from $b$ recompute $x$ from the expansion. Below are the results
$$\left(
\begin{array}{ccc}
x_{given} & b_{calc} & x_{calc} \\
 0.00 & 0.000000 & 0.000000 \\
 0.05 & 0.150125 & 0.050000 \\
 0.10 & 0.301000 & 0.100000 \\
 0.15 & 0.453375 & 0.150000 \\
 0.20 & 0.608000 & 0.200000 \\
 0.25 & 0.765625 & 0.250000 \\
 0.30 & 0.927000 & 0.300002 \\
 0.35 & 1.092880 & 0.350014 \\
 0.40 & 1.264000 & 0.400064 \\
 0.45 & 1.441130 & 0.450253 \\
 0.50 & 1.625000 & 0.500879
\end{array}
\right)$$ which seems to be a quite good approximation.
Edit
Nicer would be to use the hyperbolic solution for one real root. This would give $$x=2 \sinh \left(\frac{1}{3} \sinh ^{-1}\left(\frac{b}{2}\right)\right)\tag 5$$ that is to say $$\color{red}{t=2 R \sinh \left(\frac{1}{3} \sinh ^{-1}\left(\frac{3 V}{16 \pi  R^3}\right)\right)}\tag 6$$ which is the exact formula you are looking for.
Comment: Using $b=2c$ gives something nicer $$y=c+\sqrt{c^2+1}\implies x= c+\sqrt{c^2+1}-\frac 1{c+\sqrt{c^2+1}}$$
Comment: Thank you for all your work! The final equation is neat and beautiful. However, I had some problems modeling it and the results were incorrect. Unfortunately I didn't have time to find where I have made a mistake so I went for the equation visually more complex but easier in modeling. Once again: thank you!
Answer: Mathematica gives:
$$t(V,R)=\frac{2\cdot(2\pi)^{1/3}R^2}{\left(-3V+\sqrt{256\pi^2R^6+9V^2}\right)^{1/3}}-\frac{\left(-3V+\sqrt{256\pi^2R^6+9V^2}\right)^{1/3}}{2\cdot(2\pi)^{1/3}}$$


Quadratic covariation of two Compound Poisson Process.

Question: This is not a homework problem but a curiosity question and hence the question may not be well built but I want the community to help me in understanding this concept and hence answer it. If you think the question can be framed better please do tell me. I would really really appreciate any help in the form of comments/answers.
I want to find out the Quadratic covariation of two semimartingales $Z_1,Z_2$ where both are compound poison processes and they are correlated by say a factor of $\rho_1$.
If $Z_1(t)=\sum^{N_1(t)}Y_i$ and $Z_2(t)=\sum^{N_2(t)}U_j$ are two compound poisson process then what will be the quadratic covariation of $Z_1,Z_2$ , i.e $[Z_1,Z_2](t)$ ?
In this $N_1$ and $Y_i$ are independent and $N_2$ and $U_j$ are independent and with $Y_i$ is an i.i.d and also $U_j$ is an i.i.d. We can assume that $E(Y_i)=\mu_1$ and $E(U_j)=\mu_2$. We can also assume that the jumps $N_1,N_2$ are correlated by $\rho_2$ and $Y_i,U_j$ are corrleated by a factor of $\rho_3$ (if needed).
One of the ways in which I thought was to calculate
$[Z_1,Z_2](t)=Z_1(t)Z_2(t)−Z_1(0)Z_2(0)−\int^t_0Z_1(s)dZ_2(s)−\int^t_0 Z_2(s)dZ_1(s)$
where we will have $dZ_1(s)=Y_iN_1(s)$ and $dZ_2(s)=U_jN_2(s)$.
I am open to other methods to calculate the same as I was unable to proceed much in above. Also if you can find a reference please mention the link below.
Answer: The following is a simple model for correlated compound processes. Let $ N=\{N_t,t\ge 0\} $ be a Poisson process with $ \mathsf{E}[N_t]=\lambda t $
and $ Y=\{ ( Y_k^{(1)} ,Y^{(2)}_k), k\ge 1 \} $ be a  sequence of i.i.d. 2-d random variables, with
$$  \mathsf{E}[Y^{(i)}_k Y^{(j)}_k]=m_{ij},\qquad i,j=1,2,\quad k\ge 1 $$
Also, $ Y $ and $ N $ are mutual independent. Now define $X=\{X_t=(X^{(1)}_t,X^{(2)}_t), t\in\mathbb{R}_+\}$ as following:
$$ X^{(i)}_t=\sum_{k=1}^{N_t}Y_k^{(i)}, \qquad i=1,2. $$
Then $X^{(1)}=\{ X^{(1)}_t,t\in\mathbb{R}_+\}$, $X^{(2)}=\{ X^{(2)}_t,t\in\mathbb{R}_+\} $
are correlated compound Poisson Processes. Using the general results of  compound Poisson Processes we can get the quadratic covariation $[X^{(i)},X^{(j)}] $ as following:
$$  [X^{(i)},X^{(j)}]_t=\sum_{s\le t} \Delta X^{(i)}_s \Delta X^{(j)}_s
= \sum_{k=1}^{N_t}Y_k^{(i)} Y_k^{(j)},\qquad i,j=1,2 $$
And the predictable quadratic covariations are
$$  \langle X^{(i)},X^{(j)}\rangle_t=m_{ij}\lambda t,\qquad i,j=1,2
$$
About the general results of stochastic calculus and compound Poisson processes please refer to the following books:
J. Jacod and  A. N. Shiryayev, Limit Theory for Stochastic Processes, 2ed. Springer, 2003.
A. E. Kyprianou, Fluctuations of Lévy Processes with Applications, 2nd Ed., Springer, 2014.
D. Applebaum, Lévy Processes and Stochastic Calculus, 2nd Ed, Cambridge University Press, 2009.
Answer: So.
We have that $ Z_1(t) = \sum^{N_1(t)}Y_i $ and $ Z_2(t) = \sum^{N_2(t)}U_j $ are both semimartingale and compound poisson processes with correlation coefficient $ \rho_1 $ and i.i.d. jump sizes (from $ Y_i $ & $ U_j $ being i.i.d.) where $ \left( N_1 \perp \!\!\! \perp Y_i \right) \land \left( N_2 \perp \!\!\! \perp U_j \right) $. As $ Z_1 $ and $ Z_2 $ are both semimartingale, we know that quadratic covariance exists between them.
It must be assumed that $ E(Y_i) = \mu_1 $ and $ E(U_j) = \mu_2 $ are finite for the two processes to be correlated; that is, the random variables $ Y_i $ and $ U_j $ must be normally distributed.
This leads me to the more reckless assumption that we are working with Gaussian distributions here... but luckily, we can see that the form of the Gaussian distribution, $
f(x) = \frac{1}{\sigma\sqrt{2\pi}}e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2} $, is amenable to a (continuous and thus unique) semimartingale decomposition in that we can use $Y_i=M_1(i) + X_1(i)$ and $U_j=M_2(j) + X_2(j)$ to write $ y(i) = \frac{1}{\sigma_1\sqrt{2\pi}}e^{-\frac{1}{2}\left(\frac{Y_i-\mu_1}{\sigma_1}\right)^2} = \frac{1}{\sigma_1\sqrt{2\pi}}e^{-\frac{1}{2}\left(\frac{M_1(i)+X_1(i)-\mu_1}{\sigma_1}\right)^2} $ and $ u(j) = \frac{1}{\sigma_2\sqrt{2\pi}}e^{-\frac{1}{2}\left(\frac{U_j-\mu_2}{\sigma_2}\right)^2} = \frac{1}{\sigma_2\sqrt{2\pi}}e^{-\frac{1}{2}\left(\frac{M_2(j)+X_2(j)-\mu_2}{\sigma_2}\right)^2} $. Working with this could be an option.
I also note that the Itô integral $ [Z,Z]_t = \int_0^t{\sigma^2(s)ds} $ may be used to find the quadratic covariance between two Itô processes (because all semimartingale processes are Itô processes) via the polarization formula $ \left[Z_1,Z_2\right]_t = \frac{1}{2}\left[Z_1+Z_2,Z_1+Z_2\right]_t - \left[Z_1,Z_1\right]_t - \left[Z_2,Z_2\right] $. Use of the Itô integral obtains $ \left[Z_1,Z_1\right]_t = \int_0^t{\sigma_1^2(s)ds} $ and $ \left[Z_2,Z_2\right]_t = \int_0^t{\sigma_2^2(s)ds} $. Since sums of Itô processes are Itô processes, we also get $ \left[Z_1+Z_2,Z_1+Z_2\right]_t = \int_0^t{\left(\sigma_1+\sigma_2\right)^2(s)ds} $ so that we have
$$ \left[Z_1,Z_2\right]_t = \frac{1}{2}\int_0^t\left(\sigma_1+\sigma_2\right)^2(s)ds - \int_0^t\sigma_1^2(s)ds - \int_0^t\sigma_2^2(s)ds $$
which is more or less similar but different to what you're working with?
This may contain errors, but the basic ideas are:

Consider working with Gaussian formulae.
Treat the processes as Itô processes.
Comment: please note that $Z,Z_1,Z_2$ are not path continuous processes, so you could not use the formula for path continuous processes.
Comment: Really appreciate that you wrote the above. Thanks.


Connectedness of complements

Question: Let $A$ and $B$ are compact subsets of $\mathbb{C}$ such that $B=A \cup$ iso($B$).
If $A^c$ is connected then prove that
$B^c$ is connected.
Here iso($B$) denotes the set of isolated points of $B$.
For a compact subset $A$ of $\mathbb{C}$ we say that $A^c$ is connected if $A^c$ does not have any bounded component.
Comment: I have taken complements on both sides and we get, $B^c=A^c \cap (iso(B))^c$. Now $(iso(B))^c$ is connected and $A^c$ is connected. Then how can we say their intersection is also connected.
Comment: What have you tried so far?
Comment: @ManuRohilla Put that in your question
Answer: Since $A^c$ is an open connected set of $\mathbb C$, it is path connected. The set of isolated points is always countable in $\mathbb R^n$[Proof: $\mathbb R^n$ is second countable. Subspaces of second countable spaces are countable. An uncountable set consisting of isolated points only is not second countable.] Now $B^c$ is equal to $A^c$ minus countably many points. Can you conclude that $B^c$ is path connected using Why is open connected minus countable set is connected?
Comment: How can we say that if $B$ is compact then isolated points of $B$ are finite.
Comment: @ManuRohilla I deleted my previous comment (since it is very wrong! E.g. $\{\frac{1}{n}\}_{n\in \mathbb N}$ is an infinite set consisting of isolated points only) and make a significant edit, please check out.

Connectedness of complements


Reliability in R

Question: I'm having trouble understanding the difference between omega 1 and omega 3 in reliability function in the semTools package in R, when calculating the reliability of my factors in a bifactor model.
Are the omegas hierarchical?
Comment: Do you mean the reliability function in the semTools package?
https://cran.r-project.org/web/packages/semTools/semTools.pdf
Comment: yes, exactly! sorry, I will edit my post
Answer: If you are referring to the reliability function in the semTools package, there is a nice explanation of the difference in the documentation.
Omega1 assumes that all covariance is accounted for by the common factor model, with no residual covariances between observed variables. This assumption is the basis for computing total variance (the denominator) using only the loadings and the covariances among factors.
Omega2 relaxes the "no residual covariance" assumption, and so the denominator is simply the model-implied covariance matrix of the observed variables.
Omega3, which is intended for models with constraints on relations between factors, replaces omega2's model-implied covariance matrix with the observed covariance matrix. If relations between factors are saturated, then there is no room for the structural model to be inconsistent with the data--this is what omega2 assumes. But if relations between factors are structured, then there may be misfit between model and data, which may have implications for estimated reliability. Omega3 allows for this possibility.

Reliability in R


Python: X marks the trail

Question: I am trying to make a code that allows the user to track where they have been on a grid (grok introduction to python (2) X marks the trail) I have been working on the code for a while and I think that I'm pretty close but not sure how to correctly format it
the code should work like this:
Grid size: 3
x..
...
...
Direction: right
xx.
...
...
Direction: down
xx.
.x.
...
Direction: right
xx.
.xx
...
Direction:

but mine displays:
Grid size: 3
[['x', '.', '.'], ['.', '.', '.'], ['.', '.', '.']]
Direction: down
[['x', '.', '.'], ['x', '.', '.'], ['.', '.', '.']]
Direction: right
[['x', '.', '.'], ['x', 'x', '.'], ['.', '.', '.']]
Direction: right
[['x', '.', '.'], ['x', 'x', 'x'], ['.', '.', '.']]
Direction: down
[['x', '.', '.'], ['x', 'x', 'x'], ['.', '.', 'x']]
Direction: left
[['x', '.', '.'], ['x', 'x', 'x'], ['.', 'x', 'x']]

my code is:
g = input('Grid size: ')
gn = int(g)
grid = []
for i in range(gn):
  row = []
  for j in range(gn):
    row.append('.')
  grid.append(row)
grid[0][0]='x'
print(grid)
h = 0
v = 0
m = input("Direction: ")
while m != "":
  if m.lower() == "right":
    h = h+1
    grid[v][h] = 'x'
    print(grid)
    m = input("Direction: ")
  elif m.lower() == "left":
    h = h-1
    grid[v][h]= 'x'
    print(grid)
    m = input("Direction: ")
  elif m.lower() == "up":
    v = v-1
    grid[v][h]= 'x'
    print(grid)
    m = input("Direction: ")
  elif m.lower() == "down":
    v = v+1
    grid[v][h]= 'x'
    print(grid)
    m = input("Direction: ")

Someone, PLEASE help I can't figure out how to join the lists together (each on a new line)
Answer: You could create function to print the grid
def show_grid(grid):
    for line in grid:
        print(''.join(line))

Python: X marks the trail


Does anyone find math proofs easy to comprehend?

Question: Ever since my undergrad, I've been taking challenging math classes. Starting with the sophomore year, I faced some difficult proofs I had to learn (and be able to recite at an exam with slight modifications) and now I'm doing a PhD and still dealing with proofs that take so much of my mental energy.
Now I am in no way the brightest guy in the classroom, but I managed to get through these courses with mostly A's. The problem is when I look back, I remember nothing. Moreover, comparing the time it took for me to be able to do pages of proofs on assignments to how I'm able to absorb information so quickly in my area (AI in vision), I feel like I might be lacking some talents in math. When I read the most recent article DeepMind has published, it is a breeze. But if there is a single proof there, I'll have to be a lot slower, have my pen and paper ready and do lots of iterations.
I had a lot of friends who were extremely smart, but I remember that even they didn't feel too comfortable with proofs (way more comfortable than me though).

So I'd like to ask, is there a thing such as being naturally wired to understand and do proofs? I understand if you do it every day, you'll get familiarized and be a lot more adept in it, but are you or have you ever witnessed someone that picks it up right away?

I always felt it's fun to do this, but I am not going to be the best at it since I spend so much effort (hence I didn't pursue a maths career).
Thanks in advance!
Comment: Not meaning to be rude, but I have a hard time understanding what, in your view, mathematics is *besides* working on proofs? I mean, in the undergrad courses it might look like it's about some theorems that one can just memorise; but the deeper you dive into it, to truly understand a theorem is to understand how it connects with other theorems, and that is what a proof is. In other words, I think for many mathematicians the line between theorems and proofs becomes blurry.
Comment: _Young man, in mathematics you don't understand things. You just get used to them._   ——von Neumann.
Comment: Every university mathematics curriculum should have courses with well-designed theorem/definition sequences in which students are expected to find and present their own proofs. This teaches the student not only to discover and defend their own proofs but gives them practice in critically evaluating the attempted proofs of other students. After such basic training students will be better able to critically read and understand proofs. And one more easily remembers what one has read critically and understood in terms of basics.
Comment: @TorstenSchoeneberg Not sure if this is directed at me, but if it is: besides what I think, I see math is pretty much proving stuff- that's why I stopped pursuing it! But also I know math is also about inventing these proofs which will be used by applied science. However to me, if one struggles to understand, explain or replicate what others did, it is unlikely that s/he'll be contributing to the field.
Comment: @CaveJohnson, This is exactly what I'm doing. However, I don't think von Neumann is at my level, so probably his definition of things is way different than mine. I also can't imagine it is possible to have these proofs if NOBODY had  any earthly idea what was going on. I mean, surely someone must "get it", right?
Answer: I don't have any inherent problem reading math proofs (not that I read them as quickly or effortlessly as novels) as you describe, but I can't make much progress in reading, say, legal documents. My own thought processes are those of a mathematician and naturally line up with math proofs; that's what mathematicians do, and what mathematicians are for. Other people think like lawyers and gravitate toward legal arguments, or computer scientists and gravitate toward algorithms, or novelists and gravitate toward prose, etc. (Though it sounds like you aren't one of them, there are people who breeze through high-school-level math but hit a brick wall when they run into math that's more than just computation. The mindset to churn through integrals is not necessarily one that handles constructing and reading proofs fluently.)
Part of it is also, as you said, practice. Legal documents are written in what seems from the outside like an opaque style because of the need for precise jargon and formularies, and because it makes it clear to lawyers what the relevant parts are and what's just boilerplate. Math proofs are the same way, and after a while you learn to recognize what's just an uncreative computation and which parts are the clever ones, which parts can be extended or tweaked to give a further result, and so on.
I'd also add that there's an art to writing proofs that's rigorous without being pedantic. The style and expectations are different from other fields', even ones that involve a lot of mathematics. I've coincidentally done a little bit of work in AI and vision as well (albeit probably on a different side of things), and there's a different feel to research there than in mathematics.
Comment: Would you consider that the AI work you've done is easier/less involved than math? I understand my bias here is quite contradictory to your example about lawyers and how people are wired, but I can't imagine that someone that can deal with complex proofs will have any problem dealing with the popular form of AI today?
Comment: I would say it was, with the important caveat that AI is not my field of study and so I've gone much farther in math than in AI or vision or general computer science. It's depressing as a mathematician, but there really isn't much out there that uses a lot of very advanced, academic-research-level mathematics.
Answer: You should read some of Dr Laura Alcock's books such as "How to think about Analysis" OUP ISBN 978-0-19-872353-0. She has an amazing way of talking about how to think about and study proofs. She has written several books but it may just be what you need to help.
Comment: I think, this should be a comment.


Pointwise and uniform convergence of $\sum_{n=0}^\infty x^n(1-x)$

Question: I need to determine whether
$\sum_{n=0}^\infty x^n(1-x)$
converges pointwise and/or uniformly in $\mathbb{R}$
What I tried so far:
$\sum_{n=0}^\infty x^n(1-x)$ converges only if $|x| < 1$ or if $x=1$.
Does that mean that $\sum_{n=0}^\infty x^n(1-x)$ does not converge pointwise in $\mathbb{R}$ and therefore also not uniformly?
Comment: Yes, that's right.  It's a good exercise to show convergence is uniform on $[0,1]$  or on $[a, 1]$  where $-1 < a \le 0$.
Answer: Indeed your series diverges when $x=-1$ (for instance), and therefore, in particular, it is not an uniformly convergent series of functions from $\mathbb R$ into $\mathbb R$.
Answer: Obviously it's
$$\sum_{n=0}^{\infty}x^n(1-x)=(1-x)\sum_{n=0}^{\infty}x^n$$
but $\sum_{n\geq 0}x^n$ is a well known series which converges for $|x|<1$. For $x=1$ the whole term is zero, hence it converges in $(-1,1]$. The convergence is uniform in $(a,1]$ for each $a\in (-1,1]$. But uniform convergence implies pointwise convergence.


How can I find documents whose child documents contain fields totalling a value?

Question: A book series has many books. A book has a number of pages.
{
  "mappings": {
    "series": {
      "properties": {
        "name": { "type": "string" },
        "books": {
          "type": "nested",
          "properties": {
            "title": { "type": "string"  },
            "page_count": { "type": "integer"  }
          }
        }
      }
    }
  }
}

I index some book series.
{
  "name": "Harry Potter",
  "books": [
    {
      "title": "Harry Potter and the Philosopher's Stone",
      "page_count": 100
    },
    {
      "title": "Harry Potter and the Chamber of Secrets",
      "page_count": 100
    }
  ]
}

{
  "name": "The Long Earth",
  "books": [
    {
      "title": "The Long Earth",
      "page_count": 150
    },
    {
      "title": "The Long Mars",
      "page_count": 150
    }
  ]
}

I want to find all book series where the total number of pages of the books in that series is greater than or equal to 250. This query should return the "The Long Earth" series, which has 300 total pages, but not the "Harry Potter" series, which only has 200 total pages.
How can I structure such a query?
As far as I can tell, nested queries only allow you to look into individual nested docs (e.g. find a series that has at least one book with more than 120 pages). I've never worked with scoring before (only used binary queries), and I'm starting to think maybe that holds the answer...
Answer: Take a look at nested aggregations. You'll want to apply nested sum aggregation and filter on that.


Q: Find all functions that are analytic and satisfy $(\operatorname{Re}(f(z)))^2 = \operatorname{Im}(f(z))$

Question: I've been trying to find all functions $f(z):\Bbb{C}\longrightarrow\Bbb{C}$ that are analytic and satisfy
$$(\operatorname{Re}(f(z)))^2 = \operatorname{Im}(f(z))$$
After plugging in $f(z)=x+iy$, I got $f(z)=x+ix^2$.
These kind of functions never satisfy Cauchy-Riemann equations, since $\mathcal u_x=1 \neq 0=v_y$.
Does it follow from this argumentation that no such analytic $f(z)$ exists?
Comment: $f(z) = 0$ works, as do constant functions of that form like $f(z) = 3 + 9 \cdot i$.
Comment: The partial derivative $u_x$ in the Cauchy-Riemann equations is taken with respect to $x = \operatorname{Re} z$, not $x=\operatorname{Re} f$
Answer: You might have rushed your analysis a little bit. The condition you have given is equivalent to saying that
$$ f(x+  iy) = u(x,y) + i u(x,y)^2$$
Computing the Cauchy-Riemann equations we have
$$ \frac{\partial u}{\partial x} = 2u\frac{\partial u}{\partial y}$$
and
$$ \frac{\partial u}{\partial y} = -2u\frac{\partial u}{\partial x}$$
Combining these two we have
$$\frac{\partial u}{\partial x} = - 4 u^2 \frac{\partial u}{\partial x} \iff \frac{\partial u}{\partial x} \left(1 + 4u^2\right) = 0$$
Since $1 + 4u^2 > 0$ for all $u \in \mathbb{R}$ we must have $\frac{\partial u}{\partial x} = 0$. In similar fashion we may also compute
$$ \frac{\partial u}{\partial y} = -  4u^2 \frac{\partial u}{\partial y} \iff\frac{\partial u}{\partial y} \left(1 + 4u^2\right) = 0 $$
From which we may conclude that $\frac{\partial u}{\partial x} = 0$. So $u(x,y)$ must be a constant function. Since we did not specify any specific value of the constant function $u(x,y)$ then it follows that it works for all values. Thus functions with a constant real part which satisfy the hypothesis you have given are all solutions.
Comment: You, too, may have rushed your analysis a bit ;) We get $$\frac{\partial u}{\partial x} = 2u\frac{\partial u}{\partial y}$$ not $$\frac{\partial u}{\partial x} = 2u\frac{\partial u}{\partial x}$$
Comment: Indeed I too have rushed my analysis a bit... going to fix that up right now.
Answer: Another kind of solution: Note that ${\rm Im}(f(z))\geq 0$ for all $z$. Hence if we put $g(z)=\exp(if(z))$, we have $|g(z)|=\exp(-{\rm Im}(f(z))\leq 1$ for all $z$. By Liouville's theorem, $g$ is constant, and $f$ is also a constant, of the form $c+ic^2$, $c\in \mathbb{R}$.
Comment: This is pretty clever. If you want to bring out the big guns, Picard's little theorem says analytic functions miss no more point in their image. So you can stop after your first sentence.
Comment: Very nice, +1!
Answer: If as usual we set
$z = x + iy \tag{1}$
and
$f(z) = u(x, y) + iv(x, y), \tag{2}$
then the condition
$(\operatorname{Re}(f(z)))^2 = \operatorname{Im}(f(z)) \tag{3}$
may be written
$v = u^2;\tag{4}$
thus $f(z)$ becomes
$f(z) =  u(x, y) + iu^2(x, y).  \tag{5}$
Since $f(z)$ is holomorphic, $u(x, y)$ and $v(x, y) =  u^2(x, y)$ are harmonic; that is,
$\nabla^2u = 0 \tag{6}$
and
$\nabla^2 u^2 = 0.  \tag{7}$
We compute $\nabla^2u^2$; we have
$\nabla^2 u^2 = \nabla \cdot \nabla u^2$
$= \nabla \cdot (2u \nabla u) = 2\nabla u \cdot \nabla u + 2u \nabla^2u$
$= 2 \vert \nabla u \vert^2, \tag{8}$
using (6); in deriving (8), we have also used the standard identity
$\nabla \cdot (gX) = \nabla g \cdot X + g \nabla \cdot X, \tag{9}$
holding for differeniable scalar functions $g$ and vector fields $X$; for more, see https://en.m.wikipedia.org/wiki/Vector_calculus_identities.  It follows from (7) and (8) that
$\vert \nabla u \vert^2 = 0, \tag{10}$
or
$\vert \nabla u \vert = 0, \tag{11}$
or
$\nabla u = 0; \tag{12}$
we conclude that $u(x, y)$ must be a real constant $c$; it follows then that $v(x, y) = c^2$ and, finally $f(z)$ is a complex constant of the form
$f(z) = c + ic^2, \tag{13}$
where $c \in \Bbb R$.
Nota Bene:  The technique used above, viz. showing that $\nabla u = 0$, may be applied to other, similar questions as well; see for example the
Related Problem:
Can we conclude that $u^{-1}+iu$ is constant?


Check if the site allows new user registration

Question: In Drupal 7, on my frontpage custom template, i want to show a text if the site is allowing new users to register.
Any clues?
Thanks
Comment: You can do a variable_get call in template.php to check the value of the registration state, but I can't recall he name of the variable. It's located in the variables database table. Based on that value you can create a new template variable to show a message.
Answer: In a preprocess function for your template, add code something like:
$variables['is_registration_open'] = variable_get('user_register') == USER_REGISTER_VISITORS;

Then in your template:
<?php if ($is_registration_open) : ?>

Registration is open!

<?php endif; ?>


What does the "+" symbol mean in a keyboard piece when attached to a note?

Question: In a Daquin pipe organ piece, "Noël «Suisse»" from his "Livre de Noëls", I see this notation in the Right Hand system:

This is notated this way in the Oxford Book of Christmas Organ Music. How should I play the chord that has a "+" sign under it?
Answer: I found the below footnote in a transcription on IMSLP:

It translates:

I think that one could play the + sign, as a 'pinched' lower mordent.

Where this is first notated, it applies to the sign above a single note in the right hand, however, there are further places where the same notation is used on chords, and below the notes, without further comment from the transcriber, so I'd imagine the same still stands in these cases. (I'd also say it fits with the style of the music, and isn't impossible to play, no?)
This transcription is an extract from "Archives des Maitres de l'Orgue" (Archives of the masters of the organ) - written by Alex Guilmant (The annotator) and A. Pirro. It is dated 1903.
[Source]
Answer: Check this out.

Thumbing is the act of playing with one or both thumbs on the keyboard
  below the keyboard on which the rest of fingers are playing. This
  technique was developed in the late 19th century, and fell out of use
  after 1930. While at first an organist not used to this technique will
  only be able to use it to play isolated sustained pitches, organists
  accustomed to this technique are capable of playing moving lines,
  although the speed possible is less than that of using all five
  fingers. A composer who wants to use this technique would be wise to
  spend some time at an organ console to find out what is physically
  possible as far as the reach of a hand. Failing that, a composer
  should refer to a piano keyboard to verify that the requested hand
  positions are comfortably possible. When notating a passage using this
  technique, one should place the notes to be thumbed on a separate
  staff between the "right hand" and "left hand" staves. One should also
  mark the notes to be thumbed with a "+" symbol.
Comment: As interesting as this is, Daquin was active mid-18th century - I wouldn't have said the time periods really fit.
Comment: I expect that it's either pedagogical or whoever transcribed it wasn't thinking about time periods.
Comment: Hm. [Another thought](http://www.organforum.com/forums/showthread.php?30156-Need-help-reading-this-music) Not a terribly reliable source, but a user named Sathrandur on this forum states that it could be old notation designating a trill. Not sure how that'd work in this context, though.
Answer: This page is useful http://en.wikipedia.org/wiki/List_of_musical_symbols#Articulation_marks
It says:

Left-hand pizzicato or Stopped note
A note on a stringed instrument where the string is plucked with the
  left hand (the hand that usually stops the strings) rather than bowed.
  On the horn, this accent indicates a "stopped note" (a note played
  with the stopping hand shoved further into the bell of the horn). In
  percussion notation this denotes, among many other specific uses, that
  the hi-hat is to be closed by pressing the pedal or that an instrument
  is to be "choked" (silenced by causing vibrations to cease).

I hope it makes sense in the context!
Comment: In some musical pieces since around 1980 the sign is used to indicate a stopped or muted note on the piano -- place a finger near the pegs on the strings to be struck. It creates a muted sound. I've never seen it used for pizz. on a piano. In this older example, however, the accepted answer is the correct interpretation.
Answer: I have several recordings of the Noels and don't remember anything special here. In the second bar (the piece starts with your given bars, doesn't it?) it is not striking to be the standard symbol for an unspecified ornamentation. I observe however, that both systems being in the treble clef, on a one-manual instrument the right hand has to give way to the left, so it can use the same keys.


Spring Boot - Erro java.lang.IllegalArgumentException: Not an managed type

Question: estou com um erro no Spring e não estou conseguindo entender muito bem o que está acontecendo, poderiam me ajudar?

LOG

09:25:43.038 [main] ERROR o.s.boot.SpringApplication - Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'listarVeiculosController': Unsatisfied dependency expressed through field 'veiculoRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'veiculoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class br.com.itau.ev9.fuse.model.VeiculoCotacao
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:569)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:349)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1219)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:751)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175)
    at br.com.itau.ev9.fuse.App.main(App.java:35)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'veiculoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class br.com.itau.ev9.fuse.model.VeiculoCotacao
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:207)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1128)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1056)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:566)
    ... 19 common frames omitted
Caused by: java.lang.IllegalArgumentException: Not an managed type: class br.com.itau.ev9.fuse.model.VeiculoCotacao
    at org.hibernate.ejb.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:200)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:70)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:67)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:152)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:99)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:81)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:266)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:252)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
    ... 29 common frames omitted

listarVeiculosController

@Controller
public class ListarVeiculosController {

    @Autowired
    VeiculoRepository veiculoRepository;

    public void request(Exchange exchange) {
        try {
            RetornoData data = new RetornoData();
            List<BuscarVeiculosDTO> listaResponse = new ArrayList();
            List<VeiculoCotacao> listaVeiculos = new ArrayList();

            int anoModelo = Integer.parseInt(exchange.getProperty("year").toString());
            String stringPesquisa = exchange.getProperty("search_terms").toString();
            Boolean zeroKm = Boolean.parseBoolean(exchange.getProperty("zero_km").toString());

            //listaVeiculos = (List<VeiculoCotacao>) veiculoRepository.findBySearchTerms(anoModelo, stringPesquisa);
            listaVeiculos = (List<VeiculoCotacao>) veiculoRepository.findAll();

            for (VeiculoCotacao veiculoCotacao : listaVeiculos) {
                BuscarVeiculosDTO veiculo = new BuscarVeiculosDTO();

                veiculo.setCodigoMolicar(veiculoCotacao.getCdMolicar());
                veiculo.setMarca(veiculoCotacao.getMarca());
                veiculo.setModelo(veiculoCotacao.getModelo());

                listaResponse.add(veiculo);
            }

            data.setData(listaResponse);
            exchange.getIn().setBody(data);

        } catch (Exception e) {
            exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, HttpStatus.INTERNAL_SERVER_ERROR);
            exchange.setException(new VeiculoException(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()));
        }
    }
}

VeiculoCotacao.java

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class VeiculoCotacao {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    private int idICarros;
    private int anoInicial;
    private int anoFinal;
    private String marca;
    private String modelo;
    private String cdMolicar;

    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public int getIdICarros() {
        return idICarros;
    }
    public void setIdICarros(int idICarros) {
        this.idICarros = idICarros;
    }
    public int getAnoInicial() {
        return anoInicial;
    }
    public void setAnoInicial(int anoInicial) {
        this.anoInicial = anoInicial;
    }
    public int getAnoFinal() {
        return anoFinal;
    }
    public void setAnoFinal(int anoFinal) {
        this.anoFinal = anoFinal;
    }
    public String getMarca() {
        return marca;
    }
    public void setMarca(String marca) {
        this.marca = marca;
    }
    public String getModelo() {
        return modelo;
    }
    public void setModelo(String modelo) {
        this.modelo = modelo;
    }
    public String getCdMolicar() {
        return cdMolicar;
    }
    public void setCdMolicar(String cdMolicar) {
        this.cdMolicar = cdMolicar;
    }

}

VeiculoRepository.java

import java.util.List;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import br.com.itau.ev9.fuse.model.VeiculoCotacao;

@Repository
public interface VeiculoRepository extends CrudRepository<VeiculoCotacao, Integer>{

}

Comment: Você pode colocar também sua classe de configuração?
Answer: Pela sua stacktrace:
Caused by: java.lang.IllegalArgumentException: Not an managed type: class br.com.itau.ev9.fuse.model.VeiculoCotacao

O que acontece é que sua classe VeiculoCotacao não está sendo reconhecida como uma entidade de persistência, provavelmente por falta de configuração.
Você pode indicar o pacote onde esta entidade se encontra através da seguinte anotação em sua aplicação/configuração:
@EntityScan(basePackages = {"br.com.itau.ev9.fuse.model"})

É importante reforçar que caso você possua outros pacotes com entidades e não estejam abaixo da hierarquia da sua classe de aplicação, eles devem ser referenciados no array acima.

Incluindo também o link para a documentação do @EntityScan:

Configures the base packages used by auto-configuration when scanning
  for entity classes.
Using @EntityScan will cause auto-configuration to:
Set the packages scanned for JPA entities.
Set the packages used with Neo4J's SessionFactory.
Set the initial entity set used with Spring Data MongoDB, Cassandra and Couchbase mapping contexts.

One of basePackageClasses(), basePackages() or its alias value() may
  be specified to define specific packages to scan. If specific packages
  are not defined scanning will occur from the package of the class with
  this annotation.
Answer: Em versões anterior a SpringBoot 3.x.x, você usaria o javax.persistence na classe Model, na versão SpringBoot 3.x.x, você deve usar jakarta.persistence.


PHP: How to create a linear function, calculating a credit card fee?

Question: I'm working on a PHP project for a customer who has to receive credit card payments.
Most merchants offer an fixed pricing of 2.9% + 2.25 DKK. Right now, I'm able to calculate my fee using;
$price = 10;
$fee = ($price*0.029)+2.25;
// $fee = 2.54

So, as of now, the visitor will pay 12.54 DKK, but of course there will be added fees to my inserted "user-pays-fees", and my customer would still have to pay 2.61366 DKK for the transaction, leaving 9.92634 DKK for withdrawal, instead of pure 10 DKK.
Inserting the formula in e.g. GeoGebra, it is y = 1.029x + 2.25, if that is any help? The Y-axis represents how much the visitor is charged, and the X-axis represents how much is withdrawable.
So, my question is: How do I formulate a linear function that calculates backwards and defines $price from what should be withdrawable (with PHP)?
Comment: I'm voting to close this question as off-topic because this is a simple math question.
Comment: that's basic algebra. you've got `y= stuff with x`. reverse it and have `x = stuff with y`.
Comment: @MarcB I updated the question as you wrote your comment, and I know the linear algebra formular, `y = 1.029x + 2.25`, but I'm not sure how to reverse it? And how to insert it into a PHP-script?
Comment: like I said. it's basic algebra. write it out on paper, and solve for X instead of Y.
Comment: @MarcB Well, I obviosly can't figure it out myself. Could you might point me a little further, in the right direction ;)?
Answer: I've got what you want, so think in this way:

you have original price
you want to calculate final transferAmount

that:
transferAmount = originalPrice + fee

but fee here depends on transferAmount
fee = transferAmount * 0.029 + 2.25

now solve it:
transferAmount = originalPrice + transferAmount * 0.029 + 2.25
transferAmount*(1-0.029) = originalPrice + 2.25
transferAmount = (originalPrice + 2.25) / (1-0.029)

in php:
$price = 10;
$total = ($price + 2.25) / (1.0 - 0.029); // 12.615859938208033
$fee = $total - $price; // 2.6158599382080325

now you can verify:
12.615... * 0.029 + 2.25 = 2.615...

ie, merchant will take 2.615... as fee and result is 10
Comment: That is exactly the code I listed above. Your code doesn't keep in mind, that there will be added fees on top of `$totalprice`
Comment: @JonathanBredoChristensen what is added fees? how they are calculated?
Comment: As described in my question, they are substracted from the transfered amount, leaving a little less withdrawable. The fees are 2.9% + 2.25
Comment: @JonathanBredoChristensen finally got you
Comment: Sorry, @Lashane, but it's still not the answer. The merchant will still collect a fee on top of the defined fee, why the formular should go backwards. Basically, your code is the exact same as mine.
Comment: @JonathanBredoChristensen no, `$total` will be 2.615859 with updated formula, and merchant will subtract 2.615, so your customer finally get 10.0 as expected
Comment: Sorry, I misread your code - it works perfect now!
Answer: Do you mean that given fee=2.59, you want the base price?
In this case, you could do:
$feeMinusTax = $fee-2.25;
$originalPrice = $feeMinusTax/0.029;


favourite and unfavourite image in recyclerview gets in initial state when scrolled

Question: I have a recycler adapter in which there are  3 image buttons, one of them is for favorite and unfavorite. when the recyclerviews loads its loads proper also when I click on favorite it stores in my favorite list. But the problem is that when I scrolled it the states of image button changes to load time images.
Comment: Can you please edit your post and add the code for your adapter?
Answer: Make sure you are setting favorite/unfavorite at onBindViewHolder.
Comment: thanks for you reply i have already placed it in the onBindViewHolder
Answer: RecyclerView efficiently recycles views while you scroll.
when you maintain this kind of scenario, where image view can have Fav or UnFav images. you need to maintain both in onBindVIewHolder() method such as
if (isFav) {
viewHolder.yourImage.setBackgroundDrawable(FavImage);
} else {
viewHolder.yourImage.setBackgroundDrawable(UnFavImage);
}

Comment: thanks for you reply i have already tried for this. on click it is changing but the problem is on scrolled when i scroll it all the default states of the icon is restored.
Answer: Try setting the image on the #onBindViewHolder on every case (don't assume that you know the current state).


Unity3D Linux Build crashes on start. (Ubuntu 16.04 LTS)

Question: I am struggling in making Unity3D Build working in Ubuntu Linux Environment.
I just created an empty scene without any objects build a linux distribution, but it crashes in linux and giving following error.
'/home/jayanth/Desktop/EmptyLinuxTest/Empty_Linux.x86'
Found path: /home/jayanth/Desktop/EmptyLinuxTest/Empty_Linux.x86
Mono path[0] ='/home/jayanth/Desktop/EmptyLinuxTest/Empty_Linux_Data/Managed'
Mono path[1] = '/home/jayanth/Desktop/EmptyLinuxTest/Empty_Linux_Data/Mono'
Mono config path = '/home/jayanth/Desktop/EmptyLinuxTest/Empty_Linux_Data/Mono/etc'
displaymanager : xrandr version warning. 1.5
client has 2 screens
displaymanager screen (0)(VGA-0): 1368 x 768
Using libudev for joystick management

Importing game controller configs
Aborted (core dumped)

Here is the Player.log file output.
Selecting FBConfig
GLX_FBCONFIG_ID=227
GLX_BUFFER_SIZE=32
GLX_DOUBLEBUFFER=1
GLX_RED_SIZE=8
GLX_GREEN_SIZE=8
GLX_BLUE_SIZE=8
GLX_ALPHA_SIZE=8
GLX_DEPTH_SIZE=24
GLX_STENCIL_SIZE=8
GLX_SAMPLES_ARB=0
GLX_SAMPLE_BUFFERS_ARB=0
GLX_STEREO=0
GLX_CONFIG_CAVEAT=NONE

Desktop is 1368 x 768 @ 60 Hz
XError: BadMatch (invalid parameter attributes) (error 8, opcode 154/34, serial 37, XID 00000004, display 0xa96bdf0
XError: BadMatch (invalid parameter attributes) (error 8, opcode 154/34, serial 40, XID 00000004, display 0xa96bdf0
XError: BadMatch (invalid parameter attributes) (error 8, opcode 154/34, serial 43, XID 00000004, displaterminate called after throwing an instance of    'std::logic_error'
what():  basic_string::_S_construct null not valid

Stacktrace:
Native stacktrace:

/home/jayanth/Desktop/EmptyLinuxTest/Empty_Linux_Data/Mono/x86/libmono.so(+0x8960f) [0xb4da760f]
[0xb775cc20]
[0xb775cc31]
/lib/i386-linux-gnu/libc.so.6(gsignal+0x39) [0xb7160e89]
/lib/i386-linux-gnu/libc.so.6(abort+0x157) [0xb71623e7]
/usr/lib/i386-linux-gnu/libstdc++.so.6(_ZN9__gnu_cxx27__verbose_terminate_handlerEv+0x155) [0xb73cfd45]
/usr/lib/i386-linux-gnu/libstdc++.so.6(+0x70843) [0xb73cd843]
/usr/lib/i386-linux-gnu/libstdc++.so.6(+0x708bd) [0xb73cd8bd]
/usr/lib/i386-linux-gnu/libstdc++.so.6(__cxa_rethrow+0) [0xb73cdb80]
/usr/lib/i386-linux-gnu/libstdc++.so.6(_ZSt19__throw_logic_errorPKc+0x44) [0xb73f78b4]
./Empty_Linux.x86() [0x8b66b48]
./Empty_Linux.x86() [0x8b5802e]
./Empty_Linux.x86() [0x8b4a2ba]
./Empty_Linux.x86() [0x8b568c9]
./Empty_Linux.x86() [0x8adb803]
./Empty_Linux.x86() [0x8ad81f7]
./Empty_Linux.x86() [0x82ce6bf]
./Empty_Linux.x86() [0x83efceb]
./Empty_Linux.x86() [0x83c6c12]
./Empty_Linux.x86() [0x808e473]
/lib/i386-linux-gnu/libc.so.6(__libc_start_main+0xf7) [0xb714d637]
./Empty_Linux.x86() [0x80988e9]

Debug info from gdb:
Could not attach to process.  If your uid matches the uid of the target
process, check the setting of /proc/sys/kernel/yama/ptrace_scope, or try
again as the root user.  For more details, see /etc/sysctl.d/10-ptrace.conf
ptrace: Operation not permitted.
No threads.

=================================================================
Got a SIGABRT while executing native code. This usually indicates
a fatal error in the mono runtime or one of the native libraries
used by your application.
=================================================================

It would be glad if someone help me out in this issue.
Thanks
Comment: you're using a joystick or similar ??
Comment: No, I am NOT using any joystick. Same build if I am making for Windows/Mac its working perfectly fine, but NOT sure why it is creating problem in Linux
Comment: Same issue here @Niks, did you happen to solve it?
Answer: The line "terminate called after throwing an instance of 'std::logic_error'
what():  basic_string::_S_construct null not valid" in your logs suggests that Unity3d is trying to construct a std::string object from a null pointer which is undefined behaviour according to the C++ standard & current libstdc++ versions throw a std::logic_error exception if your code tries to do that.
This may well be a bug in Unity itself - there are a few complaints about similar errors dotted around if you search the net.
Comment: Well, just for random test, I installed a nVidia Graphics card in my system and then it started working in linux but still it was damn slow. I can't conclude on anything as the same is working in windows without graphics card and in the same system. So, I think Unity is still NOT completely ready for Linux (May be) ...


UrlEncode through a console application?

Question: Normally I would just use:
HttpContext.Current.Server.UrlEncode("url");

But since this is a console application, HttpContext.Current is always going to be null.
Is there another method that does the same thing that I could use?
Answer: Try this!
Uri.EscapeUriString(url);

Or
Uri.EscapeDataString(data)

No need to reference System.Web.
Edit: Please see another SO answer for more...
Comment: This does not be the same as ```HttpUtility.UrlEncode``` while @KevinUK asked for Encode.
Comment: This is a far better answer, because you don't have to import new references to the console app, since the `Uri` class is in `System`.
Comment: The results for this method are completely different to UrlEncode. There are several elements which will not be encoded correctly for a URL string (for example '+'. Either use HttpUtility.UrlEncode or Uri.EscapeDataString as explained very well here: https://stackoverflow.com/a/34189188/7391
Comment: Not sure why this was down-voted; maybe the edit fixed something? Anyhow, it's a good answer. For more info, see [this answer](http://stackoverflow.com/a/8451941/530545) from another, similar question.
Comment: Works great and you don't need to add any refference.
Answer: I'm not a .NET guy, but, can't you use:
HttpUtility.UrlEncode Method (String)

Which is described here:
HttpUtility.UrlEncode Method (String) on MSDN
Comment: You need (must) add System.Web as a reference.  Simply putting using System.Web is not enough
Comment: I don't want to rain on everyone's parade, but the mentioned HttpUtility.UrlEncode doesn't seem to be visible even when I include "using System.Web".  Does this actually work for someone and if so can you include the actual code?
Comment: Problem is you will get something like this: The referenced assembly ".." could not be resolved because it has a dependency on "System.Web ...". Two options - either change the target framework to not use the client profile, or use the C# example given by t3rse elsewhere on this page.
Comment: I knew about System.Web.HttpContext but it wasn't resolving.  Thanks Anjisan for pointing out that I needed to add System.Web as a reference.  +1 from me!
Answer: The code from Ian Hopkins does the trick for me without having to add a reference to System.Web. Here is a port to C# for those who are not using VB.NET:
///
/// URL encoding class.  Note: use at your own risk.
/// Written by: Ian Hopkins (http://www.lucidhelix.com)
/// Date: 2008-Dec-23
/// (Ported to C# by t3rse (http://www.t3rse.com))
///
public class UrlHelper
{
    public static string Encode(string str) {
        var charClass = String.Format("0-9a-zA-Z{0}", Regex.Escape("-_.!~*'()"));
        return Regex.Replace(str,
            String.Format("[^{0}]", charClass),
            new MatchEvaluator(EncodeEvaluator));
    }

    public static string EncodeEvaluator(Match match)
    {
        return (match.Value == " ")?"+" : String.Format("%{0:X2}", Convert.ToInt32(match.Value[0]));
    }

    public static string DecodeEvaluator(Match match) {
        return Convert.ToChar(int.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber)).ToString();
    }

    public static string Decode(string str)
    {
        return Regex.Replace(str.Replace('+', ' '), "%[0-9a-zA-Z][0-9a-zA-Z]", new MatchEvaluator(DecodeEvaluator));
    }
}

Comment: Great work both t3rse and Ian Hopkins.  I ran into this issue building a wpf application.  wpf uses the slimmed down 'client profile' of .net while my class library was using the full version.  Only the full version of .net has access to System.Web which contains HttpUtility.UrlEncode.
Answer: Add using System.Net; then use: WebUtility.UrlDecode(string)
or Fully-Qualify: System.Net.WebUtility.UrlDecode(string)
No need to add any additional References.
The WebUtility is included (by Default) in System (under the "References" Project Folder).
Comment: Good to mention this method is available since .NET 4.0.
Answer: You'll want to use
System.Web.HttpUtility.urlencode("url")

Make sure you have system.web as one of the references in your project.  I don't think it's included as a reference by default in console applications.
Answer: Try using the UrlEncode method in the HttpUtility class.

http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx
Answer: I ran into this problem myself, and rather than add the System.Web assembly to my project, I wrote a class for encoding/decoding URLs (its pretty simple, and I've done some testing, but not a lot).  I've included the source code below.  Please: leave the comment at the top if you reuse this, don't blame me if it breaks, learn from the code.
'''
''' URL encoding class.  Note: use at your own risk.
''' Written by: Ian Hopkins (http://www.lucidhelix.com)
''' Date: 2008-Dec-23
'''
Public Class UrlHelper
    Public Shared Function Encode(ByVal str As String) As String
        Dim charClass = String.Format("0-9a-zA-Z{0}", Regex.Escape("-_.!~*'()"))
        Dim pattern = String.Format("[^{0}]", charClass)
        Dim evaluator As New MatchEvaluator(AddressOf EncodeEvaluator)

        ' replace the encoded characters
        Return Regex.Replace(str, pattern, evaluator)
    End Function

    Private Shared Function EncodeEvaluator(ByVal match As Match) As String
    ' Replace the " "s with "+"s
        If (match.Value = " ") Then
            Return "+"
        End If
        Return String.Format("%{0:X2}", Convert.ToInt32(match.Value.Chars(0)))
    End Function

    Public Shared Function Decode(ByVal str As String) As String
        Dim evaluator As New MatchEvaluator(AddressOf DecodeEvaluator)

        ' Replace the "+"s with " "s
        str = str.Replace("+"c, " "c)

        ' Replace the encoded characters
        Return Regex.Replace(str, "%[0-9a-zA-Z][0-9a-zA-Z]", evaluator)
    End Function

    Private Shared Function DecodeEvaluator(ByVal match As Match) As String
        Return "" + Convert.ToChar(Integer.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber))
    End Function
End Class

Comment: downvoted... writing your own code so you can avoid a reference to a standard lib that doesn't write is "A Bad Thing" typically.
Comment: I have to agree with Justin here
Answer: Kibbee offers the real answer.  Yes, HttpUtility.UrlEncode is the right method to use, but it will not be available by default for a console application.  You must add a reference to System.Web.  To do that,

In your solution explorer, right click on references
Choose "add reference"
In the "Add Reference" dialog box, use the .NET tab
Scroll down to System.Web, select that, and hit ok

NOW you can use the UrlEncode method.  You'll still want to add,
using System.Web
at the top of your console app or use the full namespace when calling the method,
System.Web.HttpUtility.UrlEncode(someString)
Answer: HttpUtility.UrlEncode("url") in System.Web.
Answer: use the static HttpUtility.UrlEncode method.
Answer: Best thing is to Add Reference to System.web..dll
and use
var EncodedUrl=System.Web.HttpUtility.UrlEncode("URL_TEXT");
You can find the File at System.web.dll
Answer: Uri.EscapeUriString should not be used for escaping a string to be passed in a URL as it does not encode all characters as you might expect. The '+' is a good example which is not escaped. This then gets converted to a space in the URL since this is what it means in a simple URI. Obviously that causes massive issues the minute you try and pass something like a base 64 encoded string in the URL and spaces appear all over your string at the receiving end.
You can use HttpUtility.UrlEncode and add the required references to your project (and if you're communicating with a web application then I see no reason why you shouldn't do this).
Alternatively use Uri.EscapeDataString over Uri.EscapeUriString as explained very well here: https://stackoverflow.com/a/34189188/7391


Write a scalar equation of each plane, given its parametric equations

Question:
Given:
  $$x=3-2s+2t$$
$$y=1+3s+t$$
$$z=5-s-2t$$

I am truly confused, would anybody be able to help me please.
Answer: You have a point, $P(3,1,5)$ and two vectors$V=<2,1,-2>$ and $ W=<-2,3,-1>$ on your plane.
The normal to your plane is the cross product of $V$ and $W$.
Find $ N=V\times W = <a,b,c>$.
The equation of the plane is $$ax+by+cz=d $$ where you can find your $d$ from the given point on the plane.
Comment: How did you find those two vectors?
Comment: $t=0$ gives you one line and $s=0 $gives you another line. The direction vectors of those lines are these vectors.
Comment: Would you be able to show that, if you don't mind.
Comment: The cross product is $<5,6,8>$  and the equation is $5x+6y+8z = 61$
Comment: Would you be able to show how you got the two vectors
Comment: I have answered this question in my first comment above.


Estou com um problema na relação entre duas tabelas em SQlite usando python/django

Question: estou fazendo um CRUD simples, usando  2 tabelas, a user padrão do django e a cidadão que criei, estou usando uma foreinkey username para linkar as duas, porem no form, ao invés de aparecer um username(que é do usuário logado), aparece de todos os usuários já cadastrados.
codigo models.py
from django.db import models
from django.contrib.auth.models import User

class Cidadao(models.Model):
    nomecompleto = models.CharField(max_length=100)
    endereco = models.CharField(max_length=100)
    email = models.EmailField()
    nomebens = models.CharField(max_length=100)
    numSerie = models.CharField(max_length=100)
    observacao = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.user

codigo views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from cidadania3.forms import CidadaoForm
from cidadania3.models import Cidadao

# Create your views here.
def home(request):
    data = {}
    search = request.GET.get('search')
    if search:
        data['db'] = Cidadao.objects.filter(email__icontains=search, user=request.user)

    else:
        data['db'] = Cidadao.objects.all().filter(user=request.user)
    return render(request, 'index.html', data)

@login_required
def form(request):
    Cidadao.objects.all().filter(user=request.user)
    data = {}
    data['form'] = CidadaoForm()
    return render(request, 'form.html', data)

def create(request):
    form = CidadaoForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('home')

@login_required
def view(request, pk):
    data = {}
    data['db'] = Cidadao.objects.get(pk=pk)
    return render(request, 'view.html', data)

@login_required
def edit(request, pk):
    data = {}
    data['db'] = Cidadao.objects.get(pk=pk)
    data['form'] = CidadaoForm(instance=data['db'])
    return render(request, 'form.html', data)

@login_required
def update(request, pk):
    data = {}
    data['db'] = Cidadao.objects.get(pk=pk)
    form = CidadaoForm(request.POST or None, instance=data['db'])
    if form.is_valid():
        form.save()
    return redirect('home')

@login_required
def delete(request, pk):
    db = Cidadao.objects.get(pk=pk)
    db.delete()
    return redirect('home')

código forms.py
from django.forms import ModelForm
from cidadania3.models import Cidadao

# Create the form class.
class CidadaoForm(ModelForm):
   class Meta:
      model = Cidadao
      fields = ['nomecompleto', 'endereco', 'email', 'nomebens', 'numSerie', 'observacao', 'user']

Na parte de usuario era para estar somente o usuario cadastrado(que é o nome setado no botão acima )
Obrigado desde já.
Código Urls.py
from django.contrib import admin
from django.urls import path, include
from cidadania3.views import home, form, create, view, edit, update, delete

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home, name='home'),
    path('form/', form, name='form'),
    path('create/', create, name='create'),
    path('view/<int:pk>/', view, name='view'),
    path('edit/<int:pk>/', edit, name='edit'),
    path('update/<int:pk>/', update, name='update'),
    path('delete/<int:pk>/', delete, name='delete'),
    path('accounts/', include('accounts.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
]

Comment: Poderia atualizar se post com o urls.py também?
Answer: Parece que seu método form está equivocado. Em primeiro ligar sugiro trocar o nome do método para alguma coisa mais intuitiva para entendimento (ex. cadastro_cidadao)
@login_required()
def cadastro_cidadao(request):
    if request.method == 'POST':
        form = CreateCidadao(request.POST)
        if form.save(request.user):
            return redirect(reverse('core:home'))  # Ou para onde vc quiser retornar
    else:
        cidado_instance = Cidadao.objects.all().filter(user=request.user)
        form = CreateCidadao(instance=cidadao_instance)
    return render(request, 'cidadao.html', {'form': form})

Já cidadao.html seria algo como:
{% extends 'base.html'%}

{% load static from static %}

{% block content %}

Cidadao

    <form method="POST">
        {% csrf_token %}
        {% form %}
    </form>
{% endblock content %}


Rsync over ssh: "ERROR: module is read only" suddenly appeared

Question: I've used from some time rsync/ssh to backup my shared host contents to my personal Synology NAS (212j for that matter), and it worked quite well.
For information, I use a password-less ssh connection.
3 days ago, I updated my NAS software and since (or at least I believe it's since that), the backup won't work anymore.
I get the following error on the host:
rsync: writefd_unbuffered failed to write 4 bytes to socket [sender]: Broken pipe (32)
ERROR: module is read only

..which I do not understand. beside that nothing changed that I know of in both source and destination that can be related to rsync or ssh, I did check a few things and all seems to be alright:

I can still connect through ssh from the host to my NAS with the good user, so ssh stuff like keys haven't changed.
I also have the correct file permissions on the NAS (I checked, and also tried to create files, directories, .. with the user used by rsync through ssh).

I read here and there that the error means that I have to ensure that my rsyncd.conf have the right read only = no in it, but as far as I know, I never used rsyncd as well as I never configured anything for it and until now it worked like a charm..
I use the following command to do the backup:
rsync -ab --recursive \
--files-from="$FILES_FROM" \
--backup-dir=backup_$SUFFIX \
--delete \
--filter='protect backup_*' \
$WDIRECTORY/ \
remote_backup:$REMOTE_BACKUP/

So I'm stuck and really can't figure out what happened.

Edit:
As suggested in comments, I also tried passing commands to ssh (but not from inside a ssh session), that worked as expected, and also tried a single rsync command, which didnt worked, failing just like the complete backup command.
(sharedHost):hostuser:~ > touch test.txt
(sharedHost):hostuser:~ > rsync test.txt remote_backup:backups/test.txt
ERROR: module is read only
rsync error: syntax or usage error (code 1) at main.c(1034) [Receiver=3.0.8]
rsync: connection unexpectedly closed (9 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(601) [sender=3.0.7]

and
(sharedHost):hostuser:~ > ssh remote_backup 'touch /abs_path_to_backups/backups/test2.txt && echo "ProoF" > /abs_path_to_backups/backups/test2.txt'
(sharedHost):hostuser:~ > ssh remote_backup 'cat /abs_path_to_backups/backups/test2.txt'
ProoF

Comment: Try doing the remote update tests, but with commands given to ssh on the command line instead of through a ssh login session.  Also be sure the target space is not full.
Comment: Thanks for your suggestions. I edited the question with their result. Also, the target space is not full at all (I was already sure, but I checked again)
Answer: I had the same problem after updating my Synology NAS to DSM 4.1. I also do rsync over SSH. In my situation using rsync user root@ip also worked but left the files on the server with owner root which I did not want.
I found in the NAS admin userinterface, that for some reason in ControlPanel->Users->MyRSyncUser->Edit->"Priviliges setup" there was no read/write access to the homes. My RSYNC destination is under the homes.
Setting this to privilidge worked for me. I hope this helps.
Comment: This seems to work if I use full path names (i.e., `rsync something nas:/volume2/homes/foo/bar/` instead of `rsync something nas:bar/`).
Comment: I had this problem, but it wasn't caused by permissions, but simply by misspelling the remote path. the Synology rsync will not tell you that -- just that the path you specify is "read only"
Comment: The problem with this solution (I've not found a better one) is that it gives the user privileges on all user homes, not just their own.
Comment: Thank you so much ! That worked ! Next time I update DSM, I'll double-check the permissions..
Comment: full path was the last step for me in annoying bout of debugging. thanks!
Comment: In my case (with a newer version I assume), I also had to change to module based syntax ( see https://superuser.com/questions/559047/cant-rsync-locally-on-synology-nas/1532718#1532718 )
Comment: Mine was a similar issue as @dovetalk. Except I didnt mispell so much as using the wrong case. ie, Trying to pull files from a remote path of /Volume1/etc.. when it should have been /volume1/etc..
Answer: I got rid of ERROR: module is read only by changing the remote path from /var/services/homes/rsync to /volume2/homes/rsync
DSM 5.1
Comment: Yes this worked for me too: You definitely need the volume in the DiskStation path:
 USERNAME@DiskStation:/volume1/somebackupDir    works,

USERNAME@DiskStation:/somebackupDir    gives error

`receiving incremental file list
ERROR: module is write only
rsync error: syntax or usage error (code 1) at main.c(782) [sender=3.0.9]`
Answer: I encountered the same problem after upgrading a synology ds1010+ to dsm 4.1-2661.
I don't have the time to understand what happened to the rsync provided by synology but it does not seem standard.
So here is my workaround...
I didn't want to hack the privileges (multi-user setup), so I've recompiled rsync in static on my laptop, then I've transfered the binary on the sinology nas.
wget https://rsync.samba.org/ftp/rsync/rsync-3.0.9.tar.gz
tar xzvf rsync-3.0.9.tar.gz
cd rsync-3.0.9
export CFLAGS=--static
./configure
make

scp rsync <login>@<nas_hostname>:

You can tell rsync to use your new binary instead of the default one, with this parameter:
--rsync-path=<myhome>/rsync

Now I can continue using duplicity with rsync, by adding the following parameter to duplicity:
--rsync-options="--rsync-path=<myhome>/rsync"

Comment: This is what I did with my DS212j, except I used ipkg to install the new rsync.  Synology's directions for installing ipkg are [here](http://forum.synology.com/wiki/index.php/Overview_on_modifying_the_Synology_Server,_bootstrap,_ipkg_etc#for_compiled.2Fbinary_programs).
Comment: I couldn't find anything on ipkg for DSM 5.2, so for my DS215j I did as follows to compile (I already had the cross-compiler arm-unknown-eabi-gcc lying around) `./configure --host=armv7 CFLAGS=-static EXEEXT=-static --prefix=/opt CC=arm-unknown-linux-gnueabi-gcc && make && arm-unknown-linux-gnueabi-strip rsync && make DESTDIR=$PWD/../prefix install`. Put the binary in /opt/bin/ on the NAS. Also have to give my backup user a shell in /etc/passwd by changing /sbin/nologin to /bin/sh (There should be some more secure options).
Answer: I had the same kind of issue, but I wasn't using a dedicated user for rsync.
I had to fix privileges in Control Panel -> Shared folders.
Answer: I had similar issue while connecting to Synology 211j over Putty's ssh. I had to enable
"Control Panel -> Network backup -> Enable network backup service".
It is working now.
Answer: I got it working by logging in as root instead of admin or regular user.