Parabolic PDE with no nonnegative solution

Question: I am looking for a simple example of a second-order parabolic linear PDE with locally bounded coefficients on an unbounded domain which admits no nonnegative solutions (except the trivial one).
As a candidate, I am considering:
$$(\partial_t - \partial_{xx} - f)u = 0 \tag{*}$$
on the domain $(0,T) \times \mathbb{R}$, where $f \ge 0$ is some rapidly growing function of $x$, such as $f(x) = e^{x^4}$.  Let us concentrate on classical solutions and require $u \in C^{1,2}((0,T) \times \mathbb{R}$.
Intuitively, the zero-order term $f$ should be inflating the function $u$ much faster than the second-order term $\partial_{xx}$ can diffuse it, forcing the solution to become infinite immediately.  But I do not quite see how to prove this.
As a start, we can see that any nonnegative solution of (*) is a supersolution of the heat equation
$$(\partial_t - \partial_{xx}) u \ge 0$$
and so obeys the strong minimum principle.  Thus $u$ must be strictly positive everywhere, hence bounded away from zero on compact sets.  Using the minimum principle to compare $u$ with solutions of the heat equation, we can get that for all $t \ge \epsilon$, $u(x,t) \ge C e^{-c x^2}$ for some $C,c$.
If I could get some control on the negative part of $\partial_{xx} u$, I could get something like $\partial_t u \ge fu \ge C' e^{x^4}$ for $t \approx \epsilon$.  This would imply, by the mean value theorem, that $u(2\epsilon, x) \approx C'' \epsilon e^{x^4}$.  Now the heat equation with initial conditions $e^{x^4}$ blows up, which is to say I can find arbitrarily large solutions $v_n \uparrow \infty$ of the heat equation whose values at time $2\epsilon$ are bounded by $e^{x^4}$.  By the minimum principle, on $(2\epsilon, T)$, $u \ge v_n$ for all $n$, so $u \equiv \infty$.
I'd be interested in any suggestions to fix this gap, or other approaches.  Thanks!
Answer: Disclaimer: this is a formal manipulation. It may be illegal, but I don't see it as morally reprehensible. Perhaps replacing $e^{-x^2/\alpha}$ with a compactly supported version of this function can make this rigorous.
Assuming that the solution remains smooth for all times $t<T$, we must have
$$E_\alpha(t):=\int_{\mathbb R} u(x,t)e^{-x^2/\alpha}<\infty $$
for all $t<T/2$ and all $\alpha<T/2$ (otherwise the solution blows up before time $T$ even without further input from $f$). The function $E_\alpha$ ought to be smooth for any such value of parameter $\alpha$. Differentiate it with respect to $t$:
$$E_\alpha'(t)= \int_{\mathbb R} u_t (x,t)e^{-x^2/\alpha} =
\int_{\mathbb R} u_{xx}(x,t)e^{-x^2/\alpha} +
\int_{\mathbb R} u(x,t)e^{x^4-x^2/\alpha}$$
Integrate the first term by parts:
$$\int_{\mathbb R} u_{xx}(x,t)e^{-x^2/\alpha}
=\int_{\mathbb R} u(x,t)(4x^2/\alpha^2-2/\alpha)e^{-x^2/\alpha} $$
This integral converges because $x^2e^{-x^2/\alpha} \lesssim e^{-x^2/\beta}$ for any $\beta>\alpha$, and we can take $\beta\in (\alpha,T/2)$.
On the other hand, $\int_{\mathbb R} u(x,t)e^{x^4-x^2/\alpha}$ diverges due to your lower bound. Contradiction.
Answer: Your example $f(x)=e^{x^4}$ should work. According to what you know so far, whenever $t\ge\epsilon$,  $$f(x)u(x,t)\ge e^{x^4}Ce^{-cx^2}\ge c_1 e^{x^4/2}=:g(x). $$ Fix a smooth enough increasing function $h$ approximating the Heaviside function, with $h(x)=0$ for $x<0$, $h(x)=1$ for $x>1$, and find $v(x,t)$ solving $$v_t-v_{xx}=h, \quad v(x,\epsilon)=0,$$
by the standard Duhamel formula. Then one should have $v(x,t)\ge \hat C e^{-\hat cx^2}$ for $t\ge2\epsilon$.   Now for each integer $n>0$, because $u_t-u_{xx}\ge g$ and $g(x)\ge g(n)h(x-n)$, comparison yields for $t\ge2\epsilon$ that
$$
u(x,t)\ge g(n)v(x-n,t) \ge c_2 e^{n^4/2}e^{-\hat c(x-n)^2} \to\infty
$$
as $n\to\infty$.
So $u$ cannot be finite.


How to convert Dao object to Model in Exposed?

Question: I am using Jetbrains Exposed library to create ORMs for my entities.
I have an entity Book which has a one-to-one mapping with Author entity and one-to-many mapping to Chapter entity.
Using exposeds DAO classes I have created the below ORM mappings between the entities which succesfully returns a BookDao object. The problem is that I need to convert this to type BookModel so it can be serialized and sent back to the client.
How can I convert the book object (of type BookDao) to type BookModel? I have looked through Exposed's documentation but do not see a way of doing this.

val bookDao = BookDao.findById(1)?.load(BookDao::author, BookDao::chapters)
***logic to convert BookDao to BookModel***
call.respond(bookModel)

object Books: IntIdTable()

class BookDao(id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<BookDao>(Books)
    val author by AuthorDao referrersOn Authors.book
    val chapters by ChapterDao referrersOn Chapters.book
}

object Authors : IntIdTable() {
    val firstName = varchar("firstName", 32)
    val lastName = varchar("lastName", 32)
    val book = reference("book", Books)
}
class AuthorDao (id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<AuthorDao>(Authors)
    var firstName by Authors.firstName
    var lastName by Authors.lastName
    var book by BookDao referencedOn Authors.book
}

object Chapters: IntIdTable() {
    val title = varchar("title", 512)
    val book = reference("book", Books)
}
class ChapterDao(id: EntityID<Int>): IntEntity(id) {
    companion object: IntEntityClass<ChapterDao>(Chapters)
    var title by Chapters.title
    var book by BookDao referencedOn Chapters.book
}

@Serializable
data class BookModel(
    val author: AuthorModel,
    val chapters: List<ChapterModel>
)

Answer: I guess author should be authors because is a 1 to N relationship
You have to do it manually, you can define a function to convert each dao to model.
Given this models
data class BookModel(
    val authors: List<AuthorModel>,
    val chapters: List<ChapterModel>
)

data class AuthorModel(
    val firstName : String,
    val lastName: String
)

data class ChapterModel(
    val title : String
)

Define this functions to convert to models
class BookDao(id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<BookDao>(Books)
    val authors by AuthorDao referrersOn Authors.book
    val chapters by ChapterDao referrersOn Chapters.book

    fun toModel() = BookModel(
        authors = authors.map { it.toModel() },
        chapters = chapters.map { it.toModel() }
    )
}

class AuthorDao (id: EntityID<Int>) : IntEntity(id) {
    companion object : IntEntityClass<AuthorDao>(Authors)
    var firstName by Authors.firstName
    var lastName by Authors.lastName
    var book by BookDao referencedOn Authors.book

    fun toModel() = AuthorModel(
        firstName = firstName,
        lastName = lastName
    )
}

class ChapterDao(id: EntityID<Int>): IntEntity(id) {
    companion object: IntEntityClass<ChapterDao>(Chapters)
    var title by Chapters.title
    var book by BookDao referencedOn Chapters.book

    fun toModel() = ChapterModel(
        title = title
    )
}

Then just use
val bookDao = BookDao.findById(1)?.load(BookDao::author, BookDao::chapters)
val bookModel = bookDao.toModel()
call.respond(bookModel)

Be careful with the N+1 problem, I recommend use DSL instead of DAO


Run client applications from VMWare Workstation Host

Question: Does anyone know how to run applications hosted on a client VM from an icon created on the host computer?
For example I want to run IE8 installed on the client VM on my host XP computer running IE6. I cant update to IE6 on the host because of compliance issues.  I'm trying to do this with VMWare Workstation 7.
Comment: Easy with *nix-to-*nix (except OS X as remote), trickier with *nix-to-Windows, awful otherwise.
Comment: Thanks for commenting.  Not sure it counts as a helpful answer.
Answer: if you mean fully integrated in the host environnement, you would install at first wmare tools and place you guest system in unity mode (i think it is called like that).
i've done this using vmware workstation on Linux with Windows Guest system
Comment: Thank you for your help.  This should work.  I'm trying it out now.
Comment: Do you know if the util "vmware-unity-helper.exe" works in Windows?  I found post that say that it only works with linux but that was for version 6.5 and I'm running 7.  I'm not sure if it's now supported in 7 though.  Thanks again.


Prove that $\frac{1}{\sqrt{1-z}}=\sum_{n=0}^{\infty}\frac{1}{4^{n}}\binom{2n}{n}z^{n}$ using Cauchy product

Question: need to prove using Cauchy product for series for all $\left|z\right|<1$ that $$\frac{1}{\sqrt{1-z}}=\sum_{n=0}^{\infty}\frac{1}{4^{n}}\binom{2n}{n}z^{n}$$ (with appropriate branch of the root function)
Comment: Multiply the series by itself, what happens?
Answer: Prove the series converges (absolutely) for $|z|<1$, then the Cauchy product formula says
$$\left(\sum_{n=0}^\infty\frac1{4^n}\binom{2n}nz^n\right)^2=\sum_{n=0}^\infty\sum_{k=0}^n\frac1{4^n}\binom{2(n-k)}{n-k}\binom{2k}kz^n$$
Now prove
$$\sum_{k=0}^n\binom{2(n-k)}{n-k}\binom{2k}k=4^n$$
So the square of the sum is
$$\sum_{n=0}^\infty z^n=\frac1{1-z}$$
$\dfrac1{\sqrt{1-z}}$ is analytic on the disk $|z|<1$ and matches the series (which is also analytic) for $z\in\mathbb [0,1)$ by the previous calculations, as both are clearly the positive roots of $\dfrac1{1-z}$. Therefore they have to be the same for all $|z|<1$.

Details:
The  ratio test tells us the radius of convergence is
$$\lim_{n\to\infty}\frac{4^{n+1}}{4^n}\frac{\binom{2n}n}{\binom{2(n+1)}{n+1}}=4\lim_{n\to\infty}\frac{(2n)!}{(n!)^2}\frac{((n+1)!)^2}{(2(n+1))!}=4\lim_{n\to\infty}\frac{(n+1)^2}{(2n+1)(2n+2)}=1$$
The combinatorial identity is harder than I expected, for a bijective proof see this answer: Identity for convolution of central binomial coefficients: $\sum\limits_{k=0}^n \binom{2k}{k}\binom{2(n-k)}{n-k}=2^{2n}$
I suspect it should also be possible to find a bijection to the subsets of $2n$ as there's $4^n$ of them, but I don't see how.


How to calculate transformation matrix from plane P to the planes "x=0" and "y=0"?

Question: By following the answer from this question, for a given plane $P$ (defined with three points $A$, $B$ and $C$) I manged to rotate the objects from it into the plane "$z=0$" with the following method:
$$\mathbf w = {\mathbf n\over\|\mathbf n\|}, \mathbf u={B-A\over\|B-A\|}, \mathbf v=\mathbf w\times\mathbf u.$$
Where plane's normal is $\mathbf n=(B-A)\times(C-A)$ and the matrix $R=\begin{bmatrix}\mathbf u&\mathbf v&\mathbf w\end{bmatrix}$ represents a rotation that maps the standard basis vectors onto plane "$z=0$" (for more details of the approach you can read the description in the posted link above).
I need to do the same thing for rotating the objects from plane $P$ to the planes "$x=0$" and "$y=0$", so in these cases how the rotation vector should look like?
Comment: Do you understand the *method* used to construct the rotation in the question you cite? The formulas that you've lifted from it aren't a "method," but a result of applying the method.
Answer: I have found the solution which I was looking for. If the rotation vector is: $R=\begin{bmatrix}\mathbf u&\mathbf v&\mathbf w\end{bmatrix}$, for rotation to all three planes, here are the formulas for rotations:
to $XY$ plane:
$$\mathbf n=(B-A)\times(C-A),\mathbf w = {\mathbf n\over\|\mathbf n\|}, \mathbf u={B-A\over\|B-A\|}, \mathbf v=\mathbf w\times\mathbf u.$$
to $XZ$ plane:
$$\mathbf n=(B-C)\times(A-C),\mathbf v = {\mathbf n\over\|\mathbf n\|}, \mathbf u={B-C\over\|B-C\|}, \mathbf w=\mathbf v\times\mathbf u.$$
to$YZ$ plane:
$$\mathbf n=(A-B)\times(C-B),\mathbf u = {\mathbf n\over\|\mathbf n\|}, \mathbf w={A-B\over\|A-B\|}, \mathbf v=\mathbf u\times\mathbf w.$$


Show that if there are 15 points scattered inside a 1 unit square, then at least 3 of them can be covered by a square of side $1/5$

Question: I have been trying to find a proper way to divide the square into smaller squares but nothing seems to be working so far, that is, trying to apply in a straight forward way the pidgeonhole principle. I tried dividing the square into rectangles but that didn't seem to work either (14 rectangles of sides $1/7\times 1/2$). Could this be solved by contradiction? Any suggestions?
Comment: Must the sides of candidate squares be axes-aligned?
Comment: Since the problem didn't specifically stated it, I supposed they don't have to.
Comment: Makes it much more difficult...
Comment: Are you sure this is true? Unless I'm misunderstanding, $\{(\frac{a}{4}, \frac{b}{2}) : 0 \leq a \leq 4, 0 \leq b \leq 2\}$ avoids this type of covering...
Comment: Yes, perhaps the professor made a mistake when he transcripted the problem. Could it be possible that it was $2/5$ instead of $1/5$? Either way, I was also unsure that the problem was correctly stated.
Comment: @NotAMathematician I guess that instead of **a side 1/5** should be
**... a square of area 1/5**.
Answer: I'm sorry, but I simply don't see it:

or better:
Answer: The statement is not true.  Place two points at each of the dots in the figure.  The side of the inner square is $\frac {\sqrt 2}4$, greater than the diagonal of a square of side $\frac 15$.  The distance from a corner to a corner of the center square is greater yet.  By expanding the central square this construction works for $16$ points up to a distance of $\frac{\sqrt 3-1}{\sqrt 2} \approx 0.51764$, so we are not even close.


How can I find P[X ≥ 2Y] from the joint pdf?

Question: Let X and Y have the joint pdf   $f(x,y) =xye^{−x−y}$ $(x > 0,y > 0)$
Find $P[X ≥ 2Y]$.
I really don't know what can I do for this...
Comment: By definition, $$P(X\ge 2Y)=\iint_{x\ge 2y}f(x,y)\,dx\,dy$$
Answer: Hint:
$$P(X\geq 2Y)=\mathbb E\mathbf1_{X\geq2Y}=\int\int\mathbf[x\geq2y]f(x,y)dxdy$$where $[x\geq2y]$ is a function $\mathbb R^2\to\mathbb R$ that takes value $1$ if $x\geq 2y$ and value $0$ otherwise.
Answer: I would start with
$$\int_0^\infty\int_{2y}^\infty f(x,y)dxdy.$$
That is
$$\int_0^\infty ye^{-y}\bigg(\int_{2y}^\infty xe^{-x}dx\bigg)dy$$
Compute the integral in () then see where it goes?
Answer: Hint:
$$\int_{0}^{\infty} \int_{2y}^{\infty} xye^{-x-y}dxdy = \frac{7}{27}$$


Is it possible to use the required property in IE?

Question: I have code like this:
<input required>

In good browsers I can use jquery like this to add a class of error to the input:
$('input[required]').addClass('error');

It doesn't work in IE though. I will resort to this otherwise, but it's not as neat...
HTML:
<input data-required=true>

Javascript:
if( $('input').data('required') ) $('input').addClass('error');

Any ideas?
Thanks,Will
EDIT:
Yea, I am using HTML5.
IE actually interprets this:
<input required>

as:
<input required="">

So it is possible to check that like this:
if( $('input').prop() == undefined )

But again, it's a bit of a messy way of doing things, especially considering that it is only IE that has the issue. This code works perfectly in all other browsers.
I am basically asking if there is a method of checking that is cross browser and tidy. I'm a bit of a perfectionist perhaps! ;)
Comment: @DarinDimitrov `` is definitely valid HTML.
Comment: It's invalid HTML. A valid HTML would look like this: ``.
Comment: That depends heavily on your doctype. [HTML5 allows it](http://diveintohtml5.org/forms.html#required)
Comment: Strange, the validator (http://validator.w3.org/#validate_by_input) says it's invalid. Probably as it is still a draft it is not properly implemented.
Comment: `` validates for me. @DarinDimitrov
Comment: @DarinDimitrov The HTML syntax of the HTML language (which is the one you want to be using, the other one being the XHTML syntax) does allow boolean attributes to be given without a value. So ``, ``, etc. are valid. The important factors are (a) the HTML standard and (b) how browsers implement that standard. If the validator does not conform to these two factors, it's an issue with the validator, not the HTML code.
Answer: using data- attribute is safe and your page will be valid if you use them. But you need qoutation for your value. I'm using data attributes all the time. We support IE7.
<input data-required="true">

Or even you can leave the value in cases like this:
<input data-required>

If you are using data attributes often then it's good to know that you can use dataset property in Chrome developer tools (and Firebug) to access your element's data attributes via console. It's not safe yet to use dataset API in your code. it's not supported in IE8
in your console write:
$$('input')[0].dataset

and get the data attribute values and properties!
Comment: This worked fine. I just used data-required and checked for its existence. Cheers!
Answer: Try using required="required", it might make older browsers like it better.
IMPORTANT NOTE: It's still very much valid to write <input required>


Need help finding a number x so that $\phi > 9x/10$?

Question: I need help finding a number $x$ so that $φ(x) > 9x/10$? ($φ$ being Euler's phi function.)
I also need to find a number $x$ so that $φ(x) < x/3$?
Comment: Use $$\frac{\phi(x)}x=\prod \frac{p-1}p$$
Answer: Hint: if  $p$ is prime, what is $\phi(p)$?
Answer: Use the prime decomposition:
$$x=p_1^{a_1}\cdot\ldots\cdot p_n^{a_n}\;,\;\;p_i\;\;\text{primes}\;,\;\;a_i\in\Bbb N\implies \phi(x)=x\prod_{k=1}^n\left(1-\frac1{p_k}\right)$$
So you want
$$x\prod_{k=1}^n\left(1-\frac1{p_k}\right)>\frac9{10}x\iff\prod_{k=1}^n\left(1-\frac1{p_k}\right)>\frac9{10}$$
You can even take pretty simple naturals...say, that are prime s.t.
$$1-\frac1p>\frac9{10}\iff\frac1p<\frac1{10}\iff p>10$$
So it could be $\;x=11\,,\,\,13\,,\,29$ etc.


Harmonic and holomorphic, what's the difference?

Question: Correct me if this question is too broad:
I heard that real harmonic functions are the analogon to holomorphic functions. I know that they have a lot of properties in common (e.g. analyticity) but what is their connection exactly?
Comment: The real and imaginary parts of a holomorphic function are each harmonic.
Answer: Let $f(x+iy)=u(x,y)+iv(x,y)$ be a holomorphic function. Then you can calculate, by using the Cauchy-Riemann equations, Schwarz Theorem and that f' is holomorphic, that $Re(f(z))=u(x,y)$ is harmonic, in other words $\Delta u(x,y)=0$. Same goes for the imaginary part $Im(f(z))=v(x,y)$ i.e. $\Delta v(x,y)=0$.
The other way around: If you have a simply connected domain (think it is simply connected, youd have to look that one up), every harmonic function $u(x,y)$ is the real part of a holomorphic function. Same applies for the imaginary part.


Who is the most recent Everton signing that previously played for Liverpool at any point in their career?

Question: For example Kevin Sheedy played for Liverpool between 1978 and 1982 and then signed for Everton in 1982. Peter Beardsley played for Liverpool between 1987 and 1991 and then signed for Everton in 1991.
I'm wondering if there have been more recent signings.
Also, is there a complete list of all players who played for Liverpool and then Everton and vice/versa?
Comment: Do loan signings count?
Comment: Yes, let's include those
Answer: Since loan signings count, the most recent player to do this was Conor Coady, who spent the 2022-23 season on loan at Everton from Wolves, having previously come through the youth ranks at Liverpool.
In terms of permanent signings, Andy Lonergan spent a season at Liverpool in 2019-20 without playing any games, and then signed for Everton in 2021 (where he has, again, played zero games). The most recent player I can find to have signed permanently for Everton, having previously signed and played for Liverpool, was Don Hutchison, who played for Liverpool between 1990 and 1994, and Everton between 1998 and 2000.
I used this article to find this information, but it only lists the seven players that have done this during the Premier League era. This other article claims to be a complete list, but doesn't include any of the three players I mentioned above, so it's clearly not. If a complete list does exist, I've been unable to find it.


Erro ao Instalar lib react-navigation-tabs e react-navigation-drawler

Question: Depois que eu instalo as dependências e importo para o projeto ele da esse erro :
Answer: Amigo executa esse dois comandos:
<code>yarn add react-navigation-tabs
react-native link react-navigation-tabs
</code>
Espero ter ajudado amigo
Comment: funcionou amigo, muito obrigado!


Without the ZF axiom of regularity can any infinite sets be constructed?

Question: Update with Direct Question
Based on Asaf's comments, here is a related question:

Prove that the mapping $n \mapsto n \cup \{n\}$ on the set $\Bbb N$ is injective without the axiom of foundation.

The wikipedia $\text{ZF}$ article under axiom 7 contains the text

(It must be established, however, that these members are all
different, because if two elements are the same, the sequence will
loop around in a finite cycle of sets. The axiom of regularity
prevents this from happening.)

ORIGINAL QUESTION

Without the axiom of foundation (axiom 2 in the wikipedia $\text{ZF}$ article)
can any infinite sets be constructed?

By an infinite set we mean a set that is not Kuratowski finite.
I suspect that without it, the axiom of infinity (axiom 7) might be better described as
$\quad$ The formula of finitary frustration.
My work
I saw the axiom of foundation mentioned inside parentheses in the paragraph for axiom 7 allowing us to construct the natural numbers. So apparently, the familiar program of constructing the natural numbers $\Bbb N$ can't be carried out without axiom 2.
Comment: I'm confused. The axiom of infinity is still part of your system, yes? Where is the problem?
Comment: @Peter: You are missing something. The axiom of infinity simply posits the existence of a set which has the empty set as an element, and is closed under $x\mapsto x\cup\{x\}$. Since $\varnothing$ is not in the range of this map, the set has an injective function which is not surjective, and so it is infinite under any reasonable definition of infinite. Regularity has absolutely nothing to do with it. The only role of regularity is *simplifying* some of the basic proofs about the least inductive set (i.e. $\omega$).
Comment: If I understand the axioms right, the axiom of inifnity allows us to add an element to a given set as often as we want. But the regularity axiom is necessary to avoid that at some point, we can only add elements that we already have in our set (which would mean that the set would not actually become bigger). Maybe, I miss something, but this sounds as we need the axiom of regularity.
Answer: It is true, if $x=\{y\}$ and $y=\{x\}$ and $x\neq y$, then $x\cup\{x\}=\{x,y\}=y\cup\{y\}$. So without assuming the axiom of regularity the map $x\mapsto\{x\}$ is not provably injective.
But just because it is not necessarily injective on the entire universe does not mean that we cannot find a set on which it is injective.
Setting $\omega$ to be the intersection of all the inductive sets, we can now prove that $x\mapsto\{x\}$ is in fact injective on $\omega$. The reason being is that $\omega$ is in fact well-founded, so in particular the above situation does not happen inside $\omega$, it it happens at all.
The quickest, dirtiest, hackiest way to see this is to simply note that $\omega$ belongs to the von Neumann universe which is an inner model of the universe (working in $\sf ZF-Reg$). But this can be shown by hand, through what is tantamount to an ad-hoc proof that $\omega$ is well-founded.


How to notate parallel tuplets

Question: Suppose I have a 4/4 bar for piano, and in the right hand I want to play a quintuplet over 1, 2 and 3, and I want to play a quadruplet over 2, 3 and 4.
What is the proper way to notate this?
The solution I came up with is quite unwieldy. In order for the start of the quadruplet to line up with the quintuplet, we need to retain the original division of the bar, which we can do by changing the quintuplet into a 15-tuplet, where the 15-tuplet contains 5 notes with a duration of 3 units. That way we retain the orginal division on note 1, 5 and 10 of the 15-tuplet.
In order for the quadruplet to line up with the notes of the 15-tuplet, we need to move to a 60-tuplet. The intended quintuplet then becomes a 60-tuplet with 5 notes of a duration of 12 units each. The quadruplet also becomes a 60-tuplet with 4 notes of duration of 15 units each, and that starts on the 20th note of the first 60-tuplet.
Now we can merge the two 60-tuplets into one 80-tuplet that covers the entire bar.
While this seems arithmatically correct to me, it leads to something quite unreadable, so I must assume there is another way to approach this.
Answer: Divide the right hand part into two different voices, the top voice gets stems pointed up, and the bottom voice gets stems pointed down.  Then put the tuplets in for each voice the usual way.  This will make your intension clear and readable (even if it isn't easy to play).
Comment: Why is the quintuplet composed of "eighth" notes but the quadruplet of "quarter" notes?
Comment: @DanielWagner That was a somewhat arbitrary decision. I was using the logic that for the quintuplet: 5 "eighth" notes is closer to 6 eights notes, than 5 "quarter" notes would be to 3 quarter notes. And for the quadruplet that: 4 "quarter" notes is closer to 3 quarter notes, than 4 "eighth" notes would be to 6 eight notes. Though I wasn't particularly happy with the quintuplet being a stretching and the quadruplet being a squashing. As PipedPiper points out, these are non-standard tuplets, and really should be written more explicitly (with the ratio specified), and squashing both seems best.
Comment: Thank you for the great response. Voices as an aspect of musical notation, I will dig deeper into.
Comment: Because both voices must fill the entire measure, this notation is unambiguous as-is. The presence of the two plain quarter notes makes it clear that each tuplet is three beats. I actually like having the two different value notes as additional clarification about which voice they belong to and which notes are shorter compared with the notation in the other answer with a bar full of mismatched quarter notes.
Answer: For non-standard tuplets it's important to make it clear how much time they are taking up. This notation makes the tuplets more explicit:

(the red notes should be black of course)
Comment: You make a good point.

How to notate parallel tuplets


How do I get over caution of going fast (with minimal access to slopes)?

Question: I've only gone snowboarding once (a 2-week exclusively-snowboarding holiday), about 3 years ago.
It was a lot of fun, even though I didn't manage to come right too well.
The problem was that, even though I managed to get turning and such right, I really struggled to get much further than knowing the basics, as I'm too cautious about picking up speed (even carving was a problem, although the slopes were pretty steep, at least for me - it felt like about a 30-40° incline on most of the slopes where I was - this was on the "easy" slope - the "medium" slope seemed pretty similar).
I did fall a lot at first (as I guess most, if not all, new snowboarders do), so I can't imagine fear of falling, as such, is the problem.
I did take a few lessons during the first week. I got fairly comfortable with basically just going down the slope (at least better than with my board fully horizontally the whole way) and making the occasional turn, but the next part of the lessons was carving, which, as mentioned above, was a problem, so I felt a bit stuck for the remaining week and a half.
How do I get over this caution of going fast?
I've considered:

Choosing to ignore that little voice telling me to not go fast.
This probably wouldn't be too difficult, but I fear that, not being particularly experienced, I may not be able to react properly to certain situations (which may include trying to slow down / stop), and risk serious injury.
Picking up skateboarding so I can get more comfortable on a board.
Given that part of my problem is minimal access to slopes (because of distance and price), I thought it might be a good idea to get started with skateboarding, which I can do locally. A board's a board - right? Or not?
Just practice at the speed I'm comfortable with.
The problem here is the minimal access to slopes. And during my snowboarding experience, I seemed to just be stuck skill-wise during the last week of my trip because of this speed problem (not being able to go straight is a bit of a problem), so I'm not sure whether this will actually help.
I've also considered taking a really long snowboarding holiday (a month?) as to practice consecutively for a long period and hopefully get over my problem (although, if I don't, it might be a very depressing month).
Going to somewhere with slopes with less incline.
This should get me more comfortable on the board (allowing me to practice slowing down / stopping more safely), and hopefully this also makes me more comfortable at higher speeds.
Makes sense, but I wouldn't even know how to find such a place, beyond just going to different places until I find one.

Any advice on my problem or any of my considerations or any other suggestions?
Or am I too concerned about this, as it's just something that comes with time, and if it doesn't, snowboarding just isn't for me?
Comment: Where is "here?"  Maybe some hints can include locations you might not already be aware of.
Answer: First of all, I should mention that snowboarding isn't my strongest dicipline. Instead, I'm a skier - and sometimes even a telemark skier - but the general idea is the same.
To begin with, going fast shouldn't be a goal per se. Rather, your goal should be to go fast AND in control. The only way to do this, and the only way to feel comfortable doing it, is to learn the basics by heart. Before you'll be able to progress, those basics must be in your bones, in your spine, and in every other part of your body - not only in your head.
To make a personal example, I was always the most cowardly of all the children in ski- /snowboard school. However, as everyone else was going straight down, head first - I was plowing my way down the mountain in a very slow pace. As everyone grew older, most youngsters still struggled with the technique, but those of us who had gone about it slow in the past were now the ones to race down the mountain in style - despite only skiing one week every year!
What I'm trying to say is, that in order to "break the mental barrier of going fast", your instinct (which you cannot easily control) must trust your ability to stay in control while going fast. Thus, don't rush it - even though it's frustrating trying to learn, especially when older and not learning as fast as a child anymore. Take snowboard lessons a couple of days, it's amazing what that does for your development!
As for the other 50 weeks of the year, it is hard to substitute snow and board for anything likeworthy, but your skateboard idea isn't at all stupid. However, to make it more "snowboardlike", I would strongly recommend a longboard instead of a skateboard. Longboarding has a lot more in common with both snowboarding and surfing than skateboarding does.
Ride carefully and good luck!
Comment: My goal isn't going fast as such, but rather just to be comfortable enough with speed to be able to be able to practice the more advanced fundamentals. Right now I feel pretty comfortable with what I know and can do, but I feel I'm stuck there - the next step in the lessons I took was carving, which I couldn't really get right because of this problem. Also, isn't it a lot easier to control your speed with skiing, so it's fairly easy to get comfortable with going faster and faster, and much easier to practice the basics at fairly low speeds?
Comment: Ah, okey. I still think my answer is rather accurate though. The "uncomfortable" feeling that you get must be your body reacting to a danger it doesn't feel comfortable facing due to a lack of skill/experience, unless you have some sort of phobia for speed itself. Thus, you should continue on the level you feel comfortable with, and you will become more comfortable with higher speed and more advanced moves naturally as you progress. There are no shortcuts, I'm afraid.
Answer: Ride, ride, ride and ride some more, there's really no secret that will diminish your fears. Your fears are natural and everyone who picks up the sport will go through it in varying degrees based on their willingness to fall and get up. I've fallen countless times and still fall and can't see anyway to improve without doing so. I will say one thing tho, I wear kneepads, elbow pads, wrist braces, the best padded shorts on the market and a helmet. I've had numerous nasty falls and my protective gear I'm positive has prevented serious injuries. Get all the safety gear you can, ask for assistance from experienced riders or get a session of lessons but most importantly don't quit and go at YOUR OWN SPEED until your comfortable. YOU WILL IMPROVE if you stay with it... GUARANTEED!!!
Answer: Being a self-taught snowboarder (16+ years and counting) my short response is practice, practice, practice. I realize that is difficult as you do not have access to the slopes on a regular basis. So with that said, here are some opinions on your concerns.
As Qvist said, and you confirmed, going fast is not the goal. The feeling you get when you point straight downhill that causes you to get nervous is natural and a good thing. This will go away as you become more proficient and you may find that you end up enjoying turning downhill and charging (assuming you end up enjoying speed, as there is no need to focus on that aspect). So how to become more proficient?
You do not need to focus so much on pointing downhill as you do on transitioning from edge to edge (which will happen to traverse a point where you point downhill). It is that familiarity which will help you get more comfortable with speed. It is fairly rare to not be on one edge or the other when snowboarding, so edge control is what you need to progress in your skills. As you develop that natural feel for quick transition to the other edge you will be more comfortable riding any terrain as edge control lets you understand how much to dig in to stop quickly, or if you desire to carve to carve. Additionally as you get more comfortable on your edges you will be able to do your transitions in that spot where you are still pointing downhill, which is where your comfort for speed and carving comes in.
Personal opinion for other sports helping to snowboard (skateboarding, wakeboarding, surfing) is that they can only help up to a point. You use many of the same balance techniques, but the interaction is completely different. I would say wakeboarding as your feet are strapped in is likely the closest in feel.
Last but not least, if you are truly hooked on snowboarding (as I was right after I went for the first time) do not pressure yourself into thinking you need to be a 'great' snowboarder after so many visits to the slopes. Work on your turns, on your stopping, and whatever other aspect (carving, jumps, etc.) that is fun as you work up your skills. As long as you are having fun, then it is a worthwhile trip.
And BTW, I do not care what anyone else tells you, EVERYBODY falls :)
Answer: I'm a female 51 year old snowboarder. I think these answers here are right on the money. My strong advice is the protective gear. Also, make sure your bindings are correctly adjusted for your comfort. I just made a tiny adjustment to my stance and had a 100% better day out there. I ride over 20 days a season and I ride with my teens. Because of their ability to learn quickly and to overcome fear, they help me ride better. I'm still behind them, but I'm closing in on them! They even drag me into the terrain parks. But you may want to hold off on that for a bit! Always try to improve your riding by a small percentage each time you go out and if you ride with someone more experienced, I find that you automatically get better. Edge control is cardinal, and believe me, after only five seasons, I still fall. We all fall, no matter what level. This is a good thing. Fear is your enemy and speed is your friend when riding. I'm not saying charging down the mountain, but going too slow will cause you to fall more as well. Counter-rotation is the biggest mistake I see out there. This is when your body isn't in proper alignment, so when you hit a bump, down you go. Keep your shoulders straight, and in alignment with your hips. Bend your knees. Never stand straight up. Head faces downhill and eyes looking ahead to where you want to go. Don't look down. If you find yourself flailing your arms all over the place as you ride, grab the side of your pants, and continue that way for a run. Watch how much better you ride. Your edge transitions will come naturally with riding and mixing up your terrain. Again, as stated above, at your own pace. It will come. Want to know how to force yourself to become better at riding? Ride switch. It's slow and fun, but watch what happens when you go back to your normal stance. Also, take a run on a mogel field. No joke, you will fall, but you will go through carefully, bending your knees to absorb each mogel (we ride over, skiers ride around them). They are incredibly effective to force some fear out of you, while having a lot of fun. Just take it slow and at your own pace. By the time you read this text, I'm certain you're already riding the blacks and in the glades! Good luck. Ride on!


Question regarding this answer to a limit problem

Question: This is regarding this answer which sought to address this problem:

Prove that $\lim_{n\to\infty} a_n=0$ given that $|x| \lt 1$.

I perfectly understand the answer except the last few lines which solves the problem using Bernoulli's inequality. I think it should be something like this:
$(1+t)^n \gt 1+nt \ge (1+2mt)$ But how is $(1+t)^n \gt (1+mt)^2$
?  $a \gt b $ and $c \gt b$ do not imply $a \gt c$!
Answer: If $$(1+t)^m \ge 1+mt$$
Note that we have $\frac{n}{2} \ge m$
Hence we have $(1+t)^{\frac{n}{2}} \ge (1+t)^m \ge (1+mt)$
Now we square everything and we conclude that
$$(1+t)^n \ge (1+mt)^2$$


Memory leaking in windows service

Question: I had made a windows service following this article - https://msdn.microsoft.com/en-us/magazine/mt703436.aspx. All works fine and I felt like I'm a real programmer). But I have a problem - this service consumes too much memory. In fact, for about 6 hours service consumed 3 Gb memory and I think it's not very good. Maybe anyone faced with this problem and resolve it?
Maybe someone could help me?
I put my code here - http://paste.ubuntu.com/24169803/.
Thanks in advance.
Comment: It's going to be quite hard to help without being able to see the code.
Comment: Edited first message.
Comment: Over 1,000 lines of code?? http://stackoverflow.com/help/mcve
I guess as a generic answer: how often are you creating `New-Object`s and not clearing them up?
Comment: I'll check it, thanks for this hint.
Comment: I added the Remove-Item commandlet in every functions where are the New-Object. But it's not helped.
Comment: And also I found this code in finally block:

`if ($sw) {

$sw.Dispose() # Release resources

$sw = $null   # Force the PowerShell garbage collector to delete the .net object

}`
Answer: I've read the article you used for creating a service. Can't tell for sure without seeing your code but you are probably missing garbage cleaners.
<code>[System.GC]::Collect()
</code>
Comment: I tried to use garbage collecting, but there was no any effect.

Memory leaking in windows service


$sample aggregate not functioning correctly in MongoDB

Question: i am trying to grab a random document from my collection and I keep receiving the error:
PlanExecutor error during aggregation :: caused by :: The argument to $size must be an array, but was of type: missing
obviously not trying to use the $size aggregate just the parameter with the $sample aggregate.
[{
 $project: {
  _id: '$_id',
  sender_id: '$sender_id',
  date_time: '$date_time',
  numberOfLikes: {
   $size: '$favorited_by'
  }
 }
}, {
 $match: {
  numberOfLikes: {
   $gte: 9
  }
 }
}, {
 $lookup: {
  from: 'UsedClessics',
  localField: '_id',
  foreignField: 'reply_id',
  as: 'UsedClessics'
 }
}, {
 $match: {
  'UsedClessics.type': {
   $ne: 'reply'
  }
 }
}, {
 $match: {
  sender_id: {
   $ne: 'system'
  }
 }
}, {
 $match: {
  sender_id: {
   $ne: '848846'
  }
 }
}, {
 $sample: {
  size: 1
 }
}]

Answer: The error is NOT thrown because of $sample stage, but because of the first $project stage.
There, you are fetching the size of the favorited_by property, and apparently some of the documents is missing that field.
Try to change your first $project stage like this:
{
  $project: {
    _id: "$_id",
    sender_id: "$sender_id",
    date_time: "$date_time",
    numberOfLikes: {
      $cond: {
        if: {
          $isArray: "$favorited_by"
        },
        then: {
          $size: "$favorited_by"
        },
        else: 0
      }
    }
  }
}


Limiting User Permissions

Question: I have 3 sets types of users admins, writers & paid writers. Drupal has a built in administer role but not a limited administer role. I want the paid writer role to control some permissions but not all permissions of writers (like the types of content they can create). Is there a place to do this in Drupal?
Answer: In the admin/people/permissions set Administer permissions for the paid writer role:

Limiting User Permissions


Which axiom describe the distance between two variables or more?

Question: i think operator greater than or less than or equal is not enough,
any advanced thing to describe the difference between two variables
x-y < y-z, y-z < z-a  => x-y < z-a  (can this be proved valid? if not, any others)
Answer: The transitivity of the relation $<$ is what is used here. Transitivity ($a<b\land b<c\implies a<c$) is one of the defining properties of an order relation. Just plug in $x-y,y-z,z-a$ for $a,b,c$ to get what you want.


Why when giving files names numbers to the names using a counter it's giving it strange numbers?

Question: The first saved file name on the hard disk is: 201701311645---0 then 201701311645---1 then 201701311645---20 then 201701311645---21 then 201701311645---40 and 201701311645---41
But i want it to be saved as: 201701311645---0 then 201701311645---1 then 201701311645---2 then 201701311645---3 then 201701311645---4 and 201701311645---5
In the top i added a counter variable
private int countFilesNames = 0;

Then in a dowork event i also reset the counter to 0 once so if i start the backgroundworker over again it will start from 0.
private void bgwDownloader_DoWork(object sender, DoWorkEventArgs e)
        {
            Int32 fileNr = 0;
            countFilesNames = 0;

            if (this.SupportsProgress) { calculateFilesSize(); }

            if (!Directory.Exists(this.LocalDirectory)) { Directory.CreateDirectory(this.LocalDirectory); }

            while (fileNr < this.Files.Count && !bgwDownloader.CancellationPending)
            {
                m_fileNr = fileNr;
                downloadFile(fileNr);

                if (bgwDownloader.CancellationPending)
                {
                    fireEventFromBgw(Event.DeletingFilesAfterCancel);
                    cleanUpFiles(this.DeleteCompletedFilesAfterCancel ? 0 : m_fileNr, this.DeleteCompletedFilesAfterCancel ? m_fileNr + 1 : 1);
                }
                else
                {
                    fileNr += 1;
                }
            }
        }

Then in the downloadFile method
private void downloadFile(Int32 fileNr)
        {
            FileStream writer = null;
            m_currentFileSize = 0;
            fireEventFromBgw(Event.FileDownloadAttempting);

            FileInfo file = this.Files[fileNr];
            Int64 size = 0;

            Byte[] readBytes = new Byte[this.PackageSize];
            Int32 currentPackageSize;
            System.Diagnostics.Stopwatch speedTimer = new System.Diagnostics.Stopwatch();
            Int32 readings = 0;
            Exception exc = null;

            try
            {
                writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
                    "---" + countFilesNames + ".png", System.IO.FileMode.Create);
            }
            catch(Exception err)
            {
                string ggg = err.ToString();
            }
            HttpWebRequest webReq;
            HttpWebResponse webResp = null;

            try
            {
                webReq = (HttpWebRequest)System.Net.WebRequest.Create(this.Files[fileNr].Path);
                webResp = (HttpWebResponse)webReq.GetResponse();

                size = webResp.ContentLength;
            }
            catch (Exception ex) { exc = ex; }

            m_currentFileSize = size;
            fireEventFromBgw(Event.FileDownloadStarted);

            if (exc != null)
            {
                bgwDownloader.ReportProgress((Int32)InvokeType.FileDownloadFailedRaiser, exc);
            }
            else
            {
                m_currentFileProgress = 0;
                while (m_currentFileProgress < size && !bgwDownloader.CancellationPending)
                {
                    while (this.IsPaused) { System.Threading.Thread.Sleep(100); }

                    speedTimer.Start();

                    currentPackageSize = webResp.GetResponseStream().Read(readBytes, 0, this.PackageSize);

                    m_currentFileProgress += currentPackageSize;
                    m_totalProgress += currentPackageSize;
                    fireEventFromBgw(Event.ProgressChanged);

                    writer.Write(readBytes, 0, currentPackageSize);
                    readings += 1;

                    if (readings >= this.StopWatchCyclesAmount)
                    {
                        m_currentSpeed = (Int32)(this.PackageSize * StopWatchCyclesAmount * 1000 / (speedTimer.ElapsedMilliseconds + 1));
                        speedTimer.Reset();
                        readings = 0;
                    }
                }

                speedTimer.Stop();
                writer.Close();
                webResp.Close();
                if (!bgwDownloader.CancellationPending) { fireEventFromBgw(Event.FileDownloadSucceeded); }
            }
            fireEventFromBgw(Event.FileDownloadStopped);

            countFilesNames += 1;
        }

I build the file name:
writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
                    "---" + countFilesNames + ".png", System.IO.FileMode.Create);

The move the counter forward by 1:
countFilesNames += 1;

But i'm getting other files names then i wanted.
Maybe there is a better way to give the files names some identity ? The problem is that if i will not give the files names some identity it will overwrite the files all the time. The files names are the same the content is not so i need to give each file another name.
Comment: I would start with the following, `Use the Debugger and step through the code` also I would refactor this code and break the functionality down into more manageable / readable code blocks / methods this is very convoluted to say the least
Comment: Are you just complaining about the lexicographical order of the files? Windows will always show 201701311645---11.png before 201701311645---2.png If you want to change the order insert a 0 so it's 201701311645---02.png, 201701311645---11.png.
Answer: Why don't you just increment the counter only when a file is written (since the variable doesn't look like it is accessed elsewhere) and not below:
writer = new FileStream(this.LocalDirectory + "\\" + file.Name +
                "---" + countFilesNames++ + ".png", System.IO.FileMode.Create);

This way the counter won't be incremented on errors.


Providing a counter example for a Logic Statement

Question: How do I give a counter-example of the following logic statement (I think the statement is false):
There exists $x$ $\geq$ 0 s.t. (For All real $y$, $x$ = $y$$^2$)
Since the statement has a "There Exists" I need a general counter-example.
Correct me if I am wrong.
Answer: A general remark: One may prove $\exists x$ by an example and disprove $\forall x$ by a counter-example. But disproving $\exists x$ or proving $\forall x$ requires other methods.

Assume the statement
$$\tag{1}\exists x\ge 0\colon \forall y\in\mathbb R\colon x=y^2$$
is true.
Then for such $x$ we have
$$x\ge 0 \land \forall y\in\mathbb R\colon x=y^2$$
and specifically
$$\forall y\in\mathbb R\colon x=y^2.$$
We specialize for the cases $y=0$ and $y=1$ (which we are allowed to do, because $0\in \mathbb R$ and $1\in \mathbb R$) to find $x=0^2$ and $x=1^2$. By multiplying and the rules of equality we find $1=1^2=x=0^2=0$, i.e. $1=0$.
This is a false statement, therefore the assumption $(1)$ must be wrong.
Answer: You need to provide a counter example; you should be able to find one easily. Start by assuming such an $x$ exists. Can you find a $y$ whose square is not x? The trick is to come up with such a $y$ in terms of $x$.


As a pianist, am I a philistine for secretly hating Chopin?

Question: I am a pianist – not a terribly good one; I got ABSRM Grade 8 as a teenager and now (~20 years later) have moved mostly onto voice but I continue to play the piano both for fun and occasionally for rehearsal purposes with others. Over the years I have slowly got better at sight reading (in particular 4-part SATB style choral music, which I do a lot) and I enjoy playing the piano "for fun", often either with romantic composers like Beethoven, more impressionist Debussy or Satie, or (post-)modern composer's piano works like Alessandra Celletti or Joe Hisaishi. I see the value of playing scales and exercises, and I do so regularly. I try to keep it up and I find playing a nice mix of stimulating and relaxing.
I've got a very clichéd "big book of piano greats" which I am currently working my way through. This includes, amongst many other things, in my mind, a disproportionate amount of Chopin. I never liked Chopin – one of my grade 8 pieces was one of his nocturnes -- and although I can badly bash my way though most of the works in the book, they don't seem musical and the main challenge to that is his stereotypical left hand, with chords in three. I can't find a way to make music out of this other than by memorising the position of each chord. Unlike, say, Beethoven, whose insane chords always seem to just fall under my fingers, Chopin's left hand drives me mad. Even Liszt is more 'fun'.
So, whilst in the title of this question I have provocatively written "am I a philistine?" in disliking Chopin this way, I guess I really want to ask:

Would a different practice style encourage me to "enjoy" playing these pieces more?
Assuming my experience is not unique (Chopin's "left hand" is quite famous) -- what do others like about playing his works? What can I focus on instead, other than a huge sense of frustration that I haven't put the hours in to memorise all the fast leaps?
Chopin is consistently rated highly among the most important piano composers and has contributed a lot to the repertoire. Why? Is it for the musicological reason that his technique and pieces were undoubtedly novel at the time, and the development (in particular) of more "crunchy" harmonies moved the world on to exploring more interesting chords?
Comment: I think this is likely to get closed as 'opinion-based', but in the meantime, why not learn to have fun with it, mix it up a bit. This is a friend of mine's take on Cole Porter, done in the style of Chopin - [When Cole Met the Pole](https://harrythepiano.bandcamp.com/track/when-cole-met-the-pole) [bandcamp link]
Comment: Just a note: when I saw the title, I rushed to be ready to close it as opinion-based, but the actual body of the question contains at least two ( 2 1/2?) insightful and objective questions. I suggest editing the "shock – value" title.
Comment: Everyone will have their loves/likes/dislikes/hates especially when it comes to art-inspired subjects, and music is certainly one. Just because a piece (or those of a composer) are clever, challenging, boring or whatever, just means the potential adoring audience will be smaller.We do have 'rules' in music, but none of them say you have to play/enjoy/endure everything. Worth a look at all the 'great' composers, but feel free to eschew those who're maybe not on your wavelength - right now! Sorry, but this will likely be closed as subjective and opinionated.
Comment: A loophole in the logic: Someone can be highly represented in the literature of an instrument without necessarily being fun to play: Either their work is *good* for you (I don't know that anyone plays Hanon for fun), or they're one of "the greats" because of their accomplishment even if it's hard for the rest of us (I don't find Paganini very "fun").
Comment: I suggest rewriting this question to focus specifically on one problem you've encountered in Chopin and how to practice it.
Comment: You aren't a philistine for disliking Chopin, but it sounds like you've not had the sorts of good experiences with his music that would help you develop a more informed opinion. I suggest that you seek out good recordings--of which there are plenty--to find fresh ways of hearing this music. Spend time with them, and you may find your opinion changes.
Answer: Yes, you need a fluent left hand to play Chopin effectively.  And as yours becomes more fluent you'll be able to better recognise the patterns in Chopin's LH parts.
Sometimes a lot of the satisfaction in playing a piece comes from the knowledge that you HAVE overcome the technical difficulties.   Perhaps you're a Chopin listener more than a Chopin player.


Ear and singing training

Question: I have read plenty of different questions related to ear training, even way more answers, but I'm still struggling to obtain a clear-cut answer (provided that it exists). I have taken up on singing lessons a few years ago and although my technique is considered to be very decent during the exercises (it has been confirmed by a few teachers) I kinda fall to transpose these right feelings to singing songs. I have started playing piano a year ago and have a long guitar experience of about 8 years.
At some point I thought it might my hearing that stops me from making a progress I expect to see, so eversince I have been trying to pay more attention to that. Here's what I tried:

Singing notes, intervals (repeating! vocally) – I play a note (or intervals) on the piano and then try to sing (repeat) it. I think it works quite well.
Comparing intervals – this is what made me think that maybe my hearing is not as good as it should be! Even though I can compare two notes right off the bat and so it is with simple intervals like m2 and M2 I somehow struggle when it comes to, for instance, m3 and M3; my score on an Android app PerfectEar2 is 70/210 what means I am right (whether it is m3 or M3) in ~67% of cases. I have tried using songs as references but I'm not sure this is the way I want to go, as this method doesn't really involve the "context" of an interval, colour and many things that are intrinsic for (for?) a complex approach. I wonder if it makes any sense to keep on guessing and keep my fingers crossed that after one million of attempts I will have made a progress?
Functional Ear Training – teaches you to recognize a scale degree in context to the tonic of a chord progression. I haven't really spent much time on it, but what do you think? Is it a promising method?
Transcripting music – mainly melodic lines so as to learn how to sing a song properly. Nowadays I rarely practice it that way, maybe it is worth to dredge it up.

To all who have come through this – a big shoutout. Now here comes my question – could you please give me any piece of advice on how to practice? What should I do? I'd be really grateful.
Comment: Do you have a list of song beginnings referring to every interval? Did you compose your own short melodies for each interval?  Then you should like you propose continue with your 3rd and 4th idea.
Comment: Yeah, a have a list, but I have't composed such melodies.
Comment: So you can try this too, short eight bars phrases, rhythmical variations containing the same interval (e.g. the dim. 5th.)
Answer: You are on the right pathway. Functional training and transcribing or even composing your own music is the best way for ear training.
Additional to this good method you can choose two-part pieces like inventions, fugues, canons playing one voice and singing the other one.
Finally my most successful practice and secret tip was the training with the movable doremi (solfege) combined with functional training:
E.g resolving V7-I, especially the dim 7th chords, the augmented 5th triad and all kind of German-, French-, Italian sixth chords.
Comment: Thanks a lot @Albrecht Hügli! If you could, please tell me whether it makes sense to compare intervals just in the tedious way, with no songs references, just learning the differences by repeating exercises over and over again? I am capable of doing it, I mean I won't get bored or disappointed provided that it gives positive results someday.
Comment: If you listen to intervals like a chord  trying to characterize the impression, categorizing by the tension, consonance, dissonance, you'll have an alternativ approach of learning and ear training. This makes absolutely sense! Song references are just a help and compensation if the differentiation of the direct way doesn't work.

Ear and singing training


PHP change date format

Question: I have date from monthpicker in this format: 2014 April , and i want to change it to 2014-04-01 before inserting it to mysql.
I'm trying to use strtotime:
$b = date("Y-m-d", strtotime($_POST['month']));
echo $b;

Result is: 1970-01-01. I dont get it.
Comment: possible duplicate of [Convert one date format into another in PHP](http://stackoverflow.com/questions/2167916/convert-one-date-format-into-another-in-php)
Answer: Use DateTime
$date = new DateTime("2014 April");
echo $date->format("Y-m-d");

Answer: $date = DateTime::createFromFormat('Y F', '2014 April');
echo $date->format('Y-m-01');

Answer: Chances are month is being parsed incorrectly.
Try echoing strtotime($_POST['month']) - you will probably see a result of 0.
Try using DateTime function too,
$date = new DateTime("2014 April");
echo $date->format("Y-m-d");

Answer: Use strptime("date","format") - you can use same format as in date()
Answer: you can Use strtotime() and date()for PHP change date format:
$originalDate = "2014-04-06";
$yourDate = date("d-m-Y", strtotime($originalDate));

PHP change date format


Print #field_suffix with drupal_render($form['field_custom_text_field'])

Question: I have a custom module that defines a field_suffix for a custom text field
function custom_check_form_user_register_form_alter(&$form){
$form['field_url']['und'][0]['#field_suffix']='text goes here';
}

I then am calling the field in a user-register.tpl.php as
print drupal_render($form['field_reg_site_url']);

However, the #field_suffix isn't printing (checked that the value is in the array - yes). It does work (same code pattern) for username. Any ideas what I'm missing?
Answer: Try
$form['field_url']['#field_suffix']='text goes here';

Also, in your example, the suffix is being set on field_url but you are printing field_reg_site_url. That could be causing some confusion.


Django. 301 Redirect from old URL to new

Question: Hello! Please tell me how to organize a redirect correctly.
There is an old version of the site and a new one. In the old version (another CMS, not Django) the objects have their own URL, in the new revised scheme, and the objects have a different URL.
In each object on the new site, there is a completed field with the old URL. In model.py it looks like this:
old_url = models.CharField('Old URL', blank=True, max_length=100)

I specifically moved the old url to a separate field. Or was it not necessary to do this?
Question. How to set up a redirect correctly, so that after going to the object using the old URL, the site visitor will be redirected to the new URL of this object?
Answer: IMHO, I don't think writting old_url for each and every object is pretty inefficient. Instead you can implement a custom 404 view, and handle the redirection there.
I think you can create some regex or plain url maps to new url and redirect accordingly.
import re
from django.http import HttpResponseNotFound

OLD_URL_MAP = { 'old_url_regex': 'new_url_path'}

def handler404(self, request):
    for old_re, new_url in OLD_URL_MAP.items():
        if re.match(old_re, request.path):
            return redirect(new_url, request.resolver_match.kwargs)
    return HttpResponseNotFound('not found')

# inside urls.py
handler404 = 'myapp.views.handler404'

Here I have used a map hard coded in python, you can create a model for that as well.

Update
A costly solution is to use middleware. You can try like this:
import re
from django.urls import resolve

OLD_URL_MAP = { 'old_url_regex': 'new_url_path'}

class RerouteMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            resolve(request.path_info)  # trying to find if the current url exists in your django project. if not, it will throw exception.
        except:
           for old_re, new_url in OLD_URL_MAP.items():  # iterating through urls
             if re.match(old_re, request.path):
                return redirect(new_url, request.resolver_match.kwargs)
        response = self.get_response(request)

        return response

And add that middleware at the bottom of MIDDLEWARE settings.
FYI, its a regex based solution, assuming those urls are dynamic. Instead you can use plain text urls, but its up to you.
Comment: Hello, **ruddra**! Thanks for the answer. How to correctly add a line `handler404 = myapp.views.handler404` to urls.py? Sorry i didn't understand
Comment: @I.Z. Please see these documentations:

https://docs.djangoproject.com/en/2.2/ref/urls/#handler404

https://docs.djangoproject.com/en/2.2/topics/http/views/#customizing-error-views

https://docs.djangoproject.com/en/2.2/topics/http/urls/#error-handling
Comment: I feel stupid. There are no errors and does not work
Answer: Use redirect() from django.shortcuts [the same library from where you import render]. Also, assuming, that the old_url contains only the relative url.
from django.shortcuts import render, redirect
def someView(request):
    q = ~some queryset returning the current object~
    current_url = request.get_full_path().strip("http://www.example.com/")
    if q.old_url == current_url:
       redirect(q.new_url)
    else:
       pass

Remember, redirect() returns an HttpResponse.
Comment: Hello, **dotslash227**! Thanks for the answer. Sorry, but i did not understand a little how this works.
Where to place the code? Under what conditions should this start to work. Sorry again, I didn't understand.
Comment: In your views.py, in which you handling the concerned view, you must have a queryset that would be return you the object with the old_url and new_url.
request.get_full.path() is a method that returns you the full current url of the current view in browser and strip the domain out of it, that will leave you with only the relative url path of the view.
Comment: You can then compare the relative path with the old_url attribute in the queryset and redirect using django.shortcuts.redirect method accordingly to the new url, present in your queryset.
Comment: Thank! I understood the explanations, but it did not work. I'll try to figure it out.


Why C# "using aliases" are not used by default?

Question: Consider the following code.
using System.ComponentModel.DataAnnotations;

namespace Foo
{
    public class Bar
    {
        [Required, MaxLength(250)]
        public virtual string Name { get; set; }
    }
}

Unless you have a fancy IDE (that is doing all sorts lookups & static analysis behind the scenes) it's pretty ambiguous as to where "Required" & "MaxLength" actually come from. Especially when several namespaces might be imported, with similar meaning.
As a relative newbie to C# I am finding myself always having a hard time figuring out where certain things come from. Especially when looking at other code snippets on places like StackOverflow.
using DataAnnotations = System.ComponentModel.DataAnnotations;

namespace Foo
{
    public class Bar
    {
        [DataAnnotations.Required, DataAnnotations.MaxLength(250)]
        public virtual string Name { get; set; }
    }
}

Now it's very obvious where "Required" & "MaxLength" come from. You could take it another step and do something like:
using Required = System.ComponentModel.DataAnnotations.RequiredAttribute;
using MaxLength = System.ComponentModel.DataAnnotations.MaxLengthAttribute;

namespace Foo
{
    public class Bar
    {
        [Required, MaxLength(250)]
        public virtual string Name { get; set; }
    }
}

This is now very similar to how both PHP & Js ES6 works.
I'm curious as to why this isn't the default for C#? And why pretty much every other C# dev I have spoken with considers alias's bad practice? Is there some underlying performance reason perhaps?
Comment: @OP What you're suggesting would result in a `using` statement for every type you use in every .cs file. If you're using 10 types from the `System.ComponentModel.DataAnnotations` namespace, do you want 10 `using` statements, or one?
Comment: In such a case I would still only have one using statement. `using DataAnnotations = System.ComponentModel.DataAnnotations;` Its about tying the actual use of something to it's `using` statement.
Comment: I think you have the answer in your question: "Unless you have a fancy IDE". I would imagine a vast majority of C# developers are working in Visual Studio. I doubt performance has any impact, this would be a compile time thing.
Comment: @BradJones Then you have to type `DataAnnotations.[TypeName]` instead of just `[TypeName]` every time you access one of those types. Does that really benefit anybody? I think it just makes the code unnecessarily verbose.
Comment: In what context are you referring to the concept of "Default"?  You're the one writing the code, you can "Default" it to whatever you write it as.  Sure, those "fancy" editors you just disregarded could auto-insert something like this, but the whole point you were making is what if you're not using that fancy editor.. so your question really doesn't make much sense and contradicts itself.
Comment: You are not alone in sometimes feeling "lost" in C# codebases. C++ has the same problem. ES6 does a lot better here, PHP a bit less so but still better than C#.
Comment: @Brad is this a fair representation of the question?: What (if anything) makes C# dev different from dev in other languages where bulk imports are commonly regarded as bad practice or for special uses?: E.g. the equivalent of `using System;` is prohibited by google style guides for [C++](https://google.github.io/styleguide/cppguide.html#Namespaces), [python](https://google.github.io/styleguide/pyguide.html#224-decision), and [java](https://google.github.io/styleguide/javaguide.html#s3.3.1-wildcard-imports), but not for [C#](https://google.github.io/styleguide/csharp-style.html#using).
Comment: @Brad I think the above version is fact-based and might fly if you're willing to agree or edit. Also, the following deal with the same principle in other languages: [c++](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice), [python](https://stackoverflow.com/questions/2386714/why-is-import-bad), [java](https://stackoverflow.com/questions/147454/why-is-using-a-wild-card-with-a-java-import-statement-bad), [go](https://github.com/golang/go/issues/29326). I think the question here is if/why these arguments wouldn't be equally valid for C# dev. Thanks!
Answer: Why does it matter where types/definitions come from?
If you're truly that concerned about what namespace a type is present in, Visual Studio has the ability to find out in several ways, the two that are my favourite are below:

Hover the type / declaration. This often shows you the full type-name. (Hovering a new SomeType() statement shows you the method name, which is what is applied to attributes.)
Press F12 / Go To Definition. Even if you don't have the source for the definition, using the F12 or Right Click -> Go To Definition will take you to the metadata file that shows you all the public members of the type. This doesn't work on keywords (out, ref, return, null, etc.) but it works on basic aliased types (int, string, etc.) and traditional types (enum, interface, class, struct, etc.). This includes the namespace, type-name, and all public API members. If there are XML docs they are included as well. If you F12 an extension-method it takes you to the class metadata for that extension method. This is extremely helpful for identifying where a method came from if you feel it was injected by something it shouldn't have been.

So now it's not really that difficult the determine what namespace that the type came from. So what about the using aliases, when do we actually need them?
Real life scenario: I have been working on a Windows Forms model for the XNA Framework. XNA Framework has a Color type, and my framework has a Color type. Now I often use both those namespaces together but only need one of the Color types to be used natively. Often times I have a list of using statements that include something like:
using XnaColor = Microsoft.Xna.Framework.Color;
using Color = Evbpc.Framework.Drawing.Color;

So this resolves an ambiguity issue.
Why aren't using aliases a default?
Probably because they're almost never necessary. We don't really need them. If you're concerned about what namespace a type comes from it's far easier to do a quick lookup than it is to alias everything and force a namespace to be defined. At that rate you may-as-well bar using statements altogether and fully-qualify everything.
The biggest two use-cases I've ever had for a using alias are:

Resolve ambiguity between types. See example above.
Resolve ambiguity between namespaces. Same idea as above, but I alias a whole namespace if a lot of types are duplicated.
using XnaF = Microsoft.Xna.Framework;
using Evbpc.Framework.Drawing;

If you're generating code with Visual Studio, importing types, etc., it's not going to use an alias. Visual Studio will, instead, fully-qualify the name as necessary. Ever right-click a squiggle and get A.B.Type as the only option instead of using A.B? Well that's usually a good spot for an alias.
I'll warn you though, using aliases seem to increase maintainability requirements. (This may not have numbers backed up, but I won't lie - this project that I have several aliases in causes me to forget how/what I named an alias frequently.)
Generally, in my experience, if you have to use a using alias, you are probably breaking a rule somewhere.
Why don't we even use them on a regular basis?
Because they suck. They make code harder to read (take your example of DataAnnotations.MaxLength, why do I need to read that? I don't care that MaxLength is in System.ComponentModel.DataAnnotations, I only care that it's set properly), they disorganize code (now I am forced to remember that an attribute is in System.ComponentModel.DataAnnotations instead of System.ComponentModel.DataAnnotations.Schema), and they are just generally clunky.
Take your previous example, I have an Entity Framework project which has attributes something like the following on a class:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

[Key, Column(Order = 2)]
[MaxLength(128)]
public string UserId { get; set; }

[ForeignKey(nameof(UserId))]
public virtual ApplicationUser User { get; set; }

Now with your example I would have one of the following:

using DataAnnotations = System.ComponentModel.DataAnnotations;

[DataAnnotations.Key, DataAnnotations.Schema.Column(Order = 2)]
[DataAnnotations.MaxLength(128)]
public string UserId { get; set; }

[DataAnnotations.Schema.ForeignKey(nameof(UserId))]
public virtual ApplicationUser User { get; set; }

Or:

using DataAnnotations = System.ComponentModel.DataAnnotations;
using Schema = System.ComponentModel.DataAnnotations.Schema;

[DataAnnotations.Key, Schema.Column(Order = 2)]
[DataAnnotations.MaxLength(128)]
public string UserId { get; set; }

[Schema.ForeignKey(nameof(UserId))]
public virtual ApplicationUser User { get; set; }

Or worse yet:

using KeyAttribute = System.ComponentModel.DataAnnotations.KeyAttribute;
using MaxLengthAttribute = System.ComponentModel.DataAnnotations.MaxLengthAttribute;
using ColumnAttribute = System.ComponentModel.DataAnnotations.Schema.ColumnAttribute;
using ForeignKeyAttribute = System.ComponentModel.DataAnnotations.Schema.ForeignKeyAttribute;

[Key, Column(Order = 2)]
[MaxLength(128)]
public string UserId { get; set; }

[ForeignKey(nameof(UserId))]
public virtual ApplicationUser User { get; set; }

I'm sorry, but those are just terrible. This is why 'every' dev you talk to avoids them and thinks this is a bad idea. I'll just stick to intelligently[1] importing namespaces and deal with the very minute potential that types clash. Then I'll use an alias.
If you really cannot find what namespace a type is in (say you pull code from Stack Overflow) then hit up MSDN, go to the Library and search for the type. (I.e., search for KeyAttribute or MaxLengthAttribute and the first links are the API references.)
[1]: By intelligently I mean doing so with responsibility and care. Don't just blindly import / use namespaces, try to limit them as much as possible. SRP and polymorphism usually allow us to keep the using list pretty small in each file.
Comment: Thanks @EBrown, I think it's just something I have to get used to. Just found https://learn.microsoft.com/en-us/dotnet/api/ which has been super helpful.


How to estimate the confidence interval using sample average and sample size ONLY?

Question: Suppose there is a population, with goods and bads. The bad rate of the population(=bads/(bads+goods)) is of course unknown.
Now, I have a sample of $N$ from the population and I know the bad rate of this sample as $b$. The question is can I calculate the confidence interval based on $N$ and $b$ ONLY? In other words, can I calculate the confidence interval $x$ such that with, say, 95% confidence the population bad rate falls in $[\text{range}_1,\text{range}_2]$, where $\text{range}_1$ will be $b-x$ and $\text{range}_2$ will be $b+x$.
Comment: Under random sampling, yes; this is simply a confidence interval for a binomial proportion, with the usual caveats about the assumptions of and interpretation of confidence intervals.
Comment: As long as $np(1-p)$ is not small (bigger than 10 is usually plenty), you can use the normal interval described [here](http://stats.stackexchange.com/questions/30281/sample-size-for-binomial-confidence-interval/30306#30306). If the $n$ is small and $p$ is very near 0 or 1, you may need to consider one of the [other binomial approximate confidence intervals](http://stats.stackexchange.com/questions/28316/confidence-interval-for-a-proportion-when-sample-proportion-is-almost-1-or-0). Many other posts here cover aspects of CIs for binomial proportions; the search bar turns many up.
Comment: Further examples of previous posts on this topic: [e.g. 1](http://stats.stackexchange.com/questions/4756/confidence-interval-for-bernoulli-sampling), [e.g. 2](http://stats.stackexchange.com/questions/4756/confidence-interval-for-bernoulli-sampling)
Comment: Just as a side note - if you want to control your confidence level, then the size of the interval also depends on that.
Answer: Exactly as Glen_b said. Under random sampling the confidence interval for a binomial proportion can be easily calculated with, e.g., using the normal approximation. The formula can be found from Wikipedia, among other sources (http://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval).
As an example, the 95% confidence interval for a sample of 1000 with the proportion of bad of 0.5, the confidence interval would be from 0.5-sqrt((1/1000)*0.5*0.5)*1.96 to 0.5+sqrt((1/1000)*0.5*0.5)*1.96. In other words, in this case the 95% confidence interval would be 0.469-0.530.


Spring integration - Generic Webservice Outbound Gateway, any performance issue?

Question: I have an application which connects to more than 15 SOAP services. is there any performance issue if I use a single instance of a ws outbound gateway for all the calls. The idea is to create a GENERIC SOAP Connector implementation by externalizing the ws outbout gateway configurations such as endpoint url, marshaller, unmarshaller etc.
Answer: No, there is no big difference, because WS Outbound Gateway is fully based on the WebServiceTemplate which is stateless, therefore any concurrent request doesn't impact each other.
Only might be the problem that you can't change  marshaller/unmarshaller at runtime. They are really fully tied with WebServiceTemplate instance.


Isolate all variables to LHS in sympy?

Question: I am using sympy to process some equations. I want to write the equations in a canonical form such that variables of interest are all on LHS. For eg. if I have,
lhs = sympify("e*x +f")`
rhs = sympify("g*y + t*x +h")`
eq = Eq(lhs,rhs)
e*x + f == g*y + h + t*x

I need a function which can isolate a list of given variables (my so called canonical form), like
IsolateVariablesToLHS(eq,[x,y]) # desired function
(e-t)*x - g*y == h-f # now x and y are on LHS and remaining are on RHS

I have the assurance that I will only get linear equations, so this is always possible.
Answer: >>> import sympy as sm
>>> lhs = sm.sympify('e*x + f')
>>> rhs = sm.sympify('g*y + t*x + h')
>>> eq = sm.Eq(lhs, rhs)

Here's a simple construct
def isolateVariablesToLHS(eq, syms):
    l = sm.S.Zero
    eq = eq.args[0] - eq.args[1]
    for e in syms:
        ind = eq.as_independent(e)[1]
        l += ind
        eq -= ind
    return sm.Eq(l, eq)

>>> isolateVariablesToLHS(eq, [x, y])
Eq(e*x - g*y - t*x, f - h)

Answer: With the equation as provided in the question combine all the terms and construct a filter for discovering the required variables.
>>> from itertools import filterfalse
>>> terms = eq.lhs - eq.rhs
>>> vars = ['x', 'y']
>>> filt = lambda t: any(t.has(v) for v in vars)
>>> result = Eq(sum(filter(filt, terms.args)), - sum(filterfalse(filt, terms.args))
>>> result
e*x - g*y - t*x == -f + h

I'm not familiar with sympy but I think this will work for equations consisting of proper atoms such as Symbols. Make sure you replace the vars list with the actual instantiated Symbols x, y instead of the 'ascii' representations. This is probably required to combine terms that have variables in common.
filter and filterfalse might have different names in python 2.x, but this functionality is probably still in the itertools package.

Isolate all variables to LHS in sympy?


Lower Central Series and Generators

Question: Let $G$ be a group generated by $S=\{x_1,\cdots,x_n\}$ and let its lower central series be defined as $\Gamma_1=G$, $\Gamma_m=[\Gamma_{m-1},G]$ for $m\geq 2$.
By definition $\Gamma_m$ is generated by all iterated commutators of the form $[[g_1,g_2],\cdots,g_m]$, where $g_1,\cdots,g_m\in G$.
Is it true that $\Gamma_m$ is generated by all iterated commutators of the form $[[x_{i_1},x_{i_2}],\cdots,x_{i_m}]$, where $x_{i_1},\cdots,x_{i_m}\in S$?
Comment: Sorry, what I said was wrong. It is true that $\Gamma_m$ is generated modulo $\Gamma_{m+1}$ by iterated commutators of length $m$. That is true for any group, and you can prove it by induction on $m$. So, for a nilpotent group, $\Gamma_m$ is generated by iterated commutators of length greater than or equal to $m$.
Comment: It's true if $G$ is nilpotent.
Comment: Thanks @DerekHolt! Where can I find a reference of this property?
Comment: @DerekHolt, Actually I am interested in pure braid groups $P_n$. I think that they are residually nilpotent but not nilpotent. In this case, is the conclusion still true for pure braid groups?
Comment: It's not true for residually nilpotent groups in general, because free groups are residually nilpotent. For the pure braid group, I think that $[P_n,P_n]$ is probably not finitely generated.
Comment: @DerekHolt, right; [it is not finitely generated](http://mathoverflow.net/questions/134171/finite-generation-of-the-commutator-subgroup-of-the-pure-braid-group). Then is there a way to determine $\Gamma_m(P_n)$ in general? Actually I have asked this question at [mathoverflow](http://mathoverflow.net/questions/189042/lower-central-series-of-pure-braid-groups).
Comment: @DerekHolt. Can you give a reference for a proof that if $G$ is nilpotent then $\Gamma_{m}$ is generated by the iterated commutators of the given form?
Answer: This is not true, even for $\Gamma_2$. Let $G$ be the free group on $S$; it is known that $[G,G]$ is not finitely generated (provided that $\vert S\vert\ge 2$), hence it cannot be generated by all commutators of the form $[x_{i_1}, x_{i_2}]$ since there are only finitely many such.
Comment: Thank you for your reply!

Lower Central Series and Generators


divergence of $\sum_{n \in \mathbb N} \frac{|a_n|^2}{1 + \sum_{k=1}^n|a_k|^2}$ when $\sum_{k \in \mathbb N} |a_n|^2 = \infty$

Question: How can I proof that the divergence of the series $$\sum_{n \in \mathbb N} \frac{|a_n|^2}{1 + \sum_{k=1}^n|a_k|^2}$$ when $\sum_{k \in \mathbb N} |a_n|^2 = \infty$
I've been trying Cauchy test, ratio test and by contradiction, but I couldn't proof yet.
May someone give a hint of why this series diverges?
Answer: It's maybe an overkill, but you can prove that the sequence of partial sums of $\sum_{n \in \mathbb N} \frac{|a_n|^2}{1 + \sum_{k=1}^n|a_k|^2}$ is not Cauchy.
Let $S_n=\sum_{k =0}^n |a_k|^2$. Note that $S_n$ is an increasing, nonnegative sequence that goes to $\infty$ as $n$ goes to $\infty$
For any $N\in \mathbb N$ and $q\geq N, \sum_{k=N+1}^q \frac{|a_k|^2}{1 + S_k}\geq \frac{1}{1+S_q} \sum_{k=N+1}^q |a_k|^2=\frac{S_q-S_N}{1+S_q}= 1 - \frac{1+S_N}{1+S_q}$.
For fixed $N$, $\displaystyle \lim_{q\to \infty} \frac{1+S_N}{1+S_q}=0$. You can therefore find some $q\geq N$ such that $\displaystyle \frac{1+S_N}{1+S_q}\leq \frac 12$
For such a $q$, $\displaystyle \sum_{k=N+1}^q \frac{|a_k|^2}{1 + S_k} \geq \frac 12$
Putting everything together, I've proved that $\exists \epsilon > 0, \forall N\in \mathbb N, \exists p\geq N,  \exists q\geq N,\left|\displaystyle \sum_{k=p+1}^q \frac{|a_k|^2}{1 + S_k}\right|\geq \epsilon $ (namely, $\epsilon=\frac 12$ and $p=N$)


Let f: $\mathbb{R}^2 \mapsto \mathbb{R}^2$ be a linear function, proof about $f$ and directional derivative

Question: I have this $f$ that is linear and I want to show that for any $a,v \in \mathbb{R}^2$
$f(\begin{matrix}
  a_1 + v_1 \\
  a_2 + v_2 \\
 \end{matrix})$ = $f(\begin{matrix} a_1 \\ a_2 \\ \end{matrix}) + [Df(a)]   \large\vec{v}$
So, it suffices to show that
$[Df(a)]   \large\vec{v} = f(\begin{matrix} v_1 \\ v_2 \\ \end{matrix})$
how can I do this? I can't figure out a way to write down the derivative as anything but a difference quotient at a and that's not helping.
Answer: By the definition of the derivative, $f$ is differentiable at $a$ iff there is a linear transformation $B$ such that the following limit is zero:
$$\lim_{h\to\vec0} \frac{f(a+h)-f(a)-B(h)}{\|h\|} = 0$$
Since $f$ is linear, you can rewrite the numerator as $f(h)-B(h)$, which is clearly 0 if we
let $B$ just be the linear transformation $f$. Therefore, $Df(a) = f$ and
$$f(a+v) = f(a) + f(v) = f(a) + Df(a)(v)$$
Comment: $P\to Q$ and$\neg Q \to \neg P$ are equivalent statements. Proof left to the reader ;)
Comment: So really, all we had to do was show that f was differentiable at a, cool. Are you sure we can just take f to be the derivative operator though? It just seems like one out of many possible linear functions.
Comment: If the derivative at $a$ exists, then it must be unique. So since $B = f$ lets the limit go to 0, it must be the derivative. I usually overlook this tiny fact, but look at that it was very useful right now! :D
Comment: OH I see now, so we're letting B just be our function f which gives us 0 so we have that f is differentiable at a.

this part of your statement still confuses me:

"..which is clearly $0$ if we let $B = Df(a)$ just be the linear transformation $f$"

so we're letting $B$ be the derivative of $f$ at $a$ and $f$ itself? what?
Comment: That was a slight abuse of notation. In the limit, if $B$ is a linear transformation and the limit goes to zero, then it is the derivative. I edited the statement, lemme know if it's more clear.
Comment: interesting. so really f must be the derivative in this problem
Comment: what about the converse: clearly if $f$ is NOT linear then this is false?
Comment: You can prove the converse as well, but I'm gonna prove it like this: the equation holds $\to$ $f$ is linear. This is equivalent to your last question.

If $f(a+v) = f(a) + Df(a)(v)$ for all $v \in \mathbb{R}^2$, then by linearity and subtracting $f(a)$ from both sides, $f(v) = Df(a)(v)$. Since $Df(a)$ is a linear function, so must be $f$. Therefore the converse you just asked about is true as well.
Comment: wait, if and only if proves the converse?
Comment: haha, true. thank you! you're really good at math unlike me! (see my name)
Comment: Wait, you used linearity of f and then proved linearity of f by D? I don't get it
Comment: can you please come back and address what I said? you didn't correctly prove that the equation holding implies f is linear.
Comment: Whoops! Well, the converse is actually NOT true: Let $f(x,y) = (x,y)+(1,1)$, which is not linear because $f(0,0) = 1$. However, $Df(0)$ is the linear transformation that sends $(x,y)$ to $(x,y)$ and
$f(x,y) = f(0,0)+Df(0)(x,y)$.

Your question holds and is an iff statement when you make the weaker assumption that $f$ is an affine transformation, but it only goes one way if $f$ is linear.
Comment: sorry, yeah! I mixed up the terms "converse" and "contrapositive"!

In any case, is there a way to do that proof you tried without randomly pulling out linearity and using it to prove linearity? :P


No sound when playing mp3/midi from any device except Nord Piano

Question: I recorded a midi file in Cubase11 Elements 11 using Nord Piano 4. I exported the audio both in midi and mp3 but there's no sound. I can hear my track only when playing directly from Cubase when connected to my Nord Piano. Also I can open midi from GarageBand but it opens it up with its own sound from its local library. What I want - to have a recording with the original Nord sound when playing from any device.
Comment: @DariaIvanova yes - MIDI is not audio, it's just instructions to the instrument saying 'play this note', 'stop playing this note', etc. If you want to get an audio recording, you'll need to record the audio output of the nord while you are sending the midi instructions in to it. The workflow you suggest - record midi, clean up a few mistakes in the midi, then replay the fixed midi and record the audio - sounds very sensible.
Comment: If you are mainly interested in the Nord sound, why not record the sound instead of a midi track?
Comment: If you have recorded midi in cubase, but recorded no audio, "no sound" is exactly what I'd expect, i think? Have you actually recorded any audio in cubase before you export? You should be able to record the output of the Nord playing the midi track...
Comment: I'm surprised the MP3 doesn't export with the soundfont. However, I believe this is normal behaviour for MIDIs - the proliferation of videos with various computers' interpretation of music from games from *The Incredible Machine* series is one attestation to this.
Comment: @Tom I wanted to clean up some things like a dirty pedal or occasionally loud sound where it should be quiet, and midi allows you to do all of it
Comment: @topomorto I'm very new to this so my question might sound silly, but do you mean that I can play midi through the Nord Piano and make it get recorded as audio?
Answer: As far as I understood what you want to do, the workflow should be the following:

Record MIDI (you have done it)
Edit the MIDI recording, as needed
Create an audio track in your DAW.
Connect output of your electric piano to the input of your audio interface.
Record Audio: set the cursor to the beginning of the project (or beginning of the section you want to record) and click "record". Let the whole piece play until the end, then click "stop".

Note, that as audio will be transmitted in analog domain you need to take some steps to ensure good sound quality, the same as with recording real instruments:

make sure there are no drops in recording: set audio interface buffers/latency sufficiently high, don't load your computer with other unnecessary tasks at the same time
set the gain correctly: typically you want to set your piano volume to the maximum and adjust the audio interface gain so that the signal is high, but doesn't reach the maximum even in the loudest parts
make sure the audio cables and connectors are in good shape, avoid touching them during the recording
Comment: Thank you! My mistake was that for some reason when I tried to record audio I thought that I don't have to turn on the sound on the Piano at all. Thought the sound will transfer digitally (that's how far I'm from sound production). Now everything makes sense. Thanks a lot!
Comment: @DariaIvanova Your assumption wasn't completely unfounded, USB is often used to transfer audio, but in case of your particular piano only MIDI is transmitted.


Can a straight line be considered a part of a circle?

Question: Say we have a circle of infinite radius. If we zoom in infinitely on its perimeter, we should end up looking at a straight line. Intuitively. But, such a line, I believe, should have a curvature of $1/∞$. But a straight line is defined to have $0$ curvature in Euclidean geometry. My interpretation also has problems if we consider parallel lines. Can someone guide me on this?
Comment: What does "circle of infinite radius" even mean?
Comment: "Zooming in infinitely" : you really need to make things more precise.
Comment: Um, if I was looking at a part of the perimeter of a circle on a flat plane, and then kept increasing the radius such that it tended to infinity, while keeping my view fixed on the portion I was observing, wouldn't it converge to a straight line?
Comment: "tending to infinity" is not "equal to infinity".  It will "tend" to a straight line.  But it will never achieve it.  And it will never achieve infinite radius either.
Answer: "circle of infinite radius"
Meaningless.
"If we zoom in infinitely"
Meaningless.
"we should end up looking at a straight line"
A straight line that is a magnification of a single point.  Which is meaningless.
$\infty$ is not a number or a value. It is a concept to describe values that may be arbitrarily large and have no upper bound.
All circles have finite radius.  But for any value $M$ we can have a circle with radius $> M$.  So the radius becomes large the curvature becomes smaller.  We state that as $\lim_{r\to \infty} Curvature (r) = 0$ (and similarly $\lim_{x \to \infty} \frac 1x = 0$).  But that does not mean infinite radius or $0$ curvature or $\frac 1 {\infty}$ ever occur.  They don't and can't.
But yes for a circle with extremely huge radius will have extremely small curvature and the arcs will become arcs that differ from a line segments only very slightly.  But it is never infinite radius or zero curvature.  And although the arc will differ from straight lines only minisculely, they will differ.
Answer: No, it can't. A straight line can't be considered as part of a circle.
I can remember from my algebra class (long time ago), that at some point we had to take the limit of $x$ to zero. And the teacher was screaming: we never get to zero (my ears are still ringing). To give you an example, for $f(x)=\frac{1}{x}$ we have:
$$
\lim_{x\rightarrow0}f(x)=\lim_{x\rightarrow0}\frac{1}{x}=\infty,
$$
but $f(x)$ does not exist for $x=0$.


How do I reset unacknowledged messages in PubSub?

Question: The PubSub tab of the console shows that there is a message that wasn't acknowledged (probably answering my question on whether one needs to acknowledge pubsub messages: Do I need to consume pubsub messages?).
How do I reset the unacknowledged messages?
The device has the following code:
<code>import pubsub

TOPIC ::= "<MY_TOPIC>"

main:
  print "wakeup - checking messages"
  pubsub.subscribe TOPIC --blocking=false: | msg/pubsub.Message |
    print "Received message"
  print "done processing all messages"
</code>
But that doesn't seem to consume older messages that were there before.
Answer: Messages will automatically be retried after a certain duration.
We have a 10 min acknowledgement deadline and messages that has not been acknowledged within that period will be retried.
Comment: When will they be retried? I think I have a subscription that is now several days old, but I don't think it has been retried.


Script em Python via PHP

Question: Estou tentando chamar um script feito em Python via browser com PHP. Esse script possui apenas um comando que serve para desligar minha Raspberry Pi.
O PHP está dessa forma:
<?php
 exec('sudo python /home/pi/Documents/Programa/Script.py');
?>

Script Python:
import os
os.system('sudo shutdown -r now')

Eu executei o programa em Python e PHP (via terminal) separadamente e os dois estão funcionando corretamente. Apenas quando chamo no browser que ele não executa. Sei que tem que alterar permissões de pastas e arquivos, mas não sei exatamente quais diretórios tenho que dar essas permissões pois sou iniciante no mundo do PHP e do linux. Eu já procurei em alguns outros site meios de fazer isso.

PHP executando PYTHON
https://www.vivaolinux.com.br/topico/Shell-Script/Como-executar-um-comando-em-shell-script-pelo-navegador
Comment: Por que você não executa o "shutdown" direto do PHP? Esse script nem tem nada de Python.
Comment: Olá jsbueno, obrigado por sua resposta. Você diz para eu colocar o comando "sudo shutdown -r now" direto no exec() do php? isso eu já fiz, também não funciona.
Comment: Não mostra nenhuma mensagem de erro? já viu no log do php ou do server?
Comment: Oi Júlio Neto, obrigado pela resposta. Eu não sei onde fica o log, vou procurar para ver se aparece alguma mensagem lá e volto com  a resposta.
Answer: O php não tem permissão para desligar o computador. Ele roda com um usuário interno de serviço, (geralmente www-data), e esse usuário não tem permissão para executar o sudo.
Quando você roda com seu usuário, no terminal, funciona, porque o seu usuário tem a permissão de usar o sudo, mas ao fazer o php rodar o comando, vai falhar, porque o usuário que está rodando o servidor php não tem essa permissão.
Comment: @Q.Wesley Como o nosklo falou, é somente questão de permissão perante ao `sudo`. Se você adicionar o usuário do PHP, comumente `www-data` (confirme), à lista de *sudoers*, que são usuários com permissão ao `sudo`, você provavelmente conseguirá fazer algo do tipo. Mas antes de qualquer coisa, recomendo rever o comentário do [jsbueno](https://pt.stackoverflow.com/questions/331063/script-em-python-via-php#comment670193_331063), pois não temo motivo de fazer isso com o Python sendo que você pode executar o comando a partir do PHP.
Comment: Olá, eu entendi sua resposta, mas no caso não tem como eu dar essa permissão para o PHP? Eu vi em um dos links que citei ali em cima que você pode dar permissões a determinados arquivos e pastas, mas como não entendo muito de linux(raspbian) eu não sei exatamente como fazer.
Comment: @Q.Wesley, sim, o Anderson está certo. Você pode executar o shutdown direto do php, não precisa do python intermediário. A questão é configurar seu `sudo` - você pode fazer uma pergunta sobre como configurar o `sudo` no superuser.com (inglês)

Script em Python via PHP


PHP + space issue

Question: I want to get the number of spaces added before a word.
For example
String 1 = Hello
String 2 =    Server.

In String 2 there are four spaces before Server. when I concatenate string 1 and string2 I loose the spaces.
Basically space should be treated as a character. How do I do this?
Answer: You don't lose your spaces in a concatenation:
$s1 = 'Hello';
$s2 = '    Server';

print_r($s1.$s2);

Outputs
Hello    Server

http://ideone.com/PmHOQ
Answer: To avoid losing your spaces, try to echo the string in a

Html tag (or simply check it with var_dump or in the html source).
Comment: How did you figure out he was talking about HTML output?
Comment: It's a common question :) and console,file etc output shows the whitespaces.
Comment: Another easy way to tell the browser to display repeated spaces is to replace them with the   non-breaking space character. i.e.: `str_replace('  ', '  ', $string)`
Comment: common question? then why don't you flag it as a duplicate?
Comment: @zaf Common question from beginners. flag it if you want. cheers
Answer: I'm guessing you're having problems with html collapsing spaces. You just need to replace with non breakable spaces.
You could do that:
calculate how many spaces are in front:
$diff = strlen($s2) - strlen(ltrim($s2,' '));

prefix the trimmed string with non breakable spaces:
$s2 = str_repeat(' ', $diff) . ltrim($s2,' ');

Alternatively, you could use strtr to replace all ' ' into ' '

PHP + space issue


Find closet PSD matrix to given diagonal matrix

Question: Let's say I have an arbitrary diagonal matrix $A$. I want to convert this diagonal matrix to the closest matrix by some metric that is also PSD. Is there a standard way to do this?
This is for a program I'm writing. Currently, I have a small function to convert a diagonal to a PSD matrix but not to the closest PSD matrix.
<code>def to_PSD(A_diag, eps=0.00001):
    """Convert an n-by-n diagonal matrix, represented as an n-vector, into a
    positive semi-definite matrix.
    """
    A_diag[A_diag < 0] = eps
    A_diag[np.isclose(A_diag, 1)] = eps
    return A_diag
</code>
Is there a better way to do this? (No code needed.)
Answer: You can define a distance between symmetric  matrices $A$ and $B$ by using $d(A,B)=\sqrt{\mathrm{tr}(A-B)^T(A-B)}$, equivalently, by $d(A,B)=\sqrt{\sum_{i,j}(a_{ij}-b_{ij})^2}.$  For this metric, I think it's obvious that the closest psd matrix to diagonal matrix $A$ is obtained by replacing all negative entries on the diagonal of $A$ by zero.   Also for the metric
  $\sqrt{\sum_{i\le j}(a_{ij}-b_{ij})^2}.$