How does Rainbow's End by Peter Weniger work?

Question: This is Rainbow's End, composed by German saxophonist Peter Weniger. It first sounds like a straightforward 12-bar Blues in F, The melody sounds pretty normal, but as soon as it comes to the solos, something seems to be off. During the solos, one thinks that it is in fact a different kind of blues, sixteen bars maybe. After closer examination of the head, it became clear that it in fact was a Thirteen-bar blues. Counting in the solos does give different conclusions though, sometimes it feels like twelve, sometimes like sixteen, sometimes it is twelve, sometimes it is 13, sometimes 14, sometimes anything.
The harmony, as far as I can Tell is 4 bars of F7, two of Bb7, two of F7, Two of C7 and then it becomes shady.
My question is: How does this piece work? Can anybody see any patterns in there, and what is that last bit of harmony?
Cheers
Comment: FWIW, assuming the band in question is prepared, a solo could run for a few standard-length choruses and then add a "bridge" measure or two just for effect.  Sort of like a classical cadenza.
Answer: I'll focus on the end, which is where the tune deviates from a normal blues.
Harmonically, the bass is ascending chromatically from B, while the chords descend chromatically from E♭Maj. (You can most clearly hear these chords in the saxophone, which outlines those triads in the melody.) The combination of ascending and descending creates an interesting contrast, and it results in some weird chords: E♭Maj/B, DMaj/C, and D♭Maj/D.
Rhythmically, it's equally strange. Things start to get weird in measure 9: the melodic phrase from the end of measure 9 feels like it begins one beat too late. This is no coincidence; a nearly identical phrase occurs in measure 4, starting on beat 2. But when we hear this phrase again in measure 9, it starts on beat 3 (one beat later), and it doesn't conclude until beat 2 of the following measure. As a result, it feels like the downbeat of measure 10 is delayed from beat 1 to beat 2. The rest of the band emphasizes this staggered feeling by playing hits on beats 2 and 4 of measures 10, 11, and 12, which further makes the listener feel like the downbeat has been delayed from beat 1 to beat 2.
On the solos, there's a different form for the bass than for the rest of the band. Generally, each measure of the melody has been doubled for the solos. But the bass solo is only 22 measures long, whereas the other solos are 26 measures long (double the head). The bass solo deviates quite a bit from the harmonic structure of the head, but the other solos do too.
None of the solos include the strange descending/ascending chords featured in the melody, but the pianist does repeatedly use a chord substitution in the last four bars, which goes something like | E♭7 | A♭7 | G7 | C7 |. You can tell it's a substitution and not written into the sheet music because, at 1:56, the bass is riffing on the F7 lick while the pianist's left hand is playing the chord substitutions. Something similar happens at 2:24, the second time through the form on the pianist's solo. The bass riffs on F7 and doesn't pick up the pianist's chord substitution until G7. Overall, though, those substitutions most likely weren't part of the written music. I think the chords written for the solos were pretty simple.
Here's everything I'm hearing. Measure 13 of the head is one octave lower.
Comment: E♭/B is an inversion of Bmaj7, and D/C is an inversion of D7. What's so unusual about those? But +1, great answer!
Comment: @user45266, thanks! Are you thinking of E♭min/B rather than E♭Maj/B? E♭Maj contains a G♮ (which isn't present in BMaj7). DMaj/C definitely could be an inversion of D7 like you've said, but with the chord passing so quickly and the bass laying down heavy root notes throughout the song, I'm getting more of a Lydian vibe. But to your point, that chord is definitely not as uncommon as the other two.
Comment: Oh, I misread the chord labels. I'll blame the 'M's (I thought it meant major, my bad). Never mind :)
Answer: You're right that the melody is 13 measures long. Just from listening, it sounds like during the solos, they stay on each chord for twice as long. So the solo choruses are sort of a 26 bar blues.


Mal-funcionamento do site após alteração no .htaccess

Question: Para um site ficar com url mais amigável eu removi o .php utilizando os seguintes comandos dentro do .htaccess:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^([^\.]+)$ $1.php [NC,L]

Funcionou perfeitamente para a parte de noticias.php, e o site www.exemplo.com.br abre sem a necessidade de adicionar index.php.
No entanto, o problema está no painel administrativo, que se faz necessário eu adicionar index. Ficando obrigatoriamente nessa forma:
www.exemplo.com.br/painel/index

ou
www.exemplo.com.br/painel/index.php

Como posso solucionar isso? Acessar apenas com /painel/
Obrigado!
Answer: Só está faltando o RewriteBase / deixe seu código assim:
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Comment: Alterei o htaccess conforme sugeriu porém ainda não funcionou! Continuo não conseguindo acessar por www.exemplo.com.br/painel e acessando apenas via www.exemplo.com.br/painel/index
Answer: Olá,
Eu utilizo esta regra abaixo para poder ter esse efeito.
Eu possuo uma pasta e dentro dela um arquivo index.php comum.
Exemplo:

www.meusite.com.br/dashboard/novo-cadastro/

O dashboard é uma pasta;
O novo-cadastro é uma pasta;
Dentro da pasta novo-cadastro possui um arquivo index.php
No .htaccess que está na raiz do projeto, há a seguinte regra:
<IfModule mod_rewrite.c>
RewriteEngine on
    RewriteCond %{HTTP_HOST} ^www.meusite.com [NC]
    RewriteRule (.*) https://hecato.com/$1 [R=301,L]
    RewriteRule ^([a-z0-9]+)/?$ index.php?user=$1 [NC,L]
    RewriteCond %{HTTP_HOST} ^(^.*)\.hecato.com
    RewriteRule (.*) index.php?user=%1
</IfModule>

Caso não resolva, sugiro que crie outro .htaccess dentro do diretório que você quer criar essa regra (no caso, a pasta /painel).
Qualquer dúvida estamos aí.
Espero ter ajudado


If statement not being entered in for loop

Question: I have a geojson file with earthquake point features that need to be styled based on the magnitude of the quake. The switch statement works correctly but it's a lot of code that I think could be done neater:
switch (feature.properties.mag){
            case 1.0 : return layer.setRadius(5);
            case 1.1 : return layer.setRadius(5);
            case 1.2 : return layer.setRadius(5);
            case 1.3 : return layer.setRadius(5);
            case 1.4 : return layer.setRadius(5);
            case 1.5 : return layer.setRadius(5);
            case 1.6 : return layer.setRadius(5);
            case 1.7 : return layer.setRadius(5);
            case 1.8 : return layer.setRadius(5);
            case 1.9 : return layer.setRadius(5);
            case 2.0 : return layer.setRadius(8);
            case 2.1 : return layer.setRadius(8);
            case 2.2 : return layer.setRadius(8);
            case 2.3 : return layer.setRadius(8);
            case 2.4 : return layer.setRadius(8);
            case 2.5 : return layer.setRadius(8);
            case 2.6 : return layer.setRadius(8);
            case 2.7 : return layer.setRadius(8);
            case 2.8 : return layer.setRadius(8);
            case 2.9 : return layer.setRadius(8);
            case 3.0 : return layer.setRadius(10);
            case 3.1 : return layer.setRadius(10);
            case 3.2 : return layer.setRadius(10);
            case 3.3 : return layer.setRadius(10);
            case 3.4 : return layer.setRadius(10);
            case 3.5 : return layer.setRadius(10);
            case 3.6 : return layer.setRadius(10);
            case 3.7 : return layer.setRadius(10);
            case 3.8 : return layer.setRadius(10);
            case 3.9 : return layer.setRadius(10);
            case 4.0 : return layer.setRadius(15);
            case 4.1 : return layer.setRadius(15);
            case 4.2 : return layer.setRadius(15);
            case 4.3 : return layer.setRadius(15);
            case 4.4 : return layer.setRadius(15);
            case 4.5 : return layer.setRadius(15);
            case 4.6 : return layer.setRadius(15);
            case 4.7 : return layer.setRadius(15);
            case 4.8 : return layer.setRadius(15);
            case 4.9 : return layer.setRadius(15);
            case 5.0 : return layer.setRadius(20);
            default: layer.setRadius(8);
        }

I think the for loop might be caught up on the conditional statement because all the points are styled the same and not with the else value:
for (var i=0; i<feature.properties.length; i++){
            if (1.0 <= feature.properties.mag < 2.0){
                 return layer.setRadius(5);
            }

            else if (2.0 <= feature.properties.mag < 3.0){
                 return layer.setRadius(8);
            }

            else if (3.0 <= feature.properties.mag < 4.0){
                 return layer.setRadius(10);
            }

            else if (4.0 <= feature.properties.mag < 5.0){
                 return layer.setRadius(15);
            }

            else{
                 return layer.setRadius(2);
            }
            }

Comment: What's the point of the for loop? you're not iterating over anything..
Comment: is it possible for `feature.properties.mag` to be `1.05`, etc between those case values? If so, the `if` is definitely the way to go
Comment: you can group switch statements, see : http://stackoverflow.com/questions/13207927/switch-statement-multiple-cases-in-javascript
Comment: There is no point to the for loop, new to java was just overthinking it. The magnitude values only have 1 significant digit, but if is still the way to go.
Answer: First, your conditionals are not right. Try them like this setting a lower and upper bound.
if (feature.properties.mag >= 1.0 && feature.properties.mag < 2.0){
    return layer.setRadius(5);
}
// the rest similar to the above

Unless there is more to feature.properties we aren't seeing, the for-loop is unnecessary.
Comment: Should probably get rid of the `for` loop also since it doesn't do anything.
Comment: Agreed. For loop isn't needed... unless there is more to `feature.properties` we aren't seeing
Comment: It's worth explaining what OP's code does. It evaluates the left inequality (e.g., `1.0 <= feature.properties.mag`) and obtains a `true` or `false` value. That value is then converted to an integer value (either 1 for `true` or 0 for `false`) to do the second comparison.
Comment: Cool! BTW @TedHopp made a good comment about the inequalities.
Answer: Why not use Math.floor() on feature.properties.mag?
switch (Math.floor(feature.properties.mag)){
       case 1.0 : return layer.setRadius(5);
       case 3.0 : return layer.setRadius(10);
       case 4.0 : return layer.setRadius(15);
       case 5.0 : return layer.setRadius(20);
       default: return layer.setRadius(8);
}

Switch is a replacement for long if-elseif chains
Comment: You need a `return` in the `default` case.
Comment: Edited answer, sorry)
Comment: Was not aware of the Math.floor() function, that code looks a lot cleaner. Thanks!


How do I prove that a function grows faster than another?

Question: I need to prove that one function, say $n$ grows faster than say, $\sqrt{n}$?
Comment: Do you want to know show that "say" $n$ grows faster than "say" $\sqrt{n}$ or do you want to show that $n$ grows faster than $\sqrt{n}$? Only one of these is an acceptable question (and you should still add more details about your thoughts and attempts so that we can place your question in to context.
Comment: Use Principle of mathematical induction.
Answer: There are many ways.  One, which works here, is to divide $\frac n{\sqrt n}=\sqrt n$ and show that goes to infinity as $n$ gets large.
Often in these problems "grows faster" means at least that the difference grows without bound, sometimes that the ratio grows without bound.  You need to be clear which you want.  In this example, we meet both requirements.
Answer: I would compute the first Derivation $f(n) = n$ and $g(n) = \sqrt{n}$. If $f^\prime(n) > g^\prime(n)$ then $f$ grows faster than $g$.
Comment: How do you know if f'(n) > g'(n)?
Comment: In your example, $1 > \frac{1}{2\sqrt{n}}$, so $n$ is constantly growing at a rate of 1 whereas the other function is decreasing at a rate of $\frac{1}{2\sqrt{n}}$.
Comment: What if I had, say, logn and n?
Comment: Also, what about $f$ and $g$ where $f'(n) > g'(n)$, but there exists $m > n$ such that $f'(m) < g'(m)$?
Comment: Maybe we should first discuss the meaning of _grows faster_. The first derivation shows how fast a function f grows at a fixed point $n$ (in your example it has always a 'growing factor' 1'). The function $g$ has a growing factor $\frac{1}{2 \sqrt{n}}$. If we now look at the 'growing factor' at the point $n = 0.5$. The $g$ grows faster then the function $f$: $1 < \frac{1}{2 \cdot 0.25} = 2$. But for $n = 2$ $f$ grows faster then $f$: $1 > \frac{1}{2}$. As you see the _growing rate_ is only a local property.
Comment: If you want to know what happens for $n \rightarrow \infty$ you could analyze the behaviour of the derivations for $n \rightarrow \infty$. But there are many functions where you can't decide your question for $n \rightarrow \infty$ (e.g. $f(x) = \cos(x)$ and $g(x) = \sin(x)$).


Can we always find homotopy of two paths which lies "between" the paths?

Question: Let $\gamma_0,\gamma_1:[0,1]\to\mathbb{R}^2$ be paths such that $\gamma_0(0)=\gamma_1(0)$ and $\gamma_0(1)=\gamma_1(1)$.  I wish to show that there is a homotopy $\Gamma:[0,1]\times[0,1]\to\mathbb{R}^2$ from $\gamma_0$ to $\gamma_1$ that satisfies the following:

For all $(s,t)\in[0,1]\times[0,1]$, $\Gamma(s,t)$ is not in the unbounded face of $\gamma_0([0,1])\cup\gamma_1([0,1])$.

PS: If the answer is no, are there additional restrictions which we could place on $\gamma_0$ and $\gamma_1$ which would allow this?  (Ex. rectifiable, differentiable, etc.)
Answer: If you allow the contour of the union of those two paths to form a simple closed curve*, this is true, and can be seen as a consequence of the Schoenflies Theorem together with the fact that the disk is contractible.

*I think this is the case, since you are talking about "unbounded face".
Comment: I am a little concerned about this.  Just because the bounded face is homeomorphic to the the disk, does this tell us that that homeomorphism extends to a homeomorphism from the boundary to the circle?  I think you are using something like this.
Comment: @TrevorRichards Search up for "Jordan-Brouwer Separation Theorem". It can be found on Bredon, for example (page 234). It states precisely that the embedded $S^1$ (the image of the closed curve) is the boundary of each component, in particular of the bounded face.
Comment: I just read the Jordan Brouwer Separation Theorem, and I am sorry to be dense, but it still does not seem obvious.  Just because the embedded $S^1$ is the boundary of each component, it is still not at all clear that a homeomorphism of the bounded component extends to a homeomorphism on the closure of the bounded component.  Am I just missing something?
Comment: @TrevorRichard Don't worry : ). I take it you mean that by "bounded component" you are not including the boundary, correct? However, the Schoenflies Theorem entails that the *closure* of the bounded component is homeomorphic to $D^2$ (the closed disk). Bredon also mentions the theorem, and you can see it in his book.
Comment: I see, thank you, I will take a look at Bredon when I get the chance.  Thanks very much.


If $a_1 = 3$ and $a_{n+1}=a_n^2-2$, then $\frac{1}{a_1}+\frac{1}{a_1a_2}+\frac{1}{a_1 a_2 a_3}+\cdots = \frac{3-\sqrt{5}}{2}$

Question: Let $a_1=3$,and $a_{n+1}=a_n^2-2$ (for $n=1, 2, \cdots$). Show that
$$\frac{1}{a_1}+\frac{1}{a_1 a_2}+\frac{1}{a_1a_2a_3}+\cdots+\frac{1}{a_1a_2 \cdots a_n}+\cdots=\frac{3-\sqrt{5}}{2}.$$
My thought
In fact, it's natural to find the general term expression of $a_n$. Indeed, $a_n$ could be expressed explicitly as follows $$a_n=x^{2^{n-1}}+\frac{1}{x^{2^{n-1}}}~,$$ where $x$ is any of the two roots of the equation $x^2-3x+1=0$, i.e.  $x=\dfrac{3 \pm \sqrt{5}}{2},$ and $n=1,2,\cdots.$
It's simple to prove that by mathematical induction. Let $n=1$, then $$x^{2^{n-1}}+\dfrac{1}{x^{2^{n-1}}}=x+\dfrac{1}{x}=\dfrac{x^2+1}{x}=\dfrac{3x}{x}=3=a_1.$$Assume that $a_k=x^{2^{k-1}}+\dfrac{1}{x^{2^{k-1}}},$ then $$a_{k+1}=a_k^2-2=\left(x^{2^{k-1}}+\dfrac{1}{x^{2^{k-1}}}\right)^2-2=x^k+\frac{1}{x^k}+2-2=x^k+\frac{1}{k}.$$ Thus, the general term formula above of $a_n$ holds for any $n=1,2,\cdots.$ From this, we have have $$a_1=\frac{1+x^2}{x},a_2=\frac{1+x^4}{x^2},\cdots,a_n=\frac{1+x^{2^n}}{x^{2^{n-1}}}.$$ But can those offer some help to solve the problem?Besides,the general term expression is what someone told me, but he didn't tell me how to get this. Who can show me?
Another thought
Let $b_n=\dfrac{a_n-\sqrt{a_n^2-4}}{2}$, where $a_n>2$. Then \begin{align*}b_{n+1}&=\dfrac{a_{n+1}-\sqrt{a_{n+1}^2-4}}{2}=\dfrac{a_{n}^2-2-\sqrt{(a_{n}^2-2)^2-4}}{2}=\dfrac{a_{n}(a_n-\sqrt{a_n^2-4})-2}{2}=a_nb_{n}-1.&\end{align*}
Hence, $$b_n=\frac{1}{a_n}+\frac{b_{n+1}}{a_n}.$$Therefore,$$b_1=\frac{1}{a_1}+\frac{b_2}{a_1}=\frac{1}{a_1}+\frac{1}{a_1}\left(\frac{1}{a_2}+\frac{b_3}{a_2}\right)=\frac{1}{a_1}+\frac{1}{a_1a_2}+\frac{b_3}{a_1a_2}=\cdots$$
Expand like this repeatedly till infinitely. Then we have $$b_1=\dfrac{1}{a_1}+\dfrac{1}{a_1a_2}+\dfrac{1}{a_1 a_2 a_3}+\cdots.$$ It follows that $$\dfrac{1}{a_1}+\dfrac{1}{a_1a_2}+\dfrac{1}{a_1 a_2 a_3}+\cdots=b_1=\dfrac{3-\sqrt{5}}{2}.$$
Please correct me if I'm wrong!
Comment: Can you come up with a general formula for $a_n = f(n)$?
Comment: @mengdie1982: If you have a solution, you should provide it. Otherwise, how are we supposed to know if we have "a different one"? Besides, we don't want to waste time telling you things you already know.
Comment: @Arthur I think the OP put in the date as an act of professionalism?
Comment: In fact, I have one solution for this. But I hope to find a different one.
Comment: Funnily enough, $3-\sqrt{5}$ is the **Grafting Constant**. Go below for information about that (as a little fun fact) $\longrightarrow$ https://www.youtube.com/watch?v=hiOMtBrH8pc
Comment: @Blue Ok,I post it later.
Comment: @Matti P. Yes,I have got the general term. See above.
Answer: Notice that $a_1=3>2$. Suppose that $a_k>2$, then $a_{k+1}=a_k^2-2>2^2-2=2$. By mathematical induction, we have $a_n>2,$ further, $a_n^2>a_n+2$. Hence, $a_{n+1}=a_n^2-2>(a_n+2)-2=a_n.$ This shows that $a_n$ is an increasing integer sequence. Therefore, $a_n \to +\infty$ as $n \to \infty$.
Thus, we have $$\lim_{n \to \infty}\frac{\dfrac{1}{a_1 a_2 \cdots a_{n+1}}}{\dfrac{1}{a_1 a_2 \cdots a_{n}}}=\lim_{n \to \infty}\dfrac{1}{a_{n+1}}=0.$$ According to the ratio test of positive series, we have that  $\sum\limits_{n=1}^{\infty}\dfrac{1}{a_1a_2\cdots a_n}$ is convergent. Hence, let it be $\dfrac{a_1-\lambda}{2},$ where $\lambda$ is an unknown real number we need to find.
It's simple to find that $$\frac{a_2-\lambda a_1}{2}=\frac{1}{a_2}+\frac{1}{a_2a_3}+\cdots$$$$\frac{a_3-\lambda a_1a_2}{2}=\frac{1}{a_3}+\frac{1}{a_3a_4}+\cdots$$$$\vdots$$$$\frac{a_n-\lambda a_1a_2\cdots a_{n-1}}{2}=\frac{1}{a_n}+\frac{1}{a_na_{n+1}}+\cdots$$
Since $$0<\frac{1}{a_n}+\frac{1}{a_na_{n+1}}+\cdots <\frac{1}{a_n}+\frac{1}{a_n^2}+\cdots=\frac{1}{a_n-1},$$ hence $$0<\frac{a_n-\lambda a_1a_2\cdots a_{n-1}}{2}<\frac{1}{a_n-1}.$$
According to the Squeeze Theorem,$$\lim_{n \to \infty}\frac{a_n-\lambda a_1a_2\cdots a_{n-1}}{2}=0.$$ Thus, $$\lambda=\lim_{n \to \infty}\frac{a_n}{a_1a_2\cdots a_{n-1}}.$$
Moreover, from $a_{n+1}=a_n^2-2$, we have $$a_n^2-4=a_{n-1}^2(a_{n-2}^2-4)=\cdots=a_1^2a_2^2\cdots a_{n-1}^2(a_1^2-4).$$
Thus, $$\left(\frac{a_n}{a_1a_2\cdots a_{n-1}}\right)^2=\frac{4}{a_1^2a_2^2\cdots a_{n-1}^2}+(a_1^2-4).$$
Taking the limits as $n \to \infty$ of the both sides, we have $$ \lambda^2=0+5=5.$$ Then,$$\lambda=\sqrt{5}.$$ As a result, $$\frac{1}{a_1}+\frac{1}{a_1 a_2}+\frac{1}{a_1a_2a_3}+\cdots+\frac{1}{a_1a_2 \cdots a_n}+\cdots=\frac{3-\sqrt{5}}{2}.$$ This is exactly what we want to prove.
Comment: Please correct me if I'm wrong! @Blue


If $M \in [0,1)^{n \times n}$ has zero diagonal, is $I - M$ invertible?

Question: As the title states, if $M$ is a $n$ by $n$ matrix such that $M_{ii} = 0$ and $0 \leq M_{ij} < 1$ for $i \neq j$, is it always true that $I - M$ is invertible? I've tried some small examples, and they would suggest for this to be the case. Any hints?
Comment: @A.Pongrácz For any square matrix $\;A\;$ and any scalar $\;\lambda\;$, we have that $\;\lambda\;$ is an eigenvalue of $\;A\;$ iff $\;\det(xI-A)=0\iff xI-A\;$ is singular. This is just the definition of eigenvalue...
Comment: Your question is equivalent to ask whether $\;\lambda=1\;$ is an eigenvalue of the matrix, so...what do you think?
Answer: This is helpful:
https://en.wikipedia.org/wiki/Gershgorin_circle_theorem
You must find a matrix where the sum of the absolute values in the rows are big enough. In particular $2\times 2$ matrices will not provide a counterexample (OK, this is trivial anyway), and if you are looking for a $3\times 3$ counterexample, you need to have the sum of absolute values in some row outside the diagonal to be at least 1.
This is what I found:
$$M= \begin{pmatrix} 0 & \frac{1}{2} & \frac{1}{2}\\  \frac{1}{2} & 0 & \frac{1}{2} \\ \frac{1}{2} & \frac{1}{2} & 0 \end{pmatrix}$$
Can you see that $I-M$ is not invertible?
Comment: You are welcome. But also see the comment of @DonAntonio, that is a good insight, too.
Comment: Awesome! Thanks for the quick response. This is quite helpful :)


Why does fgetc() in C always reads extra, non-existent characters whenever I try to read non-printable characters from txt files?

Question: I am trying to read non-printable characters from a text file, print out the characters' ASCII code, and finally write these non-printable characters into an output file.
However, I have noticed that for every non-printable character I read, there is always an extra non-printable character existing in front of what I really want to read.
For example, the character I want to read is "§".
And when I print out its ASCII code in my program, instead of printing just "167", it prints out "194 167".
I looked it up in the debugger and saw "§" in the char array. But I don't have  anywhere in my input file.
screenshot of debugger
And after I write the non-printable character into my output file, I have noticed that it is also just "§", not "§".
There is an extra character being attached to every single non-printable character I read. Why is this happening? How do I get rid of it?
Thanks!
Code as follows:
        case 1:
            mode = 1;
            FILE *fp;
            fp = fopen ("input2.txt", "r");
            int charCount = 0;

            while(!feof(fp)) {
                original_message[charCount] = fgetc(fp);
                charCount++;
            }
            original_message[charCount - 1] = '\0';
            fclose(fp);

            k = strlen(original_message);//split the original message into k input symbols
            printf("k: \n%lld\n", k);

            printf("ASCII code:\n");
            for (int i = 0; i < k; i++)
            {
                ASCII = original_message[i];
                printf("%d ", ASCII);
            }

Comment: `§` is not ascii character, it is unicode
Comment: Use a hex editor to view the text file. I bet it's really two bytes on disk. Whatever program you used to generate the text file is using UTF-8 encoding, and in that encoding, the `§` character is two bytes long. You seem to be expecting ISO/IEC 8859-1 encoding (where `§` is a single byte). Either adapt your program to translate UTF-8 to ISO/IEC 8859-1 or convince the program that is generating the text file to use ISO/IEC 8859-1. Your main confusion is calling `§` "ASCII". It is not ASCII. ASCII stops at 127.
Comment: You're using `feof` incorrectly: https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong
Comment: "worst choice"? As opposed to what? Apple Pascal? C is no better or worse than any other language at handling Unicode. As it is, the biggest, most prolific library for handling Unicode is written in C: ICU4C.
Comment: Looks like the file you're reading is UTF-8. The C language was created back in the ancient days of 8-bit character sets and is the worst choice for reading files that contain Unicode.
Comment: `§` is not a "non-printing character"; it is a non-*ASCII* character.  If your system were using a single-byte extended character set like [ISO-8859-1](https://en.wikipedia.org/wiki/ISO/IEC_8859-1), you could read `§` as one byte (it'd be 167).  But it looks like your system is using [Unicode](https://en.wikipedia.org/wiki/Unicode), in its multibyte rendition [UTF-8](https://en.wikipedia.org/wiki/UTF-8).
Comment: Thanks for all the replies. Is there any way I can print out the Unicode string of §? for non-ASCII, how can I print something like 0x265e instead of decimal 9822? Sorry if I sound dumb
Comment: To print an integer value in hexadecimal, just use `%x` instead of `%d`.
Comment: @LeeDanielCrocker: You'd be surprised how few programming languages *actually* understand Unicode even half as well as they claim they do.
Answer: C's getchar (and getc and fgetc) functions are designed to read individual bytes.  They won't directly handle "wide" or "multibyte" characters such as occur in the UTF-8 encoding of Unicode.
But there are other functions which are specifically designed to deal with those extended characters.  In particular, if you wish, you can replace your call to fgetc(fp) with fgetwc(fp), and then you should be able to start reading characters like § as themselves.
You will have to #include <wchar.h> to get the prototype for fgetwc.  And you may have to add the call
setlocale(LC_CTYPE, "");

at the top of your program to synchronize your program's character set "locale" with that of your operating system.
Not your original code, but I wrote this little program:
#include <stdio.h>
#include <wchar.h>
#include <locale.h>

int main()
{
    wchar_t c;
    setlocale(LC_CTYPE, "");
    while((c = fgetwc(stdin)) != EOF)
        printf("%lc %d\n", c, c);
}

When I type "A", it prints A 65.
When I type "§", it prints § 167.
When I type "Ƶ", it prints Ƶ 437.
When I type "†", it prints † 8224.
Now, with all that said, reading wide characters using functions like fgetwc isn't the only or necessarily even the best way of dealing with extended characters.  In your case, it carries a number of additional consequences:

Your original_message array is going to have to be an array of wchar_t, not an array of char.
Your original_message array isn't going to be an ordinary C string — it's a "wide character string".  So you can't call strlen on it; you're going to have to call wcslen.
Similarly, you can't print it using %s, or its characters using %c.  You'll have to remember to use %ls or %lc.

So although you can convert your entire program to use "wide" strings and "w" functions everywhere, it's a ton of work.  In many cases, and despite anomalies like the one you asked about, it's much easier to use UTF-8 everywhere, since it tends to Just Work.  In particular, as long as you don't have to pick a string apart and work with its individual characters, or compute the on-screen display length of a string (in "characters") using strlen, you can just use plain C strings everywhere, and let the magic of UTF-8 sequences take care of any non-ASCII characters your users happen to enter.
Comment: Hello, thank you for the answer. I am just wondering, 'cause I do need to split the string into their characters, then how would I deal with them? For example, if I need to read Korean characters from a txt file, write these Korean characters into a char array one by one, and deal with each character separately somewhere else in my function. Finally, write these Korean characters into another txt file one by one, what would be a fast and easy way? Thanks!
Comment: @Yooshinhee Another excellent function to know about is [`mbtowc`](https://linux.die.net/man/3/mbtowc), and the related [`mbstowcs`](https://linux.die.net/man/3/mbstowcs).  These let you extract one or more "wide" Unicode characters from a multibyte string.  You might also find some tips at [this question](https://stackoverflow.com/questions/4607413/), although it's talking about converting in the opposite direction.


Use NSUserDefaults to change bundle display name?

Question: is it possible to use NSUserDefaults to store a Boolean value, and if this value is equal to "YES", then to change the BUNDLE DISPLAY NAME? Thanks for your help!
Answer: No, you can't change the BUNDLE DISPLAY NAME from within your app.  You must manually change the plist yourself.
Comment: Oh well, I was hoping this was possible. I want to bundle a lite and full version together, and if the user completes an in app purchase, it unlocks the content and takes "Free" out of the bundle display name. Thanks for your help!
Comment: Unfortunately Apple doesn't play nicely with these types of things :(.  They don't like having these upgrades be in-app purchases.


Explain excel formula in PRD

Question: I have an excel template which needs to be automated by the developer using JAVA, the problem here is that the developer is not well versed with excel and want all excel formula in detail in PRD document.
It would be great if anyone can guide me here to how to explain excel formula most effectively in PRD document or is there any other better option to explain all the details in excel as well.
Comment: Please add more details on what the relationship is here between Java and Excel.  If the developer is already controlling some of the worksheet from Java, then perhaps he should be the one who owns the formulas.
Comment: @TimBiegeleisen: The developer needs to automate the excel template on the dashboard using JAVA, and he needs to replicate all the excel formulas at backend.
Comment: Just give him the mathematical formula for the task and let them program it from scratch.
Comment: @SolarMike: How can i explain this formula `=IFERROR(IF(OR(C4>D4,C4>0),(D4-C4)/C4,-(D4-C4)/C4)," ")` in mathematical or programming terms.
Comment: What is the variable in cell C4? what is the variable in cell D4? So if D4 is Revenue and C4 is cost, then you could well say if the cost exceeds the revenue then revenue-Cost which is profit / cost etc, but without knowing exactly what you are achieving my suggestion stands.
Comment: @SolarMike: Suppose Its revenue in `C4` for previous year and in `D4` for current year.
Comment: So, how would you explain those values in accounting terms...
Comment: @SolarMike: I would explain it as a growth.
Comment: Only if current year is better than last year...
Comment: @SolarMike: Yes i guess
Answer: There are very many examples (though a minority!) here on SO of how to "explain" an Excel formula. The essence of the process is:

work from the inside out
apply Evaluate Formula (from the Formula Auditing tab)
refer to https://support.office.com for details function by function

For presentation judicious use of Alt+Enter can be very helpful where formulae are complex - to insert line breaks to split logical components.
(The above are also the main steps in debugging issues with a formula, though for that some overwriting of data is also often very helpful - so reliance is not on what seems to be the data but what is known to be, particularly for format, precision and spaces.)

Explain excel formula in PRD


Como calcular o percentual de itens realizados em uma árvore de dados no formato de lista?

Question: Existe a seguinte lista:
[
    [0, False],
    [1, True],
    [1, False],
    [2, False],
    [2, True],
    [2, False],
    [3, False],
    [3, True],
    [2, False],
    [1, False],
    [2, False]
]

Esta lista forma a seguinte árvore:

Como podem observar, a lista respeita a ordem que diz respeito a ramificação de cada item, logo numa ordem como (exemplo) 1, 2, 3, 2, 1 diz que a primeira ocorrência 2 pertence ao primeiro 1, e o 3 pertence ao primeiro 2, já a segunda ocorrência do 2 pertence ao primeiro 1, e o último 1 não possui ramificação.
Não consegui resolver esse problema, achei que pudesse usar recursividade, mas os itens da lista estão ordenados, cada próximo item da lista pode se relacionar com os anteriores. Bom, não sei como resolver, o resultado esperado é saber quantos porcentos dessa árvore foi resolvido. Nesse exemplo que citei o resultado calculado deu 45,83% da arvore resolvida.
Explicação da árvore da questão:
A ramificação de nível 3 está com 50% resolvida (um True e outro False), ela pertence a um ramo do nível 2, logo esse ramo tem valor de 50%. Esses quatro ramos de nível 2 tem um total de (0% + 100% + 50%+ 0%) que dividido por 4 é igual a 37,5%. Então existe no nível 1 um ramo de 100% outro de 37,5% e outro de 0%, que divido por três da 45,83%
Como resolver isso em Python?
Comment: O que significa estar "resolvido"?
Comment: @JuanLopes resolvido é quando está `True`
Comment: Nenhuma fração de denominador 11 (o número de nós na árvore)  arredonda para 45,83%. Você poderia explicar o resultado, por favor?
Comment: @JuanLopes creio que a explicação está bem clara. A ramificação de nível 3 está com 50% resolvida (um `True` e outro `False`), ela pertence a um ramo do nível 2, logo esse ramo tem valor de 50%. Esses quatro ramos de nível 2 tem um total de (0% + 100% + 50%+ 0%) que dividido por 4 é igual a 37,5%. Então existe no nível 1 um ramo de 100% outro de 37,5% e outro de 0%, que divido por três da 45,83%.
Comment: Não tinha ficado clara. A interpretação que tinha dado inicialmente era "qual o percentual de nós está resolvido?", e não "qual o percentual de sub-árvores está resolvido, recursivamente?". Mas agora entendi. Só acho que isso deveria estar no corpo da pergunta.
Comment: Interessante notar que, a julgar pela semântica, cada nó da árvore seria melhor representado por uma tupla do que por uma lista.
Answer: Python é uma linguagem legal por que não costuma ficar entre "você e o problema" - nesse caso, acho que levei mais tempo para entender como você chegou nesse 45.83% do que para pensar numa forma de resolver a questão.
Bom, é necessário representar para o computador cada elemento da lista com as propriedades que ele tem - no caso, cada elemento tem uma lista de outros elementos dependentes de si e uma % de quanto está resolvido. Se o elemento tem "filhos" essa porcentagem de quanto está resolvido é igual a da lista de filhos - senão, é dada pelo valor na sua lista.
Essa representação da lista é uma forma mínima de dar toda a informação necessária, mas não ajuda a resolver o problema - precisamos sim de uma classe Nó que tem as duas propriedades que eu citei: coeficente de quanto está completo, e lista de filhos - e  a partir da sua lista dada criamos essa árvore - podemos ter o requinte de usar o decorator "property" do Python para o coeficiente de quanto está completo - isso faz com que a leitura de um coeficiente de completo  seja na verdade a chamada de uma função que calcula o valor em tempo real.
class Node(object):
    def __init__(self, completeness=0):
        self._completeness =  float(completeness)
        self.children = []

    def add_child(self, child):
        self.children.append(child)

    @property
    def completeness(self):
        if self._completeness or not self.children:
            return self._completeness
        return sum(child.completeness for child in self.children) / len(self.children)

(Se não conhecer a sintaxe que usei na última linha -de generator expression, vale a pena conferir a documentação: https://www.python.org/dev/peps/pep-0289 - esse código também tira proveito do valor numérico do "True" em Python ser "1", por razões históricas  - se não fosse isso, seria necessário mais um "if")
Bom -essa é a classe como foi descrita anteriormente - só que para ela descrever o problema é necessário criar uma árvore com nós desta classe a partir da sua lista de entrada - isso pode ser feito com mais uma função -
ela é complicadinha, mas perceba pelos comentários que é exatamente comoteriamos que proceder se estivessemos cosntruindo essa árvore "em papel", desenhando cada nó  a medida que o processacemos a partir da lista de entrada:
def build_tree(source):
    # transforma a lista num iterador:
    # isso permite que tomemos o primeiro elemento com a função "next"
    # e guardemos os demais elementos para serem consumidos pelo "for" abaixo.
    source = iter(source)
    # consome o primeiro nó na lista, criando a raiz da árvore)
    level, completeness = next(source)
    root = Node(completeness)
    # lista temporária que permite subir para os nós superiores
    # quando cada ramo for preenchido:
    tree_stack = [(level, root)]
    for level, completeness in source:
        new_node = Node(completeness)

        # se estamos de volta num nó pelo menos um nível acima do anterior -  remover
        # elementos da lista temporária - o nó que ficar por último
        # nessa lista será o último nó inserido com nível acima do
        # atual (portanto, o pai do atual)
        while tree_stack[-1][0] > level:
            tree_stack.pop()
        previous_level = tree_stack[-1][0]

        if level == previous_level:
            # o mesmo nível do último nó inserido -
            # inserir o novo nó como irmão do último
            tree_stack[-2][1].add_child(new_node)
            # remover o irmão do nó atual da lista temporária -
            # de forma que o penultimo elemento seja o sempre o
            # pai de outros nós no nível atual
            tree_stack.pop()
        elif level > previous_level:
            #colocar o novo nó como filho do último nó criado
            tree_stack[-1][1].add_child(new_node)
        tree_stack.append((level, new_node))
    return root

E, de forma que o programa rode com seus dados de exemplo, quando for invocado como "stand alone"  podemos adicionar esta parte - (uso a própria formatação de strings do Python para exibir o valor do coeficiente de completude como porcentagem):
if __name__ == "__main__":
    data = [
    [0, False],
    [1, True],
    [1, False],
    [2, False],
    [2, True],
    [2, False],
    [3, False],
    [3, True],
    [2, False],
    [1, False],
    [2, False]
]
    tree = build_tree(data)
    print ("A porcentagem de completude da árvore é {:.02%}".format(tree.completeness)

Comment: sim, se você só precisa desse número e mais nada, a resposta dele deve ser a aceita.
Comment: Apesar de solucionar o meu problema, achei a solução de Juan mais simples, não sei em relação a perfomance qual se sai melhor, de qualquer forma obrigado!
Comment: Não se trata de performance - esta é a solução para montar a árvore em Python e fazer operações nela. aA outra resposta dá um jeito de fazer o cálculo usando a representação da árvore do jeito que chega para você, sem ter que montar uma estrutura de dados genérica.

Se é um problema de maratona, ou de escola - a outra resposta é a "desejada" - pois chegou num algoritimo bom para fazer as manipulações para chegar no número desejado. Se for parte de um problema do mundo real - a abordagem de montar os objetos reais e ter um sistema mantível é mais importante.
Comment: Isso não é uma questão de faculdade, entendo seu ponto de vista, no entanto o problema em questão é apenas para calcular o percentual da árvore e imprimir o valor, depois disso os dados não são mais reutilizados, por isso a solução de Juan foi mais interessante no meu caso. De qualquer forma valeu!
Answer: Você pode navegar pela árvore implicitamente calculando o total resolvido pelos filhos de cada nó, assim:
def complete(tree, i, level):
    first = i
    siblings = []
    while i < len(tree) and tree[i][0] == level:
        count, value = complete(tree, i+1, level+1)
        siblings.append(max(int(tree[i][1]), value))
        i += count + 1

    return (i - first, float(sum(siblings))/len(siblings or [0]))

L = [
    [0, False],
    [1, True],
    [1, False],
    [2, False],
    [2, True],
    [2, False],
    [3, False],
    [3, True],
    [2, False],
    [1, False],
    [2, False]
]

print complete(L, 0, 0)


How can I reuse a property within application.properties?

Question: I want to reuse a Spring property in application.properties.
For example I have the following application.properties:
spring.data.mongodb.database=my_database
org.jobrunr.database.databaseName=my_database

How can I reuse the value (my_database) of the property (spring.data.mongodb.database) for the other property (org.jobrunr.database.databaseName) , so I only have to specify the database name at one place.
Comment: Define which one you want to use and replace the other with `${spring.data.mongodb.database}` (or vice-versa). Or specify a dedicated property (`my.databaseName`) and replace both with `${my.databaseName}`.
Answer: Answer
Such as M.Deinum said :
my.database.name=my_database

spring.data.mongodb.database=${my.database.name}
org.jobrunr.database.databaseName=${my.database.name}

You can now use the property ${my.database.name} wherever you need the value my_database.

Let us know how it goes! :)


Black Scholes Merton PDE with a time variant boundary condition

Question: In a research project I need to solve the following PDE with the boundary conditions:
$rS(V,t)=c-\frac{\partial S(V,t)}{\partial t}+\delta V \frac{\partial S(V,t)}{\partial V}+\frac{1}{2} \sigma_h^2 V^2 \frac{\partial^2 S(V,t)}{\partial V^2}$
where you can assume $S(V,t)$ is the price of the option and $V$ is the price of the underlying asset and $t$ is time.
with boundary conditions:
$S(V_s,t)=f(t)$
where $V_s$ is a constant.
I would be happy if there is a solution to solve this for arbitrary $f$, but if it helps, $f(t)=D(V_s,t)$ where $D(V,t)$ is the solution of an other similiar PDE :
$rD(V,t)=c-\frac{\partial D(V,t)}{\partial t}+\delta V \frac{\partial D(V,t)}{\partial V}+\frac{1}{2} \sigma^2_l V^2 \frac{\partial^2 D(V,t)}{\partial V^2}$
which has a different $\sigma$ than the first PDE.
with the following boundary condition: $D(V_B,V_B)=T$ where $T$ is an arbitrary constant. and $D(V,0)=p$ for all $V \gt V_B$
In fact I am facing a system of two PDE with boundary conditions, I think I know how to solve the second one (since its boundary condition is constant) but I have no idea about the first one.
I would really appreciate any help or suggestions
Regards
Comment: A few questions: Is there a relationship between $r$, $\delta$ and $\sigma$? Are all constants positive? One bigger than the other, etc? What's the domain for $V$? What's the behavior you're expecting for $S$ as the price $V$ goes to infinity?
Answer: Case $1$: $r\neq0$
Let $S(V,t)=S_c(V,t)+\dfrac{c}{r}$ ,
Then $\dfrac{\partial S(V,t)}{\partial t}=\dfrac{\partial S_c(V,t)}{\partial t}$
$\dfrac{\partial S(V,t)}{\partial V}=\dfrac{\partial S_c(V,t)}{\partial V}$
$\dfrac{\partial^2S(V,t)}{\partial V^2}=\dfrac{\partial^2S_c(V,t)}{\partial V^2}$
$\therefore r\left(S_c(V,t)+\dfrac{c}{r}\right)=c-\dfrac{\partial S_c(V,t)}{\partial t}+\delta V\dfrac{\partial S_c(V,t)}{\partial V}+\dfrac{1}{2}\sigma_h^2V^2\dfrac{\partial^2S_c(V,t)}{\partial V^2}$
$rS_c(V,t)+c=c-\dfrac{\partial S_c(V,t)}{\partial t}+\delta V\dfrac{\partial S_c(V,t)}{\partial V}+\dfrac{1}{2}\sigma_h^2V^2\dfrac{\partial^2S_c(V,t)}{\partial V^2}$
$\dfrac{\partial S_c(V,t)}{\partial t}=\dfrac{1}{2}\sigma_h^2V^2\dfrac{\partial^2S_c(V,t)}{\partial V^2}+\delta V\dfrac{\partial S_c(V,t)}{\partial V}-rS_c(V,t)$
Of course we use separation of variables (similar to Black-Scholes PDE with non-standard boundary conditions):
Let $S_c(V,t)=P(V)Q(t)$ ,
Then $P(V)Q'(t)=\dfrac{1}{2}\sigma_h^2V^2P''(V)Q(t)+\delta VP'(V)Q(t)-rP(V)Q(t)$
$P(V)Q'(t)=\dfrac{\sigma_h^2Q(t)}{2}\biggl(V^2P''(V)+\dfrac{2\delta}{\sigma_h^2}VP'(V)-\dfrac{2r}{\sigma_h^2}P(V)\biggr)$
$\dfrac{2Q'(t)}{\sigma_h^2Q(t)}=\dfrac{V^2P''(V)+\dfrac{2\delta}{\sigma_h^2}VP'(V)-\dfrac{2r}{\sigma_h^2}P(V)}{P(V)}=-s^2-\dfrac{1}{4}\biggl(\dfrac{2\delta}{\sigma_h^2}-1\biggr)^2-\dfrac{2r}{\sigma_h^2}$
$\begin{cases}\dfrac{Q'(t)}{Q(t)}=-\dfrac{\sigma_h^2s^2}{2}-\dfrac{\sigma_h^2}{8}\biggl(\dfrac{2\delta}{\sigma_h^2}-1\biggr)^2-r\\V^2P''(V)+\dfrac{2\delta}{\sigma_h^2}VP'(V)+\biggl(s^2+\dfrac{1}{4}\biggl(\dfrac{2\delta}{\sigma_h^2}-1\biggr)^2\biggr)P(V)=0\end{cases}$
$\begin{cases}Q(t)=c_3(s^2)e^{-t\Bigl(\frac{\sigma_h^2s^2}{2}+\frac{\sigma_h^2}{8}\bigl(\frac{2\delta}{\sigma_h^2}-1\bigr)^2+r\Bigr)}\\P(V)=\begin{cases}c_1(s^2)V^{\frac{1}{2}-\frac{\delta}{\sigma_h^2}}\sin((\ln V-\ln V_s)s)+c_2(s^2)V^{\frac{1}{2}-\frac{\delta}{\sigma_h^2}}\cos((\ln V-\ln V_s)s)&\text{when}~s\neq0\\c_1V^{\frac{1}{2}-\frac{\delta}{\sigma_h^2}}\ln V+c_2V^{\frac{1}{2}-\frac{\delta}{\sigma_h^2}}&\text{when}~s=0\end{cases}\end{cases}$
$\therefore S(V,t)=\int_0^\infty C_1(s^2)V^{\frac{1}{2}-\frac{\delta}{\sigma_h^2}}e^{-t\Bigl(\frac{\sigma_h^2s^2}{2}+\frac{\sigma_h^2}{8}\bigl(\frac{2\delta}{\sigma_h^2}-1\bigr)^2+r\Bigr)}\sin((\ln V-\ln V_s)s)~ds+\int_0^\infty C_2(s^2)V^{\frac{1}{2}-\frac{\delta}{\sigma_h^2}}e^{-t\Bigl(\frac{\sigma_h^2s^2}{2}+\frac{\sigma_h^2}{8}\bigl(\frac{2\delta}{\sigma_h^2}-1\bigr)^2+r\Bigr)}\cos((\ln V-\ln V_s)s)~ds+\dfrac{c}{r}$
$S(V_s,t)=f(t)$ :
$\int_0^\infty C_2(s^2)V_s^{\frac{1}{2}-\frac{\delta}{\sigma_h^2}}e^{-t\Bigl(\frac{\sigma_h^2s^2}{2}+\frac{\sigma_h^2}{8}\bigl(\frac{2\delta}{\sigma_h^2}-1\bigr)^2+r\Bigr)}~ds+\dfrac{c}{r}=f(t)$
$V_s^{\frac{1}{2}-\frac{\delta}{\sigma_h^2}}e^{-\Bigl(\frac{\sigma_h^2}{8}\bigl(\frac{2\delta}{\sigma_h^2}-1\bigr)^2+r\Bigr)t}\int_0^\infty C_2(s^2)e^{-\frac{\sigma_h^2ts^2}{2}}~ds=f(t)-\dfrac{c}{r}$
$\int_0^\infty\dfrac{C_2(s^2)e^{-\frac{\sigma_h^2ts^2}{2}}}{2s}d(s^2)=\left(f(t)-\dfrac{c}{r}\right)V_s^{\frac{\delta}{\sigma_h^2}-\frac{1}{2}}e^{\Bigl(\frac{\sigma_h^2}{8}\bigl(\frac{2\delta}{\sigma_h^2}-1\bigr)^2+r\Bigr)t}$
$\int_0^\infty\dfrac{C_2(s)e^{-\frac{\sigma_h^2ts}{2}}}{2\sqrt{s}}ds=\left(f(t)-\dfrac{c}{r}\right)V_s^{\frac{\delta}{\sigma_h^2}-\frac{1}{2}}e^{\Bigl(\frac{\sigma_h^2}{8}\bigl(\frac{2\delta}{\sigma_h^2}-1\bigr)^2+r\Bigr)t}$
$\mathcal{L}_{s\to\frac{\sigma_h^2t}{2}}\left\{\dfrac{C_2(s)}{2\sqrt{s}}\right\}=\left(f(t)-\dfrac{c}{r}\right)V_s^{\frac{\delta}{\sigma_h^2}-\frac{1}{2}}e^{\Bigl(\frac{\sigma_h^2}{8}\bigl(\frac{2\delta}{\sigma_h^2}-1\bigr)^2+r\Bigr)t}$
$C_2(s)=2V_s^{\frac{\delta}{\sigma_h^2}-\frac{1}{2}}\sqrt{s}\mathcal{L}^{-1}_{\frac{\sigma_h^2t}{2}\to s}\left\{f(t)e^{\Bigl(\frac{\sigma_h^2}{8}\bigl(\frac{2\delta}{\sigma_h^2}-1\bigr)^2+r\Bigr)t}\right\}-\dfrac{2c}{r}V_s^{\frac{\delta}{\sigma_h^2}-\frac{1}{2}}\sqrt{s}\delta\biggl(s+\dfrac{1}{4}\biggl(\dfrac{2\delta}{\sigma_h^2}-1\biggr)^2+\dfrac{2r}{\sigma_h^2}\biggr)$
Answer: Since the problem is linear, I'm going to split the problem in two:
$$
S_t - \frac{\sigma^2}{2}v^2 S_{vv} - \delta v S_v + r S = 0, \qquad S(v_s,t) = f(t) \tag{1}
$$
and
$$
S_t - \frac{\sigma^2}{2}v^2 S_{vv} - \delta v S_v + r S = c, \qquad S(v_s,t) = 0. \tag{2}
$$
For (2), let $S(t,v) = S(v)$, then
$$
-\frac{\sigma^2}{2}v^2 S'' - \delta v S' + r S = c, \qquad S(v_s) = 0.
$$
One would solve this equation by proposing $S(t,v) = v^\alpha$, determining $\alpha$ with the inditial equation
$$
\alpha^2 + \left(\frac{2\delta}{\sigma^2} - 1\right)\alpha - \frac{2 r}{\sigma^2} = 0,
$$
and then the Green's function. A problem can be seen here: we are missing a boundary condition. My guess is that as the price of the asset grows, the price of the option diminishes; in other words, $S(t,v \to \infty) \to 0$.
The interesting problem is (1). As @doraemonpaul points out, we can use separation of variables $S(t,v) = T(t) V(v)$, and then
\begin{align}
T' + (r + k) T &= 0 \\
\\
\frac{\sigma^2}{2}v^2 V'' + \delta v V' + k V &= 0
\end{align}
where I've used $k$ as a separation constant.
The first equation has as solution
$$
T_k(t) = e^{-(r + k)t}
$$
while the second
$$
V_k(v) = c_1(k) v^{m_-(k)} + c_2(k)v^{m_+(k)},
$$
where
$$
m_{1,2}(k) = \frac{1}{2} - \frac{\delta}{\sigma^2} \pm \frac{1}{2}\sqrt{\left(1- \frac{2 \delta}{\sigma^2}\right)^2 - \frac{8 \delta k}{\sigma^2}}.
$$
To deremine the values of $k$ where both solutions are valid, one most be very careful. For instance, if $1-\frac{2\delta}{\sigma^2} \ge 0$, the only way for a bounded solution to exist is that
$$
-r < k < 0.
$$
In this case,
$$
S(t,v) = \int_{-r}^0 c_1(k) e^{-(r+k)t} v^{m_-(k)} d k = \int_0^r c_1(s-r) e^{-s t} v^{m_-(s-r)}ds.
$$
Evaluating the boundary condition
$$
f(t) = \int_0^\infty e^{-s t} C_1(s) ds,
$$
where
$$
C_1(s) = v^{m_-(s-r)}  c_1(s-r) H(r-s)
$$
and $H(x)$ is the Heaviside step function. In this way, we can see that $C_1(s)$ is the Inverse Laplace transform of $f(t)$, and the solution is fully determined.
For $1-\frac{2\delta}{\sigma^2} \le 0$, the condition $S \ge 0$ will restrict $k$ in a similar way, and we will be able to construct the solution.


Can I freely drag-resize events to be arbitrary lengths in fullCalendar agenda view

Question: I want to display an agendaDay view with hour spaced slots. However I also want to events that are arbitrary lengths. If something takes an hour and 5 minutes then I want it to display as an hour and 5 minutes. At the minute drag resizing snaps to the next available slot.
how can I disable this snap drag behaviour and allow users to set events of arbitrary length?
This doesn't seem to be that unusual a use case to me, how have other people solved this?

Things I've tried:
Setting the slotMinutes to a low value such as 5. This helps with resizing but also makes the default event length 5 minutes. Also it takes up alot of space. I tried reducing the height of the slots to 1px which works to an extent but the drag action becomes untethered from the timescale. Also the calculation of the clicked time becomes wildly inaccurate.
Answer: I don't know of a programmatic solution, but I think this is a problem best solved by a second edit screen for the event.
Take a look at Google Calendar, you drag events to the nearest size (often the divisions work out well for most events) ... and then you edit the event giving a specific start/end time on a second page.
Other than that ... when you say arbitrary length, you mean 1 minute precision I assume - so then you essentially need slots of 1 minute. Not sure how cumbersome that will be for the user. You could have 1 min slots and then only display the time on the left hand side every half hour. Not sure where in the code this would be, but try having a look in /src/agenda/AgendaView.js


How to test an asynchronous function using karma/Jasmine in ionic2?

Question: Below I have written down the code in which there is an asynchronous function, that uses setTimeout() internally and prints message after 3seconds.
I have to write the spec using Jasmine.
I have followed the docs but I didn't get how to apply this in the code.
home.ts
<code>//implementing only function written in a class.All imports are done properly.

click(){

function delayedAlert(message: string, time: number, cb) {
      return setTimeout(() => cb(message), time);
    }
    delayedAlert('Aditya3', 3000, (message) => console.log(message));//function is called
  }
}
</code>
home.spec.ts
<code>describe('Asynchronous call', () => {
    let fixture: ComponentFixture<HomePage>;
    let comp: HomePage;
    let de: DebugElement;
    let el: HTMLElement;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [HomePage],
            imports: [
                IonicModule.forRoot(HomePage),
            ],
            providers: [NavController],
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(HomePage);
        comp = fixture.componentInstance;
        de = fixture.debugElement

    });

it('Asynchronous testing with callback', ()=>{
         //how to write the spec here for the asynchronous function wrriten in the above class using Karma/Jasmine.
})
});
</code>
In the comments marked in the test spec, I need to write the spec.
Answer: Use the done() method. Check this out.
http://www.htmlgoodies.com/html5/javascript/using-the-done-method-in-your-jasmine-driven-asynchronous-javascript-tests.html
Comment: In this article jasmine.async lib, in which they are using async.it etc, Can you help me to write this spec without using jasmine.async lib?
Comment: I am unable to implement it.can you help?


I got error while deploying my app on heroku

Question: Hey guys i got stuck in that error i did all the steps right but it still not work,my deploy failed after all this is the error i got, please help me i want to deploy my app for demonstration purposes i tried to reinstall my heroku cli and that does not work too
here are the logs
what i got on the browser when i try to open the app
Comment: Did you check this answer https://stackoverflow.com/a/34637534/6392696
Answer: Your app crashed and the logs do not show the real error, so you should SSH on the dyno to read the logs (they gave the path).
It's doable with the CLI: https://devcenter.heroku.com/articles/exec
Comment: yes exactly i don't see where is the error i'll check the link thanks
Answer: What type of error you are facing. If this is about deploying and git push etc then tell me about the error.Please specify your problem.
Comment: Yes i got this after i did the commands to deploy my app it seems every thing is right to me but the deploy field


Force Windows to recalculate disk size on VM after resizing hard drive

Question: Is there a command line or similar that I can run to force Windows to recalculate disk size on a VM after resizing the hard drive?
Answer: Yes there is!

Start CMD in an elevated prompt
Run 'diskpart'
Run 'Rescan Devices'
Run LIST VOLUMES to get the list of volumes
Run SELECT VOLUME #, where # is the number of the volume needing expansion
Run EXTEND to expand the volume into the newly visible free space

We use this procedure for volume extensions on physical servers as well, when the volumes are on a SAN.
Comment: BTW on 2008 or Win7, you can do it all from Disk Management - There's an 'extend' option on the context menu for the partition, after you've rescanned. Also, on 2008 and Win7, you can do this on boot volumes. On versions prior, you need to use a GParted LiveCD to resize the partition.
Comment: One of the two, and I always seem to guess wrong! Thanks.
Comment: Thank you.  This worked for me.  I only had to change EXPAND to EXTEND and it worked like a charm.
Comment: That's good to know Chris, thanks.  For my particular case I need to script this so this answer was just what I needed.


Java import com.sun.prism.Graphics

Question: enter image description hereDoes anyone know, how to solve the import com.sun.prism.Graphics problem? It says to me, that the import is not accessible.- I coded this according to the tutorial... And Java also advices me to add this command. But when I add it, Java says that its not accessible.
(Basic game tutorial)
Comment: `com.sun` in internal. Don't use.
Comment: what tutorial was that?
Comment: *"Basic Java Game turorial."* Provide a link to it! Tip: Add @Simons0n (or whoever, the `@` is important) to *notify* the person of a new comment. *"what was the problem?"* The problem is that those classes in the `com.sun` package hierarchy are *'subject to change without notice'* and should not be used directly. Any tutorial which uses them is ***highly suspect*** and itself, should not be used.
Comment: Basic Java Game turorial. Im just beggining.
Andreas Java.awt.Graphics has worked. Thank you very much. And can I ask you, what was the problem?
Answer: This is internal class of particular JRE implementation. It is not part of Java Language Soecification. The tutorial you are using is bad in this sense.
If you really want to implement graphics with Java, consider Java FX.
Comment: Java FX? Well Because I ve started just few days ago, I am not really sure what to do. I wanted to learn begins and then start codding android apps.. Im still not sure yet.  But thanks for advice!
Comment: @Miky537: If you plan to work on Android apps, then Java FX is not the best choice. I'd suggest you search for an Android tutorial and start with it. Sorry I don't want to discourage you. But if you start from the right thing now, you will save much time :)
Comment: Im grateful for every advice. Ive tried many possiblities. (and it seems, ill try another one :D) Thanks for help!

Java import com.sun.prism.Graphics


Is smart hosting to an A record a violation of RFC-5321 section 1?

Question: I have a sendmail server configured to smarthost to a downstream resource.  The configuration is currently:
define(`SMART_HOST',`relay:[vip.example.local]')dnl

Since it's sending the A record for vip.example.local.  I've been told that this is a violation of IETF RFC-5321 section 5.1 which states:

Once an SMTP client lexically identifies a domain to which mail will
  be delivered for processing (as described in Sections 2.3.5 and 3.6),
  a DNS lookup MUST be performed to resolve the domain name (RFC 1035
  [2]).  The names are expected to be fully-qualified domain names
  (FQDNs): mechanisms for inferring FQDNs from partial names or local
  aliases are outside of this specification.  Due to a history of
  problems, SMTP servers used for initial submission of messages SHOULD
  NOT make such inferences (Message Submission Servers [18] have
  somewhat more flexibility) and intermediate (relay) SMTP servers MUST
  NOT make them.
The lookup first attempts to locate an MX record associated with
  the    name.  If a CNAME record is found, the resulting name is
  processed as    if it were the initial name.  If a non-existent domain
  error is    returned, this situation MUST be reported as an error.  If
  a    temporary error is returned, the message MUST be queued and
  retried    later (see Section 22.214.171.124).  If an empty list of MXs is
  returned,    the address is treated as if it was associated with an
  implicit MX    RR, with a preference of 0, pointing to that host.  If
  MX records are    present, but none of them are usable, or the
  implicit MX is unusable,    this situation MUST be reported as an
  error.
If one or more MX RRs are found for a given name, SMTP systems MUST
  NOT utilize any address RRs associated with that name unless they are
  located using the MX RRs; the "implicit MX" rule above applies only
  if there are no MX records present.  If MX records are present, but
  none of them are usable, this situation MUST be reported as an error.
When a domain name associated with an MX RR is looked up and the
  associated data field obtained, the data field of that response MUST
  contain a domain name.  That domain name, when queried, MUST return
  at least one address record (e.g., A or AAAA RR) that gives the IP
  address of the SMTP server to which the message should be directed.
  Any other response, specifically including a value that will return a
  CNAME record when queried, lies outside the scope of this Standard.
  The prohibition on labels in the data that resolve to CNAMEs is
  discussed in more detail in RFC 2181, Section 10.3 [38].

Since mail servers support the option to smart host to an IP, I don't understand how smarthosting to an A record could be a violation.
Comment: Me neither. Your server isn't delivering the email directly. It's passing it off to a smarthost for delivery. I'm fairly certain that the RFC isn't relevant at all to your server. Where are you hearing/reading that what you're doing violates the RFC?
Answer: This obviously applies to mail servers attempting to deliver mail to its destination. It's utterly irrelevant to situations where you are delivering all mail to a smarthost; the smarthost that you deliver to is responsible for following this, but you are not.
Comment: Thanks.  I agree however I found this Microsoft article which gives me pause: http://blogs.technet.com/b/eopfieldnotes/archive/2014/06/18/outbound-connector-smart-host-behavior.aspx   Specifically, there's a section at the bottom: "How does the lookup for the FQDN smart host work?".  Admittedly it's a different product/platform but the principle seems similar...
Comment: @MikeB That's describing a completely different (though _possibly_ related) scenario, and what MS is doing there is probably wrong. In any case no RFC specifies the behavior in these scenarios anyway.
Comment: Actually I'm pretty sure that how MS is abusing MX records there is a horrible idea, as it provides a publicly advertised point for delivering mail that _bypasses_ their filters!
Answer:

Me neither. Your server isn't delivering the email directly. It's passing it >> off to a smarthost for delivery

So even if its a smart host delivery, you should not use a .local for helo.
.local (.lan) are reserved names for Apple's mDNS. (zeroconf)
In you case, you helo is not correct and should always be a resolvable hostname.
If an MX lookup is done based on .local wel that errors.. since it cannot find your hostname on the recieving server.
And depencing on the mail server setting where your relaying over, its allowed.
This depends on the provider used.
The client name, should also be resolable, but since lots of people misconfigure there dns and forget the PTR, not many block on "unknown" hostnames.
in you case, your server wil never be able to send email to my servers.
These al check on DNS correctness and a resolvable helo hostname.
And more servers are doing this, why, this setting save my for about 80% of spam.
So correct your helo hostname or dont run a mail server.


How to get my Back To Site button to point to the correct location?

Question: I recently logged out of my Drupal 8 site to see the pages not obscured by the admin menu.
I then logged back in (/user/login) and, to my surprise, it sent me to /user/1.
When I tried to click the "Go To Site" link - it sends me BACK to /user/1.
I did nothing out of the ordinary except log out.
How do I get my Back To Site button to point to the correct location (mydomain.com/) again?
Answer: You're just stating facts, that is how Drupal works. If you log in, you go to your profile site by default. That might not make sense for most sites, but that's what it does by default, there modules that allow you to change it.
And "Back to Site" takes you back you the last non-admin page you were on. If you are on the homepage, it will point you back to that. Again, that's a feature, not a bug
Comment: Not sure about the exact implementation there, but non-admin is basically everything except urls starting with /admin. Usually in Drupal, it is a bit more complex than that, you can mark routes as admin/non-admin to override that, but since this link is AFAIK simply done with client-side JS based on your browser history, I doubt it cares about that. So no, user/1 is not an admin page, it's your profile page, which is public assuming you set the permission accordingly.
Comment: Exactly. The new Drupal 8 toolbar includes a contextually aware "back to site" button that serves the same use-case as overlay by allowing site users to return from the admin context _to the page that they were on_.
Comment: So a user page is not considered an admin page?
Answer: This is very confusing, even for people that knows Drupal. The problem is with usability. You wouldn't expect that the same button will take you to different places. Sometimes it take you to the home, some times to your user profile.
To avoid frustrations, I'm removing it from my projects using the following code on a custom module:
/**
 * Implements hook_toolbar_alter().
 */
function mymodulename_toolbar_alter(&$items) {
  // Remove the "Back to site" button from toolbar because it has a confusing logic.
  unset($items['home']);
}


Exhaustive list of chord (at least triad and dom7) functions for a software ear training tool

Question: TL;DR: Does music theory have a name for all possible chord functions for every key chord combination possible (beyond the 7 diatonic functions, including those that seemingly make no sense)? If not how else would you classify chords (root + quality doesn't seem quite sufficient to me but if you think it's the best way to go let me know)
Background
So a few month ago I started working on this side-porject aiming to create a simple ear training tool that was really unique in that 99% of other tools that I found online used interval recognition or absolute pitch, while what I was looking for was a more "functional" method (if there is a more correct term please let me know) that requires you to identify the scale degree of the note rather than its distance from the previous one.
I preferred this method because it felt like the most natural to me (just my subjective opinion), and I made a lot of progress using it. And now I'm looking to add chord recognition to my app. However there's just one tiny problem: I'm not sure how to classify all chords (functionally - by their role in the key). With the 12 chromatic tones it was easy: it was either a tonic, supertonic, mediant... or easier yet: I, II, III... As for the offscale tones, I'd just add a b or # to the roman numeral.
With chords however, things get tricky when we want to classify all the chords with regard to a given key. The 7 diatonic chords, can simply classified by their root tone degree, but what about chords that don't quite fit into the scale? They could be anything (from a functional perspective), as secondary dominant from a related key, a minor chord played major just to tease the listener...
So in general there are 12 tones x 2 qualities (at least major or minor to keep things simple) that need some sort of function (at least one per chord) assigned to them that the user could rely on to answer.
While I know my fair share of theory, I am by no means an advanced musician in that regard. Does music theory have a name or explanation for every chord function possible in a given context? If not, I'm sure all of us tend to interpret an A major (or F minor or Bb minor...) played in a C major context the same way even if it's not a very common thing we hear in music.
Links (If you're interested):

the web application I'm working on is FreeEarTrainer.org. feel free to try it out and maybe tell a friend, but it's still not exactly polished. Check out the settings at the bottom. You can answer faster using the keyboard (Z, X, C, V...). Sadly it doesn't work on iPhone's Safari, and I didn't find time to fix it.

a similar application is "Functional Ear Trainer" which wasn't available on mobile or web when I first started my project, but now is (on Android at least, their website is miles.be).

UPDATE: hadn't had much time to polish up the tool (will occasionally experience bugs when you change keys, requires you to hit the reset button) nor add chord recognition functionality, but I did wrap it in an android app with the same name "FreeEarTrainer.org" for those who are curious to try. The site is also not compatible with Safari (tested With Firefox and Chrome).
Comment: Just to make sure I understand your question correctly: wouldn't e.g. "biii" be sufficient to refer to a minor chord on the lowered 3rd scale degree (in a major key)? So in the key of C major, "biii" would refer to Ebm, whereas bIII (capitals) would refer to Eb (major).
Comment: Going to four note chords should include 3 lots of 7ths, 6ths and sus.
Comment: @MattL. What I'm looking for here is more about whether music theory has a more precise naming to those non-diatonic chord functions. For the example you gave, is it correct to say that Ebm played in a C maj context a flat minor mediant? because that's what the "b", "m" and "E" symbols stand for. Or does music theory have a more correct name for this function. If there is no standard naming for these non-diatonic functions than I guess your suggestion is quite valid.
Comment: @Tim the way I hear 7th, 9th, 11ths, and sus chords, the added notes are more about decoration rather than completely altering the function of the chord. So if I were to add those in my ear training tool, I'd have an option to answer by function, then specify the decorations added to the chord. i.e I'd isolate them from the chord function. The dom7 chords are probably the single exception, as the 7th can really alter the perception of the chord, and making clearer that is is a dominant chord (potentially a secondary dominant).
Comment: @Matt. What if a certain chord was almost inevitably borrowed from a neighbouring key, isn't there a better way to name it? Secondary dominants have a special notation for example. Are there similar notations for other non diatonic functions?
Comment: In a major key, borrowed chords usually come from the parallel minor key, and they are simply named the way I mentioned in my previous comment. So e.g., in C major, and Eb major chord would be "bIII". Secondary dominants are named "V/X", where X is the chord the dominant would usually resolve to. I.e., in the key of C, "V/ii" would be an A major chord (dominant of ii = Dm). However, a chord function only becomes clear in a given context. Are you going to give that context in your tool?
Comment: @MattL. Currently, for individual notes, the diatonic degrees are given a higher weight (controlled in the settings) so that they come up more often, help maintain the sound of the key in question. And there is also an option to play a cadence to re-establish the sound of the key if forgotten. For chords, the matter is going to bi a bit more complicated. I'm considering two options. Completely random roots and qualities, but diatonic chords have higher weight and come up more often (the answer in that case would be as you suggested a "biii" for example).
Comment: @MattL. The second option would be a 2-step technique for generating the chords: 1- diatonic, 2- secondary dominant 3- parallel minor, 4- half-step up change ... This is the category if you will. The most probable will always be diatonic. Then, a chord from that category is picked. The answer buttons would reflect these categories. And for some of the options multiple answers may be valid, so either one is accepted. eg. "relative minor tonic" and the regular "submediant" are valid. I'd prefer this 1, however I'll need to get educated on these "categories" first. Thats where you guys come in :)
Answer: The simplest way to describe nondiatonic chords in this way would be Degree+chord name. I.e. bIImaj7, #VIm7b5, etc. It should be fairly straightforward in all cases where users are able to identify the root note of the chord, and then the relation of that note to the root of the actual key. The number of inversions for full (no skipped notes) chords should be kept limited for everything above m9/maj9 because after that point inverting a chord essentially makes it a different chord (try inverting a full m13).
The only issue I see with this are chords with more than one possible name. For example a chord consisting of F#, C, E, B can be either considered F#m11b5 with no third, or a Cmaj7/F#, and at that point the function is really what you decide it to be in the context of a song. Since your app lacks said context, I would simply avoid such chords and stick to more normal chords ranging from triads to m13/maj13 +limited number of inversions.
Comment: Additionally, make sure your app specifies key (root note + major/minor/any other mode) as degrees only make sense in that context.
"E" or "F#" is not a key. Trying to discern degrees without the context of major/minor would force the user to "assume" major and use degrees in relation to the standard major scale, which is wrong for a number of reasons (but unfortunately fairly common).
Comment: Thanks for your suggestion. I may well adopt this method. Though I doubt I will include anything more than 7th chords. If I ever add 9th chords and beyond (as well as sus and aug...) I'll make sure an answer is considered correct based on the notes that form it and not the exact root + quality ( + inversion if any) intended by the generator.
Answer: There is absolutely a classification for all possible chord functions and root locations in a key. The concept you need to look up is "chord-scales". What that means is that every chord in a key has an assumed scale attached even when not all the notes are played. The tensions (9,11,13) CAN alter the chord-scale—they are not just "decoration" but an integral part of a chord. 1, 3, 5, 7, 9, 11 and 13 are assumed for every chord in a key regardless of whether they are in the chord symbol. Even triads have assumed tensions.
These assumptions dictate the available notes you can play over the chord. Every note in the chord-scale is then classified as a chord tone (1,3,5,7), scale degree (S2,S4,S6), or tension (T9,T11,T13)
The way this works functionally is
IVmaj7—assume "Lydian" (T9,T#11,T13).
bIII7 (a.k.a SubV7/II)—assume "Lydian Dominant" (b7,T9,T#11,T13).
V7/VI—assume "Mixolydian b9,#9,b13" (Tb9,T#9,S4,Tb13).
VII-7b5—assume "Locrian" (Sb2,T11,Tb13). Etc...
If you wrote -7b5(9), it would change the chord scale to "Locrian #2" and (Sb2) would become (T9)
This is called the "berklee method" of music theory. Berklee college of music was the first place to write out a precise chordal classification system back in the 40's so it has become the industry standard for all modern music. There is also the Lydian Chromatic Concept and some others but they aren't as common or as user friendly. You can find Berklee Harmony textbooks online and I would highly recommend picking one up!
Comment: Thank you for the very useful answer. I wansn't aware of the Berklee method, I'll definitely look it up. And welcome to music SE :D


how to get correct order of the image when converted to numpy array?

Question: I am reading the image from the disk and I am converting it to a numpy array
im=Image.open(infile)
imdata = scipy.misc.fromimage(im)

but the image is mirrored like it is stored on the disk.
How to read it in a correct order.
Thanks a lot.
Comment: Have you tried transposing it?
Answer: If it is upside down:
imagedata = imagedata[::-1, :]

If it is swapped left to right:
imagedata = imagedata[:, ::-1]

And if it is transposed (flipped at the diagonal):
imagedata = imagedata.T

If you have more dimensions more (color, alpha, ...) flipping can be done by
imagedata = imagedata[::-1, ... ]

or
imagedata = imagedata[:, ::-1, ... ]

"..." is not a placeholder for something I do not know, but an implemented feature in numpy.


Como guardar valor de uma variável em uma função Bash Script

Question: Estou  criando uma fábrica para que seja facilmente cifrado um arquivo neste caso em txt ou decifrar. O problema neste programa é valor da variável CIFRA_HEX e CIFRA que não consigo passar o valor guardado para a seguinte função (decifra_RC4() ) não sendo possível decifrar o ficheiro.
Como posso resolver essa situação para que consiga obter o valor das chaves na função ?
O código implementado está em Bash Script
    menu(){
case $opcao_menu in
1)echo "REVERSE CRYPTO 4" ;;
esac

echo "1 -> Cifrar"
echo "2 -> Decifrar"
echo "3 -> Voltar ao menu anterior"
echo "Escolha uma das seguintes opções:"

read opcao

case $opcao in
0);;
1) cifrar_RC4 ;;
2) decifrar_RC4;;
esac
}

cifrar_RC4() {
nome="RC4"

echo -n "Introduza a chave de cifra que pertende criar:"; read CIFRA
CIFRA_HEX= openssl rand -hex 8

if [[ -z "$CIFRA" ]]; then
echo $CIFRA_HEX
fi

echo -n "introduza o nome do ficheiro para cifrar:"; read ENTRADA_FICHEIRO
echo -n "Introduza o nome para o ficheiro de saida cifrado:"; read SAIDA_FICHEIRO
echo -n "Deseja remover o ficheiro original?"

if [[ -z "$ENTRADA_FICHEIRO" ]]; then
echo "O ficheiro foi encriptado"
fi

case $opcao_menu in
1) algoritmo_cifraRC4 ;;
2) algoritmo_cifraAES128 ;;
3) algoritmo_cifraAES256 ;;
esac

#read opcao

valor_chave=$CIFRA_HEX
echo "A cifra utilizada foi: " $nome

if [[ -z "$CIFRA" ]]; then

echo "A chave gerada foi: " $valor_chave
else
echo "A chave criada foi: " $CIFRA
fi

echo "O ficheiro criado foi:" $SAIDA_FICHEIRO

}

decifrar_RC4() {

echo -n "introduza o nome do ficheiro para decifrar:"; read SAIDA_FICHEIRO
echo -n "Introduza o nome para o ficheiro de saida:"; read ENTRADA_FICHEIRO

case $opcao_menu in
1) algoritmo_decifraRC4 ;;
2) algoritmo_decifraAES128 ;;
3) algoritmo_decifraAES256 ;;
esac

if [[ -z "$CIFRA" ]]; then
echo "A chave usada foi: " $CIFRA_HEX
else
echo "A chave usada foi: " $CIFRA
fi
echo "O ficheiro de saida foi: " $ENTRADA_FICHEIRO

}

algoritmo_cifraRC4(){
if [[ -z "$CIFRA" ]]; then
openssl enc -rc4 -e -K "$CIFRA_HEX" -in "$ENTRADA_FICHEIRO.txt" -out "$SAIDA_FICHEIRO.rc4"
else
openssl enc -rc4 -e -K "$CIFRA" -in "$ENTRADA_FICHEIRO.txt" -out "$SAIDA_FICHEIRO.rc4"
fi
}

algoritmo_decifraRC4(){
echo $valor_chave
if [[ -z "$CIFRA" ]]; then
openssl enc -rc4 -d -K "$CIFRA_HEX" -in "$SAIDA_FICHEIRO.rc4" -out "$ENTRADA_FICHEIRO.txt"
else
openssl enc -rc4 -d -K "$CIFRA" -in "$SAIDA_FICHEIRO.rc4" -out "$ENTRADA_FICHEIRO.txt"
fi
}
menu

Answer: Único erro que vi no teu código foi CIFRA_HEX= openssl rand -hex 8 se vc deseja colocar o resultado do comando dentro da variável deve fazer asim

CIFRA_HEX=$(openssl rand -hex 8)

veja o resultado:

echo $CIFRA_HEX
2e7918cf12d2f50e

ou assim

CIFRA_HEX=`openssl rand -hex 8`
echo $CIFRA_HEX
2e7918cf12d2f50e

se quer o conteúdo como string, deve colocar entre aspas simples

CIFRA_HEX='openssl rand -hex 8'
echo $CIFRA_HEX
openssl rand -hex 8


Does $destroy function removes the Vue Custom component from cache

Question: I construct deep nested tree of parent and children Vue custom components using my top level component dynamically and then I am updating the data from which all tree is constructed. Which has an effect of rendering the entire tree (its a form with various custom components). I refresh/rebuild the whole form after fetching the data (which is what vue do for reactive data) that itself tell me how to regenerate the view (its like a JSON Schema from which I render the entire view).
This is related to my other issue here.
I am observing a very weird behavior in my Vue Application. When I destroy all my children components and rebuild the data to force rendering the form, it appears that even after I have called $destroy on every child component...Vue is not entirely removing them from cache?
Does vue remove the component from cache if a $destroy is called ?
Because I do not see multiple components of the same type in the Vue component list in the Chrome Vue DevTool extension panel. But I see that the same custom event is handled twice by the same component. Same function that handle the events is getting called twice even though there is only one component visible in Vue DevTools of this type.
This only happens after I render the form. When the page is loaded for the first time every thing works. Then after I reset the form by destroying the child component and resetting the data to re-render the form, magically this child component start handling the event twice.. and in 3rd render it handle the events thrice. But I see only one component in google chrome VueJS DevTool extension panel. So my guess is that vue is still keeping the previously destroyed component in cache. I am trying to figure out how should I destroy those components in the cache.
If anyone has observed something similar and found a solution please let me know.
At the moment I am going to dig little bit more on my component keys (this particular component does not have explicit key set by me).
Comment: If you could add a code example, I can customize my general answer to it
Answer: First and foremost, the vue documentation states:
vm.$destroy

In normal use cases you shouldn't have to call this method yourself.
Prefer controlling the lifecycle of child components in a data-driven
fashion using v-if and v-for.

So instead of destroying and rebuilding the components manually yourself, you should really letting vue handle that via v-if and v-for. If the components aren't updating to your changes, you might be dealing with a reactivity issue.
As you mentioned that this is a deeply nested structure, the reactivity is key to keeping the components up to data with the data.
Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it's possible to add reactive properties to a nested object using the Vue.set(object, key, value) method:
Vue.set(vm.someObject, 'b', 2)

Inside of a component:
this.$set(this.someObject, 'b', 2)

Also, keep in mind that Vue should be doing the heavy lifting in regards to component management, while you should define the parameters by which a component is rendered.


Jsoup elemento sem id

Question: Bom, estou querendo usar JSoup pra pegar uma tabela de um site e mostrar no aplicativo. O problema é que essa tabela não tem id. Como fazer pra pegar essa tabela e exibir no app?
Aqui tá o site:http://warface.uol.com.br/suporte/lista-de-punidos
Answer: Com o JSoup, a busca por elementos não precisa ser exclusivamente por Id. Você pode também fazer buscar por CSS Selectors. Assim:
<code>Elements elements = document.select("#main > div > div.conteudo > table");
</code>

Jsoup elemento sem id


custom module date formatter for publication date

Question: I have a Drupal 8 contrib module AP Style Date that provides a formatter for dates to conform to the AP Style Guide date rules. When using the module Publication Date, this formatter does not come up as an option. The AP Style Date does come up in views and in managing field display for other date types. Is there a modification that needs to be made to the AP Style Date module or something in the publication date that needs to be modified?
Comment: AP Style Date provides a field formatter, which effects how a field (E.g. something that takes user input when creating the content) is displayed. "Publication date" on the other hand provides a display field that outputs a value set in the backend. So it does not expose itself to field formatters for rendering. So in other words, unfortunately they are not compatible. At least as far as I can tell.
Answer: The Publication Date module provides a function to define which formatters can be used. I added a patch, which we maintain locally, to add the defined "timestamp_ap_style" format to the options. Optionally, I could have added it inside a custom module, but the patch seemed to make more sense.
<code> function publication_date_field_formatter_info_alter(array &$info) {
   $info['timestamp']['field_types'][] = 'published_at';
   $info['timestamp_ago']['field_types'][] = 'published_at';
   $info['timestamp_ap_style']['field_types'][] = 'published_at';
 }
</code>
Update:
Recently I came across a commit in the Smart Date with the same need that I had in the AP Style Date module. So, I tried that and it works.
<code>/**
 * Plugin implementation of the 'timestamp' formatter as time ago.
 *
 * @FieldFormatter(
 *   id = "timestamp_ap_style",
 *   label = @Translation("AP Style"),
 *   field_types = {
 *     "datetime",
 *     "timestamp",
 *     "created",
 *     "changed",
 *     "published_at",
 *   }
 * )
 */
</code>
Simple and elegant.


Refer to memory location with an offset in GNU Assembly

Question: Sorry in advance for the novice question, but strangely enough I couldn't find a proper answer to this question. Simply put, let's say I want to movl from a certain variable to the %ecx register. This variable is a buffer full of input. How do I reference the buffer AT a specific offset, ie buffer + 1 or buffer + n? I need it for basic string iteration.
All help is appreciated, even if it's just helping me find a previous post that answers it but that I couldn't find.
Comment: That's not a register that you are asking about, that's a variable. And you refer to it exactly like you showed: `movl buffer + 1, %ecx`. If the offset is not constant you load it into a register and use something like `movl buffer(%eax), %ecx`. This is basic knowledge you should read some introductory material. PS: for strings you probably want to use a 8 bit destination or `movzbl`/`movsbl`.
Comment: @Jester For one, I don't have access to any introductory material proper, the one book I have on assembly is in x86 architecture. So it is literally just [variableName] + [offset]?
Comment: You should be careful about `[]` notation because that has its own meaning in intel syntax. I have showed you the example, that's how it should look. See also the [as manual](https://sourceware.org/binutils/docs/as/i386_002dMemory.html).
Comment: Please do not remove architecture tag.
Comment: Does this apply to x86 as well? If so I have no problem, but the question is about GAS assembly.
Comment: It applies to x86, other architectures may use different addressing.
Comment: Also, how do I use the contents of a register instead of a number as the offset?
Comment: I have **showed** you an example for that too!
Comment: Ok, ok, yeesh. I didn't notice it, I'm getting frustrated that what little assembly instruction I can find with Google is never in a format that I can understand and it's making me weird. I'll try that. EDIT: Ok, it works now. Thank you for your help, the manual you linked me to I simply could not understand.
Answer: In AT&T syntax (used by GAS), the following is used for an indirect offset reference:
<code> movl     8(%ebp), %eax   ; Move from EBP+8 into EAX
</code>
In Intel syntax (Which is actually also understood and accepted by GAS) it would be:
<code> MOV      EAX, [EBP+8]
</code>
Another alternative (which you seem to be interested in) is Base Plus Index addressing:
<code> MOV      EAX, [EBX + EDI]
</code>
This moves into EAX (using Intel format) the content of the memory location that is the sum of EBX and EDI.  In AT&T format this would be:
<code> movl     (%ebx,%edi), %eax
</code>
Honestly, I rarely use this form.  You may have to include a scale factor.  You can use one to meet your needs:
<code> movl     (%ebx,%edi,1),%eax   ; Where 1 is a scaling factor (ebx+edi*scale)
</code>
Comment: Could you show me your first example, but instead of 8 use a register that contains the offset number?
Comment: I've added some examples that ought to work.  Might need adjusting.  I rarely write code quite that way and I avoid AT&T syntax whenever possible. :)
Comment: I still seem to have trouble. Here, I'll show the code that's having issues: `movl $buffer, %edi - movl (%edi,%esi), %ecx` The contents of %esi are incremented in a loop that I know works, and movl $buffer, %edi is called at the beginning of the loop every time. However, it doesn't increment the index properly to be one after another, and seems to randomly jump around. Am I doing it right?
Comment: It sounds to me as though you have an entirely different problem that needs debugging.  I think the question you have here is a good one and you should leave it as is since it's been answered.  I'd open a new question, posting your code and asking what you just said to me here... "I can't see why this index is jumping around randomly.  What have I missed??"


How do I determine whether a function/map T is one-to-one and/or onto?

Question: Given $T(x,y,z) = (xy, yz, xz)$, determine whether $T$ is one to one and/or onto.
So far, I have come up with a contradiction that proves $T$ is not one to one:
$T(-1, 1, -1) = (-1, -1, 1)$
and, $T(1, -1, 1) = (-1, -1, 1)$. However, I can't figure out whether or not $T$ is onto... I think it is, but I don't know the reaosn why or how to prove it.
Can I say:
Taking arbitrary elements a,b,c $\in \mathbb R$, $T(a,b,c) = (ab, bc, ac)$, and therefore any element $x,y,z \in \mathbb R$ can be generated by $x=ab$,   $y = bc$, and $z=ac$?
Answer: Assuming both the domain and codomain are $\mathbb{R}^3$.
Suppose on the contrary that it is onto, then $(-1,-1,-1)$ has a preimage.
Suppose $$-1 =ab, -1=bc, -1=ac$$
then we have $a = -\frac{1}b, c= -\frac{1}{b}$
and we have $ac= \frac1{b^2}>0$ which contracts $ac=-1<0$.


Linear algebra - orthogonal basis

Question: Question- Find an orthogonal basis for the set of solutions of the equations:
$x_1-2x_2+3x_3-x_4=0$
$ 2x_1+x_2+x_3+2x_4=0$
(sorry for all the underscores, still haven't worked out how to insert equations)
So, I put this into a matrix, row reduced and got $x_1$ and $x_2$ as functions of $x_3$ and $x_4$.
$ x_1 = -\frac{1}{5} x_3 -  \frac{3}{5} x_4$
$x_2 = \frac{7}{5} x_3 -\frac{4}{5} x_4$
Then let $s=x_3$ and $t=x_4$ to get a basis,
Basis.image
However I believe this is not orthogonal as the dot product should equal zero.
Any help is appreciated, I'm not sure if I'm doing any of this correctly, thanks.
Comment: You need to add a \$ before and after the mathematical expression. For example, adding a \$ before and after x_2 results in $x_2$.
Answer: You need to orthogonalize the basis vectors your computed. You may use Gram-Schmidt orthogonalization method to do so.
The equations you provided ($x_1 - 2 x_2 + 3 x_3 - x_4=0$ and $2 x_1 + x_2 + x_3 + 2 x_4=0$) should result in $$x_1 = -x_3 -\frac{3}{5}x_4,$$ and $$x_2 = x_3 -\frac{4}{5}x_4.$$
Answer: Suppose you have computed a basis (the vectors you have in the linked image) for the solutions set to be $\{u,v\}$. Then you want a basis $\{u,w\}$ such that $u \perp w$. Since $w \in \text{Span}(\{u,v\})$, so you can simple choose
$$w=v-\text{proj}_uv=v-\left(\frac{u \cdot v}{\|u\|^2}\right)u.$$
It is easy to see that $w \perp u$.

Linear algebra - orthogonal basis


IndexError: index 4 is out of bounds for axis 0 with size 4

Question: Boa noite. Estou com o seguinte código em Python, mas aparece o erro citado:
import numpy as np
x=np.ones((4,1))
for k in range (5,45):
x[k]=5.5369*x[k-1]*(x[k-2])**2+0.1931*x[k-3]
print(x)

O erro é:

IndexError: index 4 is out of bounds for axis 0 with size 4

Comment: Você está criando uma matriz 4x1 e então tentando acessá-la como se fosse um vetor nas posições de 2 até 45.
Comment: O que é que você está tentando fazer com esse código?
Comment: Eu já tenho as 4 primeiros valores do vetor x, então através da função recursiva dentro do for, quero calcular os outros valores
Answer: Você tem dois problemas grandes no seu código (mais uma pequena falha de formatacão dentro do loop).
Um está no seu range, o outro na alocacão do vetor.

Range:

Para um vetor de tamanho N, Python usa indices de 0 até N-1.
No seu caso, N=4, com índice máximo de N-1=3.
A primeira chamada usa range(5,45) = [5, 6, ... , 44] com k-1=4. Obviamente um problema aí. Usando range(4,45), este problema fica resolvido, mas daí temos o problema seguinte.

Memória:

Em Matlab a sua sintaxe funciona, pois ele vai alocando a memória conforme a matrix é chamada. Vale lembrar que isso é uma prática de programacão terrível!
 Não use isso ao menos que você realmente precise. Em Python, ele não faz isso. Pelo menos não desta maneira.
O que você quer é fazer um append a matrix.
Porém vamos a um código da maneira eficaz, em que o vetor foi alocado completamente antes do cálculo:
x=np.ones((45,1))
for k in range(3,45):
  x[k]=5.5369*x[k-1]*(x[k-2])**2+0.1931*x[k-3]

print(x)

Caso você queira muito usar o append (que não é necessário para este caso, mas pode ser para outro), o código fica:
x=np.ones((3,1))
for k in range (3,45):
  x=np.append(x,5.5369*x[k-1]*(x[k-2])**2+0.1931*x[k-3])
print(x)


WHM / Cpanel : Create and download backups for all accounts?

Question: Is this possible? I want to download a standard cpanel full backup of every account on my server. There's about 15 accounts. Each are about 50-500 megs. It takes me about 3 hours every week to do this and I'd like to automate this process or at least do it in batch so it takes less time.
Comment: This question appears to be off-topic because it is about [`working with a service provider's management interface, such as cPanel`](http://serverfault.com/help/on-topic).
Answer: You should be able to do this from within WHM, go to backup & restore, and there is the ability to backup and download all accounts?
Alternativley, if you use virtuozzo on your server, you could create a compelte server backup.
Answer: You can either just write a script that will do this for you or use services like backupsetc.com which allow you to automatically backup your accounts within their infrastructure and then you can get them from there any time you want, and it's fully automated.
Answer: You can upload all you backups to an FTP server using the cpanel backup wizards.
This option is available on both cpanel and WHM.


What security issues are involved with cross-domain logons using OpenID?

Question: I want to implement cross-domain logons for 3 sites. Is OpenID the best tool for protecting my site and users?
Answer: As far as I'm aware OpenID is reasonably secure. The downside to OpenID is that it's fairly complicated for non-technical users to understand. Something like this might make that a little easier on your users. There are options to make your site the OpenID provider, but they don't seem ready for production sites yet from a brief skim through the issues.
Another option might be OAuth. This would let your users log in with their accounts from sites like Facebook, Twitter and LinkedIn.
If all 3 sites are Drupal sites, one final solution might be to share the users between the sites, by sharing certain database tables. This would allow you to share other information about your users between the site profiles as well.
This page on Drupal.org describes the details, as well the downsides. Main one being that upgrades to major Drupal updates aren't supported. I honestly wouldn't recommend this unless you know a great deal about how the database side of Drupal works.


Range of $p$ in cubic equation

Question:
If $2x^3+px^2+qx+4=0$ has $3$ real roots, then what is the range of $p$? Here $p,q>0$.

My try: Let $\alpha,\beta,\gamma$ be the roots of $2x^3+px^2+qx+4=0$.$$
\begin{cases}
\alpha+\beta+\gamma=-\dfrac{p}{2}\\
\alpha\beta+\beta\gamma+\gamma\alpha=\dfrac{q}{2}\\
\alpha\beta\gamma=-2
\end{cases}
$$
Help me how to solve after that point.
Comment: See https://math.stackexchange.com/questions/425187/abc-0-a2b2c2-1-prove-that-a2-b2-c2-le-frac154/425269#425269
Comment: Because $P(x)=2x^3+px^2+qx+4$ has $3$ real roots then, by [Rolle's theorem](https://en.wikipedia.org/wiki/Rolle%27s_theorem), $P'(x)$ has 2 real roots. I.e.
$$P'(x)=6x^2+2px+q$$
where $\Delta=4p^2-24q>0$ or $p^2>6q$.
Answer: Let $\beta = \sqrt[3]{2}$. Change variable to $y = \beta x$, $p = 6a\beta$ and $q = 6b\beta^2$. The problem is equivalent to:

For what $a > 0$ we can find a $b > 0$ so that the cubic equation
  $$y^3 + 3a y^2 + 3b y + 1 = 0\tag{*1a}$$
  has $3$ real roots.

Let $z = y+a$, $(*1a)$ is equivalent to
$$z^3 -3(a^2-b) z + (1 + 2a^3 - 3ab) = 0\tag{*1b}$$
In order for $(*1b)$ and hence $(*1a)$ to have $3$ real roots (counting multiplicity), the discriminant of $(*1b)$ has to be non-negative. More precisely,
$$-4(-3(a^2-b))^3 - 27(1 + 2a^3 - 3ab)^2 \ge 0
\quad\iff\quad
 4(a^2-b)^3 \ge (1 + 2a^3- 3ab)^2\tag{*2}
$$
Notice RHS$(*2)$ $\ge 0$, this imposes $a^2 \ge b$ as a necessary condition for $(*1b)$ to have $3$ real roots.

Case I ( $a < 1$ )
We have $1 - a^3 > 0$. This implies
$${\rm RHS} = (1 + 2a^3 - 3ab)^2 = ((1 - a^3) + 3a(a^2-b))^2 \ge (1-a^3)^2 > 0$$
This leads to $a^2 - b > 0$ and
$$4 (a^2-b)^3 = {\rm LHS} \ge {\rm RHS} \ge (3a(a^2-b))^2 \implies 4 (a^2-b) \ge 9a^2$$
which is clearly impossible. This means there is no $b$ which can make
$(*1b)$ having $3$ real roots.
Case II ( $a = 1$ )
$(*2)$ reduces to $4(1-b)^3 \ge 9(1-b)^2$ and it has a unique solution $b = 1$.
Case III ( $a > 1$ )
If we take $b = \frac{1+2a^3}{3a}$, we have RHS$(*2) = 0$ and
$${\rm LHS}(*2) = 4\left(a^2 - \frac{1+2a^3}{3a}\right)^3 = 4\left(\frac{a^3-1}{3a}\right)^3 > 0$$
For such a $b$, $(*2)$ is satisfied and $(*1b)$ has $3$ distinct real roots.

Combine these, we can conclude:

When $a < 1$, there is no $b$ which makes $(*1b)$ has $3$ real roots.
When $a = 1$, there is a unique $b$ where $(*1b)$ has $3$ real roots
(counting multiplicity).
Namely $b = 1$ and $(*1a)$ has a triple root at $y = -1$.
When $a > 1$, there is at least one $b$ which makes $(*1b)$ has $3$ distinct real roots.

Translate this to $p$, the desired range of $p$ is $[6\sqrt[3]{2},\infty)$ or
$(6\sqrt[3]{2},\infty)$ depends on whether having $3$ real roots means
$3$ real roots (counting multiplicity) or $3$ distinct real roots.
Answer: Since $p, q > 0$, the real roots to the equation $2x^3 + px^2 + qx + 4 = 0$ can only be negative. Replacing $x$ by $-x$ and dividing by $x$, the equation is equivalent to $2x^2 - px + q - \dfrac{4}{x} = 0$, where $x > 0$.
Define $f(x) = 2x^2 - px + q - \dfrac{4}{x}\ (x > 0)$, then$$
f'(x) =4x - p + \frac{4}{x^2},\ f''(x) = 4 - \frac{8}{x^3}.
$$
Thus the minimum of $f'(x)$ is $f'(\sqrt[3]{2}) = 6\sqrt[3]{2} - p$.
Case 1: $0 < p \leqslant 6\sqrt[3]{2}$. In this case, because $f'$ is positive on $(0, \sqrt[3]{2})$ and $(\sqrt[3]{2}, +∞)$, respectively, then $f$ is strictly increasing on $(0, \sqrt[3]{2})$ and $(\sqrt[3]{2}, +∞)$, and thus strictly increasing on $(0, +∞)$. Therefore, $f$ has no more than one real root.
Case 2: $p > 6\sqrt[3]{2}$. Now take $q = \sqrt[3]{2} p$, then $f(\sqrt[3]{2}) = 0$. Because $f'(\sqrt[3]{2}) < 0$, then there exist $x_1 < \sqrt[3]{2} < x_2$ such that $f(x_1) > f(\sqrt[3]{2}) = 0 > f(x_2)$. Note that$$
\lim_{x → 0^+} f(x) = -∞,\ \lim_{x →+∞} f(x) = +∞,
$$
then there exist $0 < x_3 < x_1$ and $x_4 > x_2$ such that $f(x_3) < 0 < f(x_4)$. Therefore, $f$ has roots on $(x_3, x_1)$ and $(x_2, x_4)$, respectively. Therefore, $f$ has three real roots.
Hence the range of $p$ is $(6\sqrt[3]{2}, +∞)$.

Range of $p$ in cubic equation


Locate the lookaround positions in vim [Possible VIM Bug]

Question: I wanted to understand the behavior of the lookaround in vim so for that I tried to mark the positions of assertion. Let's suppose I have the content of this file:

foobar

By executing this command :s/\(foo\)\@<!/♠ /g I got:

♠ f♠ o♠ ob♠ a♠ r

Why I don't have ♠ at the end of line ? Is the $ anchor not considered as a position in this case ?
Instead if I execute this command :%s/\(bar\)\@<=/♠ /g I got:

foobar♠

Any Explanation ? and Can someone please confirm this behavior ?

Vim 7.4 Ubuntu 16.04 LTS
Comment: I can reproduce this as well. It looks like it might be a bug.
Comment: @merlin2011 thanks for notifying !
Comment: It can reproduce this as well in pcre. It looks like a vim's specificity or bug. [![enter image description here](https://i.stack.imgur.com/BlKiv.png)](https://i.stack.imgur.com/BlKiv.png)
Answer: In both of your cases, you're effectively matching nothing, and just do assertions around that.
The behavior of :s/\(foo\)\@<!/♠ /g is consistent with the simpler :s/\zs/♠ /g
♠ f♠ o♠ o♠ b♠ a♠ r

A match only starts at an existing character; the implicit newline after each line does not count (according to Vim's implementation).

With your second :%s/\(bar\)\@<=/♠ /g command, the assertion effectively acts like the simpler $ atom. Like :s/$/♠ /g, it therefore inserts after the assertion match, even though there's only the (implicit) trailing newline after it.

So, though maybe surprising and inconsistent with other regular expression engines, you see that inside Vim, this is all consistent with the internal workings of its regular expression engine and buffer representation. I therefore would think that this is not a bug. If you still feel strongly about this, you could raise an issue at the bug tracker, or directly discuss this on the vim_dev mailing list.