What can one do to understand time signatures?

Question: I am struggling with the basics of Time Signatures. For one, I see it as more of a 'beat' signature. Notation is old, and time signatures are of an age where there was no clock, or way of keeping time (metronome).
The main reason I can see as to why I do not get it is that:
I fear you have to have a mathematical brain? It would explain why I am struggling to understand and count beats within a bar.
Back to my question, what can one do (what exercises can one do) to understand time signatures?
Resources online are good, but they do not explain it if you are struggling. Instead they continue to then talk about key signatures.
I do understand the following:

The first number (on top) tells you how many beats there are in a bar.

The second

What kind of beat is given one note.

This is agreed yes, but if I am still struggling when reading music to understand if there are the correct beats within a measure what else can I do?
Comment: I'd be inclined to phrase The second as 'What **kind of note** is given to one beat.'
Answer: True, the top number tells how many beats per bar. The bottom tells what sort of notes each beat is.
In 4/4, for instance, the top 4 says there will be 4 of the bottom 4. That bottom 4 says that each beat, or pulse, will be worth a crotchet, or quarter note. Be aware that nowhere here tells how fast or slow the piece will be played, that's not the purpose. So with no metronome mark or bpm stated, it could be played at whatever speed the player decides.
In 3/4, there will be 3 crotchets per bar, so the count will be 1 2 3 1 2 3, or if there are shorter notes, it may be easier to read counting 1+2+3+1+2+3+, the numbers being counted at the same speed in both cases, but again the speed is not mentioned.
There is no need to struggle to understand if each bar will contain the correct quota - it just will !! It has to . That's why the time sig. is put at the beginning!
If you like, it could be called a 'beat signature', it's not a bad title, although there's no need to change its name, as it does explain the timing, which really has nothing to do with how fast the piece is played.
In 3/8, there will be 3 quavers (1/8 notes) per bar, as the 8 represents quavers. These can be seen as lasting half as long as the aforementioned crotchets, BUT since the actual duration of a crotchet isn't specified within the time sig., it can only be construed that all the notes in the piece will be shorter than in 3/4, thus making it a quicker piece. But no-one can say each beat is half as long, simply because no-one can say how long a crotchet is. I think that's the crux here. Unless we're told how long a beat is (bpm),then we can play the piece at whatever tempo we want, within reason. But - the whole point is that each bar will contain its proper sum of beats, as per time sig., and each bar will be played at the same speed as any other bar in that same piece.
Incidentally, metronomes have been around for over 200 yrs, and clocks a darned sight longer. But neither would be that helpful in explaining time sigs...
Answer: Top number: 'how many', bottom number: 'of what?'  is half the answer.  But it's more complicated than that.  When the top number is greater than 4 it will normally be divisible by 3 (6/8, 12/8) and the 'beat count' is the number of '3-groups'.  6/8 is two beats to the bar, each group consists of three 8th notes.  9/8 is three beats, 12/8 is four beats...   Then we have time-signatures that indicate a mixture of 3- and 2-groups.  5/8 or 5/4 is a 3-group plus a 2-group (and there's nothing in the time signature to tell us which way round, and it may keep switching! You have to look at the note groupings.)
And none of the above is exhaustive, or immune from exceptions.
Yes, it's complicated.  And it's really nothing to do with having a metronome available or not - they just help you keep in time once you've worked out how many beats there are and what the metronome should be set to!
Sit down with your teacher, use music that you are actually working on as examples. This sort of thing is much better demonstrated than explained. Don't worry too much about a Unified Theory of Time Signatures, just learn about the music you're currently reading.
Comment: @Dekkadeci If grouping is consistently 3+3+2+2 and there are no groups of 5 coinciding with bar lines I would find it plainly confusing to notate this as a hemiola in a 5/4 for the whole piece. (Note that with a three beat anacrusis it does fit the bar lines.)  But then again, the internet is filled with crappy transcriptions of all kinds of pieces and songs; I've seen D major triads spelled as D, G flat, A for example. I'd take a slightly mismatching time signature over these weird enharmonic mistakes any day.
Comment: Yes, like I said about 5/8.  I've added 5/4 to the answer.  And, like I said; the grouping may net be consistent throughout a piece (I'm not going to call it a 'song').    It can vary bar-by-bar.  As most 'theory', this is about description, not about a set of rules.
Comment: What about 5/4, 7/8, 7/4, etc? For that, you split them up into groups of two or three beats, with the splitting happening in different places for different songs, IIRC.
Comment: I've seen 3+3+2+2 notated as 5/4. I've seen those same pieces notated so rarely as 10/8 that I don't know whether that's correct, even though it makes more sense to me.
Comment: To add to the exceptions: [Blue Rondo à la Turk](https://en.wikipedia.org/wiki/Blue_Rondo_%C3%A0_la_Turk) is notorious for being in 9/8 with alternating 2+2+2+3 and 3+3+3 groupings.
Answer: As you have said, the top number tells you how many beats are in each measure. The bottom number tells you the duration of each beat. Multiplying the two numbers in the time signature tells you the total duration of a measure.
To reinforce this, practice translating the time signature into the appropriate music notation. How would you notate the duration of one beat? How would you notate the number of beats? You might find it helpful to make charts like this one:

When I am just beginning to practice something, I like to approach it
systematically at first. I would write out the beat duration and number of beats for 2/2, 2/4, 2/8, and 2/16. Then I'd do it again for 3/2, 3/4, 3/8, and 3/16 (see image above). Then I'd do it again for 4/2, 4/4, 4/8, and 4/16. Once you get the hang of this, you can mix up your practice (e.g., do 3/2, 2/4, 5/16, etc.).
Another way to quiz yourself is with flashcards. Here are two flashcards you might have:

As you can see, this forces you to recognize the time signature even when some of the beats are subdivided.
But if you start subdividing, there's something to watch out for. Imagine taking a measure of 3/4 and subdividing each quarter note into two eighth notes. This gives 6 eighth notes:

How would you distinguish this from a measure of 6/8? After all, they both contain six eighth notes. The answer is in the beat emphasis/grouping. By convention, 6/8 groups the beats this way:

The first beat in each group is stronger (S), meaning we emphasize that beat. The other beats in each group are weaker (W), meaning we don't emphasize them as much. For more on conventions of beat groupings/emphasis, check out this post. The short version is: time signature with 6 beats, 9 beats, 12 beats, or any other higher multiple of 3 are "compound" meter. This means we break up those beats into groups of 3. By contrast, "simple" meters (2/2, 2/4, 3/2, 3/4, 3/8, etc.) generally break up beats into groups of 2.
Comment: In your 1st para, have you mixed up 'top' and 'bottom'? Or did I read it wrong?
Answer: I think you already understand the theory behind time signatures, but that you are having trouble with all the exceptions that occur in practice. As Laurence Payne writes, "Top number: 'how many', bottom number: 'of what?' is half the answer". The only thing that a time signature denotes with any degree of reliability is the notated length of all the notes in a single bar added together. For example, in a 4/4 you know that all notes in that bar (in a single voice) add up to the same length as 4 quarters (or a whole note). (And even for this seemingly trivial statement there are counterexamples.)
According to the how-many-of-what-system, you should count 4 beats in a 4/4 bar (we would call this "counting in 4"), you should count a 3/4 in 3 and a 6/8 in 6. In practice, however, it doesn't work this way. For starters, 6/8 is virtually always counted in 2 (and a 9/8 in 3, etc). This has a historical justification since these meters are related to time signatures in mensural notation (music notation in the renaissance) and were later used as shorthands for triplets. But this shouldn't have to be a problem; we could call it an exception to the rule (as many theory books do) and be done with it. But the next thing that happens in practice is that some pieces are fast. This means that sometimes it makes more sense to count a 4/4 in 2, or a 3/4 in 1.
When it comes down to it, you should use the time signature to derive the grouping of the notes in a bar (2+2+2 eighths in a 3/4, but 3+3 in a 6/8, for example) and the appropriate downbeats. When you get more comfortable with music notation you will see that at a certain point it doesn't particularly matter how you count internally as long as you preserve the grouping and downbeats; sometimes you need to be aware of all eighth notes in a very slow 3/4 to keep the tempo, sometimes a piece is so fast it doesn't make sense to count as many beats as indicated by the time signature.
To experience this I would advise the following, and I hope this will resolve your doubts about time signatures. Listen to a lot of music, trying to count along, then check the time signature in the sheet music, see if it matches what you thought and if it surprised you listen again, trying to count as the time signature would suggest. Probably, if you were surprised by the notated meter, there is an obvious problem with counting as the meter would suggest (in most cases either too fast or too slow).
If you try my advise, don't expect you will learn to tell the meter of each piece (because, without knowledge of the type of piece, the style of the time the piece was written and the style of the composer it can be impossible to tell). The point of this exercise is for you to see how what you hear relates to what is written (in terms of time signatures). Each time you are surprised by the notated meter is a win.
Comment: Counting 6/8 in 6 is as unlikely as counting 4/4 in 8.
Comment: @LaurencePayne I agree. I intended to contrast the theoretical conclusions the OP seems to draw with what happens in practice, but rereading I agree it could be much clearer. Will edit.
Comment: @LaurencePayne Have edited. Thoughts?
Comment: There's nothing in MUSIC theory that tells us to count 6/8 in 6.   You're making it sound like that's the 'right' way to do it, but we slip into 2 for expediency.
Comment: @LaurencePayne I would argue that that _is_ what the notation "should" mean, my point being that there is more to meters than the notation. However, music theory being descriptive rather than prescriptive I agree my phrasing was off.
Answer: I think you should distinguish between meter and time signatures. Understand meter first then the time signatures used to represent meters.
Musical meter can be understood as an abstract mathematical idea.
Time signatures are the product of centuries of notation development. As a system they are inconsistent and involve exceptions to rules. But, the good news is that in normal practice there are a small number of common time signatures.

Meter
Meter is a regular pattern of accents. Logically it needs at least 2 units so that something is accented while some other thing is not accented. The next larger group of units will be 3. All larger groups can be divided into combinations of just 2 or 3. Sorry for that digression, but it's musically relevant to understand the significance of 2 and 3.

Meters using a division of 2 are called duple.
Meters using a division of 3 are called triple.
Meters using combinations of 2's and 3's are called additive. Example, a meter based on 7 could be broken into groups like 2+2+3, 2+3+2, or 3+2+2. Let's gloss over questions like a count of 7 with only a single accent.

Regardless of how a meter is notated in written form aurally it will conform to this breakdown into groups of 2 or 3. Of course, music may not conform to a regular meter and it would be called un-metered.

Time Signatures
Time signatures are the traditional way to indicate meters in a score and they aren't consistent.
The main inconsistency, however, involves groups of 3. If you get a handle on the time signatures involving 3, the rest should be fairly straight forward.
While meters and time signatures can be classified as duple or triple, they are also classified as simple and compound. Strictly speaking duple/triple tells the number of accents (beats) per measure while simple/compound tell the number of subdivisions of the beat. Subdivision of the beat by 2 is simple and subdivision by 3 is compound.
Regarding the top number of the time signature:

if it is a power of 2, the meter is duple and simple
if it is divisible by 3, it is triple, and simple or compound
if it is prime, it is additive

Notice how the terminology gets jumbled together right at the start of reading the time signature! And the line for "3" more complicated than the other two.
We can untangle the complications by falling back to the abstract metrical concept of 2 and 3 and finding where the accents (beats) are placed and how beat subdivision is handled. The practical way to illustrate it is by comparing the time signatures 3/4 and 6/8.
Numbers like 6 and 12 can be divided by either 2 or 3. From a metrical perspective we could think of them as ambiguous compared to a number like 8 which cannot be divided by 3. Let's examine 6. It could be grouped two ways (angle bracket shows the accent/beat)...

>     >     >
|  |  |  |  |  |

...or...

>        >
|  |  |  |  |  |

I deliberately made abstract figures above and did not indicate the time signatures. Again, the idea is first understand the abstract pattern, then understand the time signature.
The traditional time signature for 3 beats subdivided by two is 3/4...

The traditional time signature for 2 beats subdivided by 3 is 6/8...

The eighth note beaming indicates the beat.
Time signature conventions are...

Simple and triple is 3/4
Compound and duple is 6/8

If we wanted to state rules, it would be something like...

upper numbers that are powers of two or the number 3 are simple
upper numbers that are greater that 3 and divisible by 3 are compound
upper numbers divisible by 2 and 3 could be compound or reduced and re-beamed to become simple meters
upper numbers that are prime are additive meters
the lower number of a simple meter indicates the note type used for the beat
the lower number of a compound or additive meter indicates the note type used to subdivide the beat, the number of beats per measure being the upper number divided by 3 for compound meters or some division of the upper number by 2 or 3 for additive meters.

...logical rules get unwieldy, because the time signatures follow conventions not rules.
We could notate rhythms with beaming and accents that contradict those conventions...

...or...

...mathematically we have the correct number of notes, but either we are accidentally contradicting the conventional placement of accents, or technically we are using the rhythmic device called hemiola.

In the two sections above the meter part is straight forward while the time signature part is a confusing mess of two counting systems.
Instead of trying to handle time signatures with pure logically, just follow conventions.
When the top number is: 2, 3, or 4 it gives the beats per measure, is simple meter, and and the lower number indicate which note type gets the beat. Subdivide the beat by 2 or 4.
When the top number is: 6, 9, or 12 it gives total subdivisions of the beat per measure, is compound meter, and the lower number is the note type used to subdivide the beat into groups of 3 typically it will be an eighth note.
When the top number is one of the primes: 5, 7, 11, or 13 it gives total subdivisions of the beat per measure, the meter is additive, and the lower number is the note type used subdivide the beat into unequal groups of 2 and 3.
A practical list might be...
Simple

2  3  4  3  2  3
4, 4, 4, 8, 2, 2

Compound

6  9  12 6
8, 8, 8, 4

Additive

5  7  11 13
8, 8, 8, 8

The list above isn't exhaustive and additive or changing time signatures can be written differently. Like this for 7/8...

3+2+2
  8

But, there are only about a dozen common time signatures. It may be easiest to just memorize how they are classified and practice counting them.

...I am still struggling when reading music to understand if there are
the correct beats within a measure...

If the score is notated correctly, you don't need to worry about this. Try to focus on counting the time (either out loud or silently in your head.) The only case I can think of to worry about having the correct beats per measure is proof reading a score.


Angular custom click to edit - input value to function

Question: I have a basic click to edit span field in my code, which prompts an input box and a couple of buttons:
    Your text to edit

        <input type="text" ng-bind="data.field" value="Your text to edit" />
        <button type="submit" class="btn btn-primary" ng-click="update(data.field, 'somename')"></button>
        <button type="button" class="btn btn-default" ng-click="cancelEdit()"></button>

When the user saves, the update function is called. However, the issue I'm having is that how do I send whatever text the user inputs, towards my angular logic, without settings the text values in an object at the start of the controller?
Heres an example:
http://jsfiddle.net/43GUa/1/
Basically it prints in the console: undefined + somename
How do I get that undefined to the text in the input field? I can't use ng-model since I'm unable to declare my object data(?) in my controller.
Cheers
Answer: ng-bind replaces the text of the element with the value, you want to use ng-model for two-way binding to the value of the control (fiddle):
<input type="text" ng-model="data.field"/>

Why don't you want to set the value at the start?  If you want the value to come from the HTML you should write a directive.  If you are doing this in more than one place you could write something to update a field or to call a function:
<my-editable update="data.field">Your text to edit</my-editable>

<my-editable update="updateValue($value, 'somename')">Your text to edit</my-editable>

If you really don't want to do that, you could pass $event to editField() and load data.field with the value then:
$scope.editField = function(event) {
    $scope.edit = true;
    $scope.data.field = event.target.innerText;
 };

 Your text to edit

Comment: Thanks, the event bit worked :) And it's not a matter of not wanting to, it's just the environment it's working on won't allow it that easily :)


Is it possible to define a result of a calculation as an absolute value of a number?

Question: Purplemath
What is the absolute value of a number?
The absolute value of a number n is the distance of the number n from zero. The absolute value is denoted by vertical bars as | n |, and is read aloud as "the absolute value of enn".
The absolute value of a number, being the distance of that number from zero, will always be a positive number (or zero, if you're taking the absolue value of zero). Absolute values are never negative, because absolute value only asks "how far?", not "in which direction?" This means not only that | 3 | = 3, because 3 is three units to the right of zero, but also that | −3 | = 3, because −3 is three units to the left of zero.
I am trying to get always a positive number as a result from a calculation even when it is negative I want my script to convert it to a positive number similar to using the "|" character in maths. Is that possible in Pine Language?
Comment: math.abs(number)
Answer: Check out the math namespace. There are many helper functions inclueding what you are looking for math.abs.

Absolute value of number is number if number >= 0, or -number
otherwise.
RETURNS
The absolute value of number.


How to show that this integral diverges or converges?

Question: I want to verify if the integral $$\int_1^{\infty}\ln((\exp(1/x)+(n-1))/n)dx, \;\;n>0$$
is convergent or divergent? I made some handy calculations but couldn't find any way for it. Please give me help.
Comment: Divergent. Hint: find a simple equivalent of the integrand at infinity.
Answer: Note that $e^{1/x}+(n-1)/n\geq e^{1/x}$ and so $\ln (e^{1/x}+(n-1)/n)\geq 1/x$. Hence the given integral is greater than or equal to $$\int_1^\infty\frac{1}{x}dx=\lim_{x\to\infty}\ln x=\infty$$
Comment: Your first step is a nice trick. Thank you very much.
Comment: The idea is nice but the logarithm is not the one in the question hence its lower bound does not apply, as soon as $n\gt1$. (So much for the upvotes and for the acceptance 14 minutes after the answer is posted.)
Answer: HINT: Besides to @pritman's answer; consider the integrand as $f(x)=\ln(1+\frac{e^{x^{-1}}-1}{n})$. I agree with @did that $f(x)=\ln(1+\frac{e^{x^{-1}}-1}{n})\sim\frac{1}{nx}$ when $n$ tends to infinity. Can you do the rest?


Show that $\omega \mapsto \int_A \lambda^{i\omega}d\mu(\lambda)$ is analytic

Question: Let $\alpha\in \mathbb{R}$ and $D_\alpha$ be the open horizontal strip in the complex plane $\mathbb{C}$ bounded by $\mathbb{R}$ and $\mathbb{R}-i\alpha$. Let $\mu$ be a complex measure on $[0, \infty[$ and consider the function
$$D_\alpha \ni \omega \mapsto \int_{1/k}^k \lambda^{i\omega}d\mu(\lambda)$$
where $k\in \mathbb{N}$ is fixed.
I want to show that this function is analytic.
Since every complex measure is a linear combination of finite positive measures, we may assume that $\mu$ is a finite positive measure.
Consider a sequence $\{\omega_n\}\subseteq D_\alpha$ and $\omega\in D_\alpha$ with $\omega_n \ne \omega$ for all $n$ and $\omega_n\to \omega$. It suffices to show that
$$\lim_{n \to \infty} \int_{1/k}^k \frac{\lambda^{i\omega_n}-\lambda^{i\omega}}{\omega_n - \omega}d\mu(\lambda) = \int_{1/k}^k i \operatorname{Log}(\lambda) \lambda^{i\omega}d \mu(\lambda)$$
so basically we need to justify why we can interchange limit and integral. For this, I wanted to apply the dominated convergence theorem. However, then I have to argue that there exists an integrable function $g$ on $[1/k,k]$ such that
$$\left|\frac{\lambda^{i\omega_n}-\lambda^{i\omega}}{\omega_n - \omega}\right|\le g(\lambda).$$
How do I find this function? Thanks in advance for your help/comments!
Comment: When you differentiate $\omega \mapsto \lambda^{i \omega}$, you most certainly will not expect $i\omega \lambda^{i \omega}$ as the derivative. It should rather look like $i\mathrm{Log}(\lambda) \lambda^{i\omega}$ for an appropriate branch $\mathrm{Log}$ of the complex logarithm.
Comment: There's a standard Fubini + Morera theorem trick here, right?
Comment: I don't think I'm qualified to talk about it with confidence, but in general if you can show: $$\int_\gamma\int g=\int\int_\gamma g=\int(0)=0$$For closed contours $\gamma$ and analytic $g$ then you've shown $\int g$ is analytic by the Morera theorem
Comment: @Meowdog You are of course right. Any idea how to do the estimate?
Comment: I'm thinking about it. Althouhgh I suspect that this type of estimation might not get you far...
Comment: @FShrike I am not aware of this trick? Maybe you want to post an answer?
Comment: You just need to show that the derivative is bounded above by an integrable function independent of $\omega$. Which it certainly is. But in thr holomorphic case things are much better.
Comment: @peek-a-boo Mind writing an answer?
Comment: I don't have time to write up the details for this specifically right now, but take a look at [this](https://math.stackexchange.com/a/4120068/568204) for seeing how to prove the Gamma function is holomorphic. This uses the Morera and Fubini trick mentioned above. It is relatively straightforward to adapt the argument here.
Answer: I have another suggestion: Please tell me if I made a mistake: Fix $\lambda \in [\tfrac{1}{k}, k]$. Then we can find the $k$-th derivative of
$$
g_\lambda:\omega \mapsto \lambda^{i\omega}
$$
by
$$
g_\lambda^{(k)}(\omega) := \log(\lambda)^k i^k \lambda^{i\omega}.
$$
Here $\log$ denotes the usual real (!) logarithm. So for any given $\omega \in D_\alpha$ we can write
$$
g_\lambda(z) = \sum_{\nu=0}^\infty \frac{\log(\lambda)^\nu i^\nu \lambda^{i\omega}}{\nu!}(z - \omega)^\nu
$$
where $z$ is in a small, open neighborhood with radius $\varepsilon$ of $z$ such that the power series converges. Then observe that for fixed $\omega$ and $z$ (as above) we have
$$
\int^k_{1/k} \lambda^{iz}~\mathrm{d}\mu(\lambda) = \int^k_{1/k} \lim_{n \rightarrow \infty} \sum_{\nu=0}^n \frac{\log(\lambda)^\nu i^\nu \lambda^{i\omega}}{\nu!}(z - \omega)^\nu~\mathrm{d}\mu(\lambda).
$$
Then estimate for arbitrary $n$:
$$
\left \lvert \sum_{\nu=0}^n \frac{\log(\lambda)^\nu i^\nu \lambda^{i\omega}}{\nu!}(z - \omega)^\nu \right \rvert \leq \sum_{\nu=0}^\infty \frac{\lvert \log(\lambda) \rvert^\nu \lvert \lambda^{i\omega} \rvert \varepsilon^\nu}{\nu!} = \lambda^\varepsilon \lvert \lambda^{i\omega} \rvert
$$
I am not very well versed with complex measures, but the RHS looks $\mu$-integrable to me.
So we can apply dominated convergence to find
$$
\int^k_{1/k} \lim_{n \rightarrow \infty} \sum_{\nu=0}^n \frac{\log(\lambda)^\nu i^\nu \lambda^{i\omega}}{\nu!}(z - \omega)^\nu~\mathrm{d}\mu(\lambda) = \sum_{\nu=0}^\infty \int^k_{1/k}  \frac{\log(\lambda)^\nu i^\nu \lambda^{i\omega}}{\nu!}\mathrm{d}\mu(\lambda) (z - \omega)^\nu~
$$
So around every $\omega \in D_\alpha$ we were able to write your function as a power series. So it is holomorphic.
Answer: Even more is true, and there is nothing special about your domain $D_{\alpha}$, or the endpoints $1/k$ and $k$.

Let $U\subset\Bbb{C}$ be any open set, $0<a<b<\infty$ given, and $\mu$ any positive measure on $[0,\infty)$ which assigns finite values to compact sets (like $[a,b]$). Then, the mapping $\omega\mapsto\int_{[a,b]}\lambda^{i\omega}\,d\mu(\lambda)$ is analytic as a function $U\to\Bbb{C}$ (it doesn't matter if the integration domain is any variant of $[a,b]$ with/without endpoints).

And even this is not the most general, but let's just stick to this. The first proof uses the holomorphic version of Leibniz's rule, as explained in The Gamma function is holomorphic on V. For this, fix a point $\omega_0\in U$, and a small disk $\Delta_r$, say of radius $r$, which contains $\omega_0$ and is contained in $U$ (actually any bounded open set works… nothing special about a disk). Then, we have that for any $(\lambda,\omega)\in [a,b]\times \Delta_r$,
\begin{align}
|\lambda^{i\omega}|&=|e^{i\omega\log\lambda}|\leq e^{|\omega\log\lambda|}\leq e^{(|\omega_0|+r)\sup\limits_{\lambda\in [a,b]}|\log\lambda|}<\infty.
\end{align}
In words, $\lambda^{i\omega}$ is uniformly bounded on $[a,b]\times \Delta_r$, and since $\mu$ assigns finite values to compact sets, we have found an integrable upper bound. Thus, by the Leibniz integral rule stated in the link, the claim follows. Also, note that there are no issues with branch cuts; here I'm just using the usual logarithm on the positive real axis.
Let's say we didn't know the Cauchy inequalities from complex analysis. Then, what we'd have to do is show that for each point $\omega_0\in U$, there is an open neighborhood $\Delta$ of $\omega_0$ in $U$, such that the partial derivative $\frac{\partial}{\partial \omega}(\lambda^{i\omega})=i(\log\lambda) \lambda^{i\omega}$ has an upper bound $g(\lambda)$, which is independent of $\omega\in \Delta$, and such that $g$ is integrable on $[a,b]$. Well, once again, by taking $\Delta$ to be a bounded open set, and by noting that $\lambda$ varies in an interval $[a,b]$ strictly away from the origin and infinity, we see that we can bound it above uniformly by a constant $C$ (depending only on the bounded set $\Delta$, and $a$ and $b$), and since constants are $\mu$-integrable, by the Wikipedia version, we can apply Leibniz's rule safely.
The key thing you're missing is that the difference quotient can be bounded by the partial derivative using the mean-value theorem (see Wikipedia for some details). Once you take this into account, you'll arrive at the argument of the previous paragraph. But like I said, in the holomorphic case, Cauchy's inequalities are wonderful and they allow us to seemingly weaken the hypothesis further, so we have fewer things to verify.
Comment: Thanks for your answer (and sorry for the late reply)! The wikipedia version you mention is only for real functions, isn't it? There the proof is based on mean value theorem, which doesn't hold in our context. Maybe the wikipedia version is still true though in the complex case?
Comment: @Andromeda you don't need the mean-value theorem in the form of an equality (and indeed, that is false for functions whose target space is not $\Bbb{R}$), but all you need is the mean-value inequality, which holds very generally for functions with values in any Banach space.


conditional probability with independent and non independent events

Question: I need to clear up some confusion on conditional probability and independence.

Two events are said to be independent if the probability of two events equal their product.

So
$$P(B\mid A)=\frac{P(A \cap B)}{P(B)} = \frac{P(A)P(B)}{P(B)}=P(A),$$ correct?
Based on that i have a problem where i need to find it's conditional probability:
probability of $P_c(B)$ where the event of $B=\{\text{no two people are born in the same month}\}$ and event $C= \{\text{exactly three people were born in the summer of june, july august}\}$ and there are 9 people involved.
for
$P(B)$ I got $=\frac 1{12} \frac 1{11} \frac 1{10} \frac 19 \frac18 \frac17 \frac 16 \frac 15 \frac 14 =\frac 1{79833600}$
$P(C)=\binom 9  3 \left(\frac 3{12}\right)^3\left(\frac 9{12}\right)^6=\frac{15309}{65536}$
so
$P_c(B)=P(C\mid B)=\frac{P(B \cap C)}{P(C)} = \frac{P(B)P(C)}{P(C)}
    =\frac{(1/79833600)(15309/65536)}{15309/65536}$
This is not correct because this event is not independent. Therefore $P(C \cap B)$ does not equal $P(C)P(B)$. I can definitely see that by reading the events, it makes sense, but using the formula to check yields a different result:
$P(C\mid B)=\frac{P(C)P(B)}{P(B)} = P(C)$ then $((1/79833600) (15309/65536))/(15309/65536) = (1/79833600)$ which is $P(C)$, which says this is independent.
To be further confused my professor used $P(C\mid B)=\frac{P(C)P(B)}{P(B)} = P(B)$ to check whether it is independent or not. I thought you divide by $P(B)$ not $P(C)$. He did get the probability of $P_c(B)$ using $P_c(B) = \frac{P(B \cap C}{P(C)}$ but I thought that wasn't the correct formula if they are not independent. It seems like he did everything backwards from me which puzzles me.
If it is non independent what is the formula?
Answer: The definition of $B$ and $C$ independent is $P(B \cap C) = P(B) P(C)$.  If
$P(B) \ne 0$ this is equivalent to $P(C|B) = P(C)$, and if $P(C \ne 0)$ it
is equivalent to $P(B|C) = P(B)$.
If the events are not independent, you can't use $P(B) P(C)$ to calculate
$P(B \cap C)$.  If you happen to know $P(B|C)$, you can say $P(B \cap C) = P(B|C) P(C)$, and similarly if you happen to know $P(C|B)$ you can say $P(B \cap C) = P(C|B) P(B)$.  If you don't know either of those, you have to do something else.
In your example, $B \cap C$ means exactly one person was born in June, one was born in July, and one was born in August.  So the number of ways to do that with $9$ people is ...
Comment: zero, so they are not independent. From the information i provided we are not provided P(C|B) or P(B|C) so how do i figure out the conditional probability based on the fact that they are not independent? Also just to be sure, the only way to figure out whether something is independent is by thinking about the actual events? There are no formulas to check?  (cont.)
Comment: I used this website as reference(Independence): [Conditional probability and the product rule](http://www.cs.uni.edu/~campbell/stat/prob4.html) and it checks for independence by $(((P(C)*P(B))/P(B)) =P(C)$ and my professor checked by $Pc(B)=P(B)$ which is actually the opposite: $P(C|B)=(((P(C)*P(B))/P(C)) =P(B)$, assuming you can check for independence this way are both ways okay to check (I think that's what you mentioned previously). Does this mean my professor was actually looking for $P(B|C)$ instead of $P(C|B)$?


How to skip an index Java?

Question: I need help with skipping a specific index in an array. Say I divided them with String.split() and I wanted everything to print out except for the first string, how would I accomplish this? I've been trying to find for an answer for an hour and haven't found anything, please help.
import java.util.Scanner;

public class test {
  public static Scanner Link = new Scanner(System.in);

  public static void main(String[] args) {
      String Zelda = Link.nextLine();
      String[] str = Zelda.split("\\s");
      System.out.println(str);
  }
}

Comment: If you wanted to print the string minus the specific index, you could: (1) declare a stringbuilder (2) iterate through str array via for loop, calling your stringbuilder.append( str[i] ) when i != 0 (or i != whatever index you want to skip), then (3) print the stringbuilder.toString()
Answer:
i wanted everything to print out except for the first string

int first = 0;
for(int i=0; i<str.length; i++)
{
   if(i!=first)//except for the first string
   System.out.println(str[i]);
}

OR
Arrays.asList(str).subList(index, str.length);

List#subList() doc
Answer: the followong code can print what you want... you can skip any index of your choice as long as it exists in between 0 and your string array's length-1.
String Zelda = "akash:kumar:coder"; // test string
String[] str = Zelda.split(":");
for(int i = 0; i<str.length; i++)
   {
    if(i==1) //Index you want to skip
    {
      continue;
    }
    System.out.println(str[i]);
  }

For more on continue statement... see this... Branching Statements in Java
Answer: Use copyOfRange to get sub array:
 str = Arrays.copyOfRange (str, 1, str.length);
 System.out.println(str);

Answer: Try this:
String[] str = Zelda.split("\\s",-1);
System.out.println(Arrays.copyOfRange(str, 1, str.length);

Notice that Arrays.copyOfRange requires jdk 1.6 or higher. If you use java 5 you could use System.arrayCopy instead.

How to skip an index Java?


I would like to find the difference of each row, from the first row As Alias

Question: To clarify my Title
I would like to tabulate how far behind the leader, each successive finisher is from 1st place as shown in my table below.
Finish | Points | Points Behind
   1   |  102   |
   2   |   92   |   10
   3   |   82   |   20
   4   |   71   |   31
   5   |   61   |   41
   6   |   50   |   52
   7   |   40   |   62
   8   |   30   |   72
   9   |   20   |   82
  10   |   10   |   92

 Select
  snpc_stats.gamedetail.Finish,
  snpc_stats.gamedetail.Points,
  some code I don't know As 'Points Behind'
 From
  snpc_stats.gamedetail
 Where
  snpc_stats.gamedetail.GamesID = 113

Comment: What happens when you have ties?
Answer: You can get the points from first finish and do a cross join with rest of the table.
SQL Fiddle
select  gd.Finish, gd.Points,
        t.Points-gd.Points as PointsBehind
from gamedetail gd
cross join ( select max(Points) from gamedetail where Finish =1) t

Comment: I would suggest `max(Points)` or `limit 1` in case there are ties.


No content but empty row outputted by view

Question: I have a view as follows:

Display: Master
Format: Unformatted list
Fields: Content: Images
Filter criteria: Content type, published
Contextual filter: Content: Nid with 'Provide default value' set to 'Content ID from URL'

The view is placed on the node using Panels and Panalizer modules.
The node in question had no images uploaded to the image field but the view is outputting an empty row as follows:

I have checked and unchecked the 'Count the number 0 as empty' and ' Hide if empty' on the 'Content: Images' field but the view still shows.
How can I hide the view (by removing this empty row) if there are no images on a node?
Happy to attach any additional information you require to this post. Thanks.
Comment: Add `hide if empty` in each fields.
Comment: @SumitMadan as per above, I've already done this Sumit
Comment: Actually I have also faced same problem many times. What I actually do just add a filter `nid not empty`.
Comment: @SumitMadan There's no option to set Nid as not empty when adding it as a filter. Additionally, I believe the Nid will exist whether there are images or not because of the contextual filter.
Comment: May be `Nid != ''`.
Answer: You need to set a filter value on the image field.
Open your view, then edit as follows:
Enable 'Use Aggregation'.
Make sure that the image field is aggregating on 'Group Result together', using Group column 'Entity ID'. Sometimes views gives an error here, so just remove and re-add the image field with these settings.

Add a Filter criteria using 'field_image:fid', set its aggregation to COUNT, and choose the operator 'Is greater than' with value 0.
You might have to remove all of your sort criteria and re-add them as switching on aggregation mid stream can cause issues with sorting.
Basically, what you have done is to do a count on the image primary key (fid) for each node, and if the count is 0 to exclude the record from the result.
This should work for an image field that has either a single, or multiple values.
I you are uncomfortable working with aggregation, then have a look at the Field Count Formatter module. It adds a views field that simply count the number of values contained in a multi-value field. I would imagine it providing a filter in views as well.
Comment: Worked perfectly. Thanks. And yes, it's really important to either re-save or re-add your fields otherwise this won't work.
Answer: May be the content is not NULL, but it is equal to '' (empty string) or ' ' (space)
Try to add a filter on field "Images" and test for lenght >0 (or 1)


Raspberry Pi Login Error - Login incorrect

Question: I have a Raspberry Pi running raspbian that I can no longer login to. I have been using the "pi" user without any problems up to this point. However, when it asks for a login and I input "pi", I get an error that says "Login Incorrect" and am asked for a login again. This happens at the command line as I was working on setting it up as a headless file server.
This doesn't happen if I give it the username "root". If I try to login as "root", it asks for a password but no password seems to work. I tried looking up the default "root" password and found that the "root" user is not enabled on the pi.
Strangely, if I try to access the pi via ssh (using PuTTY), I can login as the user "pi". However, as soon as I do the connection is broken with the error: "Server unexpectedly closed network connection".
What could be happening to cause this? Do I have any way of fixing the problem if I can't login?
Some background as to what might have caused this:
I was working on setting up Deluge with it's Web UI. However, deluge doesn't have init scripts so I was following this guide to create the init scripts. My pi didn't have "systemctl" installed so I started following this guide to install "systemctl". I had a problem after editing "/boot/cmdline.txt" which caused my pi to boot into safe mode. I removed my edits and the pi booted normally again.
I don't know if any of my above attempts could have caused my login problems but essentially the only thing I was doing was trying to setup deluge when I stopped being able to login.
Answer: Login as root and type:
<code>passwd pi
</code>
And that will allow you to set a new password for user pi. if not, re install raspbian to your SD card. Works everytime.
Hope this helps.
Answer: I'm not sure why you're not able to login but I would suggest using the Deluge client instead of the WebUI as it has more features - you can get it from here
You can find a good step-by-step tutorial of how to use Deluge with a client here
In the meantime I might be inclined to start from scratch with a fresh Wheezy install instead of wasting too much time on it..
Comment: The main reason I was planning on using the WebUI is so that my wife can access it on her phone. She uses her phone much more than any computer. I have done a few other things with the pi, such as setting up a file and print server so I was hoping to not have to start fresh but I will if I have to. Thanks for the help.


retrieve footnote of word file with openxml

Question: How can retrieve all footnotes of a word file in c# using open xml, i know that we can retrieve the paragraphs with some things like this:
IEnumerable<Paragraph> paragraphs = mainPart.Document.Body.OfType<Paragraph>();

but when i test it for footnotes i just get the null while i know there is some footnotes in my word file.
i have just find this pages to help me on this problem, but they didn't help me:
Footnotes constructor
how can i get all the footnotes and save theme in a list.
Answer: Example to get the footnotes:
FootnotesPart footnotesPart = wordDoc.MainDocumentPart.FootnotesPart;
if (footnotesPart != null)
{
    IEnumerable<Footnote> footnotes = footnotesPart.Footnotes.Elements<Footnote>();
    ...
}


Table view: "Hide Empty Column" checkbox doesn't seem to work

Question: I've created a view, formatted as a table.
I'm trying to hide empty columns – so, in the table settings, I've checked the "Hide Empty Column" checkbox for most of the table columns.
However, this doesn't seem to have any effect – these columns are still included in the rendered table, with empty <td>s.
I expect this checkbox to hide the column entirely when all data cells contain an empty value. Am I understanding this correctly?
This certainly seems to be how it worked in Drupal 7. (I'm converting an existing D7 site to D8 – and this is how the table columns were hidden on the D7 site.)
Is there anything I should check which might be preventing this from working as expected?
Thanks.
Answer: Someone elsewhere suggested that I disable Twig debugging. This fixed this issue. Weird.


LIKE operator MySQL doesn't work

Question: I tried to make search using LIKE operator:
SELECT author_id, header, text FROM blog_u.posts WHERE text LIKE '%Samsung%';

It works with latin symbols but doesn't work with russian
SELECT author_id, header, text FROM blog_u.posts WHERE text LIKE '%Проверка%';

My database in utf-8. Help me pls
Comment: Can you elaborate?  Appears to be working for me in this fiddle: http://sqlfiddle.com/#!2/49cc2/1
Comment: My problem has been in my Servlet encoding, but thanks anyway
Answer: As a follow-up to my comment, I don't think you're having an issue with LIKE.  However, you have to make sure what you're searching for have the equivalent ascii values.
For example, consider this:
select * from posts where Text Like '%Проверка%';
select ascii('p');
select ascii('р');

The 'p' looks identical in both, but the ascii version is indeed different -- one works, and the other doesn't.  I copied the p in your above statement vs. just typing a p on my keyboard.
Here is a Fiddle to demonstrate.

LIKE operator MySQL doesn't work


Qual a diferença ente getRating() e getProgress()?

Question: Segundo a documentação o getProgress retorna o level de progresso do rating bar, enquanto que o getRating retorno a quantidade de estrelas do rating bar.
Então em termos gerais o getProgress retorna um valor double enquanto que o getRating retorna um valor inteiro?
Answer: getProgress() deve ser usando quando usa um ProgressBar e getRating() quando usa um RatingBar.
O mesmo se aplica a setProgress() e setRating().
TL;DR
getProgress() é um método da classe ProgressBar da qual RatingBar deriva(extends) indirectamente através de AbsSeekBar.
O propósito do ProgressBar é indicar visualmente a "quantidade" parcial, a que já decorreu, de um qualquer processamento.
É usada uma representação visual cuja dimensão é proporcional à "quantidade" decorrida.
Essa dimensão é calculada relacionando o valor mínimo e máximo do valor e a dimensão mínima e máxima do ProgressBar.
Por padrão esses valores são 0 e 100, podendo ser alteradas através dos métodos setMin() e  setMax().
O valor da "quantidade" decorrida do processo é atribuída por setProgress() e obtida por getProgress() que, ao contrário do que diz, retorna int.
O uso dos valores 0 e 100 proporciona que a "quantidade" decorrida seja indicada como uma percentagem.
Por outro lado, o RatingBar é usado para representar uma classificação, usando estrelas.
O número de estrelas a mostrar pelo RatingBar é atribuído por setNumStars().
Em vez de um int, que é usado para indicar o progress, é usado um float para indicar o ranting.
O uso de um float, em conjunto com a indicação de um step, permite que o ranting seja representado pelo preenchimento parcial da estrela.
Assim, ao contrario do que diz, o método getRating() retorna float.
Note que o valor retornado por getRating() pode não ser igual ao número de estrelas preenchidas. Esse número depende do valor máximo para o rating, do step e do número de estrelas do RatingBar.
Apesar dos métodos setProgress(), getProgress() e setMin() estarem disponíveis não devem ser utilizados quando se usa o RatingBar.
Este é um bom exemplo de um caso em que não deveria ter sido utilizada herança.
Comment: "Este é um bom exemplo de um caso em que não deveria ter sido utilizada herança." Disse tudo!
Answer: É o contrário:
O getProgress() retorna um valor inteiro, enquanto o getRating() retorna um float.
A diferença
Apesar de o RatingBar ser uma subclasse do ProgressBar o getProgress geralmente é usado para recuperar a porcentagem (int) de um ProgressBar, enquanto getRating é usado para recuperar a qualificação de estrelas atual (float) de um RatingBar.


How can prove that $\sum_{n=1}^{\infty }\frac{\zeta (2n)}{4^{n-1}}(1-\frac{1}{4^n})=\frac{\pi }{2}$

Question:
$$\zeta (2)(1-\frac{1}{4})+\frac{\zeta (4)}{4}(1-\frac{1}{4^2})+\frac{\zeta (6)}{4^2}(1-\frac{1}{4^3})+...=\frac{\pi }{2}$$

The WolframAlph couldn't recognize the closed-form which is $\pi/2$ when I gave the series,

so I used the WolframAlph again to compute many terms of infinite series.

I think that the WolfarmAlph cannot say the value is $\pi/2$,So we need to prove it.
Comment: Not that it helps you, but if you subtract the series from $\pi/2$ W|A gives zero.
Answer: Since,
$\begin{align}\sum_{k=1}^\infty\zeta(2k)\,x^{2k} &= \sum_{k=1}^\infty\sum_{n=1}^\infty\frac{x^{2k}}{n^{2k}}\\
&=\sum_{n=1}^\infty\frac{\frac{x^2}{n^2}}{1-\frac{x^2}{n^2}}\\
&=\sum_{n=1}^\infty\frac{x^2}{n^2-x^2}\\
&=-\frac{x}{2}\sum_{n=1}^\infty\left(\frac{1}{x+n} + \frac{1}{x-n}\right)\\
&=-\frac{x}{2}\left(\pi\cot(\pi x)-\frac1x\right)\\
&=\frac{1}{2}\left(1-\pi x\cot(\pi x)\right)
\end{align}$
Plug in the particular cases $x = \dfrac{1}{2}$ and $x = \dfrac{1}{4}$ in the series.
Answer: We have:
$$\zeta(2n)\left(1-\frac{1}{4^n}\right)=\sum_{k=0}^{+\infty}\frac{1}{(2k+1)^{2n}}\tag{1}$$
hence:
$$\sum_{n=1}^{+\infty}\frac{\zeta(2n)}{4^{n-1}}\left(1-\frac{1}{4^n}\right)=4\sum_{n=1}^{+\infty}\sum_{k=0}^{+\infty}\frac{1}{(4k+2)^{2n}}=4\sum_{k=0}^{+\infty}\frac{1}{(4k+2)^2-1}\tag{2}$$
and the result follows from:
$$\sum_{k=0}^{+\infty}\frac{1}{(4k+2)^2-1}=\frac{1}{2}\sum_{k=0}^{+\infty}\left(\frac{1}{4k+1}-\frac{1}{4k+3}\right)=\frac{1}{2}\arctan 1 = \color{red}{\frac{\pi}{8}}.\tag{3}$$
Answer: $$\zeta(2n) = \frac{1}{\Gamma(2n)}\int_{0}^{+\infty}\frac{x^{2n-1}}{e^x-1}\,dx $$
so we have:
$$\sum_{n=1}^{\infty}\frac{\zeta(2n)}{4^{n-1}} =\sum_{n=1}^{\infty}\frac{\zeta(2n)}{2^{2n-2}}= 2\int_{0}^{\infty}\frac{\sinh(x/2)}{e^x-1}\,dx =\int_{0}^{\infty}e^{-x/2}\,dx = 2$$
also we have :
$$\sum_{n=1}^{\infty}\frac{\zeta(2n)}{4^{2n-1}} = \int_{0}^{\infty}\frac{\sinh(x/4)}{e^x-1}\,dx =\frac12\int_{0}^{\infty}\frac{1}{e^{\frac{3x}{4}}+e^\frac{x}{4}}\,dx =2-\frac{\pi}{2}$$
last integral we can slove using $u=e^\frac{x}{4}$
putting all together :
$$\sum_{n=1}^{\infty}\frac{\zeta(2n)}{4^{n-1}} -\sum_{n=1}^{\infty}\frac{\zeta(2n)}{4^{2n-1}} =\sum_{n=1}^{\infty}\frac{\zeta(2n)}{4^{n-1}}(1-\frac{1}{4^{n}})=\frac{\pi}{2}$$


JQuery show hide multiple DIVs from menu and menu within DIV

Question: I'm new to JQuery. I'm trying to show and hide multiple divs. I have a menu showing A,B,C. When I click A, the div A1 appears. Div A1 has a menu within it showing 1, 2, 3 and so on. When I click 2 in this menu, A1 disappears and A2 appears. When I click B, the currently visible div disappears and B1 appears. B1 has a menu showing 1, 2, 3. When you click 2, B1 is replaced by B2. And so on - I think you get the picture.
Here is my html:

A B C

A1

1 2 3

A2

1 2 3

A3

1 2 3

B1

1 2 3

B2

1 2 3

B3

1 2 3

C1

1 2 3

C2

1 2 3

C3

1 2 3

And here's the code to go with it:
$(document).ready(function() {
$('div[class^=work-]').hide();
$(".A").click(function() {
    $("div[class^=work-]").hide();
    $("div[class^=work-A-link1]").fadeIn();
});
$(".B").click(function() {
    $("div[class^=work-]").hide();
    $("div[class^=work-B-link1]").fadeIn();
});
$(".C").click(function() {
    $("div[class^=work-]").hide();
    $("div[class^=work-C-link1]").fadeIn();
});
$('[class^=link]').click(function() {
    $('div[class^=work-]').hide();
    var $this = $(this);
    var x = $this.attr("className");
    $(".work-A-" + x).fadeIn();
    return false;
});
});

This code only works with the div "A", and I'd have to number each div individually, which seems really inefficient. I've tried using split() to gather up the class names and target the respective divs, but I don't have the coding skills. Is there an elegant solution to this?
Answer: I have a different way if you can split up the classes in your HTML?
e.g. the divs which are

can you change them to?

if so this appears to work.. will add a fiddle a bit later added fiddle
$('.work').hide();
   $(".thework a").click(function() {
      var letter = $(this).attr("class"); // link class is also in work class
         $(".work").hide(); // hide all work class
         $(".work.link1."+letter).fadeIn(); //show the relevant work class
   });

   $('.work a').click(function() {
     var pLink = $(this).attr("class"); //gets the link# class
     var pLetter = $(this).parent().attr("class").split(' ')[1]; //gets the relevant letter if letter is 2nd class in array  index 1

     if ($(this).parent().hasClass(pLink)) {
        //do nothing
     } else {

     $(this).parent().hide();
     $("." + pLetter + "." + pLink).fadeIn(); // produces the .letter.link# CSS selector required
   }

   return false;
});

Working Example : Here
Comment: @clairesuzy: That works perfectly. Thank you very much for your time and your elegant coding skills!
Comment: @clairesuzy: Gah! Now that I have put content into the divs (images and text between  tags), the click function has rendered them 'active' and an inadvertent click makes the div disappear (they fulfill the hide but not the fadeIn requirements). If I give the content a class, can I add a statement into the if/else so that a click does nothing?
Comment: would need to a sample of your new code, perhaps stick it in a [**jsfiddle**](http://jsfiddle.net/) for brevity.. my code should only activate on the click of a link, perhaps you've changed `$('.work a').click(function()` or there are more links in your content, if the latter you will need to give the "activating" link another class to target it more specifically
Comment: [**here's an updated one**](http://jsfiddle.net/clairesuzy/bxsFC/), you had too much hiding attached to your new divs `faber` and `wandw` they don't need 'hide on click' actions, the about and contact wrappers would never be open when your sub divs (`.work`) are open, as you've already had to close them to get to the "work00" wrapper
Comment: the main problem was that you had your `wandw` and `faber` divs closing themselves on click - `"div[class^=work]").hide();` - both those divs are also class `work`
Comment: @clairesuzy: Bear with me, I'm trying to digest that. So all my extra bits have broken your code? Ah. The fiddle you linked to [link](http://jsfiddle.net/clairesuzy/bxsFC/) still behaves broken to me, though. Thanks for you patience.
Comment: it's OK no hurry, I'm nearly off to bed though! ;) - No your bits didn't break my code, they were just doing extra things by themselves, e.g. when you had `div[class^=work]").hide();` attached to `faber`, `faber` is already `.work` too so by clicking ion it it was hiding itself, what's not working the way you want in the new fiddle?
Comment: oh shoot I linked to your original one!! dohh.. need to refind my one .. it' time for bed defintiely.. back it a minute -  [here try this one](http://jsfiddle.net/clairesuzy/NSB38/).. sorry, no wonder it didn't make sense LOL!
Comment: @clairesuzy: That works brilliantly, thank you. I'll have to get my head around what you did in the morning. Good night!
Comment: @clairesuzy: Now I see - lots of schoolboy howlers in my code. Thanks for clearing that up, and thanks for your elegant solution.
Answer: You could do it like this:
$(document).ready(function() {
   $('div[class^=work-]').hide();
   var letters = ["A", "B", "C"]; //Put all posible letters here
   for(var i in letters){
      var letter = letters[i];
      $("."+letter).click(function() {
         $("div[class^=work-]").hide();
         $("div[class^=work-"+letter+"-link1]").fadeIn();
      });
   }
   $('[class^=link]').click(function() {
      $('div[class^=work-]').hide();
      $(this).parent().fadeIn(); //This does the trick!!
      return false;
   });
});

Hope this helps. Cheers
Comment: Many thanks for doing this - unfortunately it doesn't work for me. Clicking 'A', 'B', or 'C' shows only 'C1'; also the links within 'C1' are inactive.


How to do form validation with Django?

Question: This is a simple form that is present in my template(comment.html).
<form id="my_form" action="{% url 'a' pk=id %}" method="POST">
            {% csrf_token %}
            <input id="in" required minlength="5" name="message" type="text">

            <button id="click" title="add your comment" type="submit">Comment</button>
</form>

As you can see there is an input tag inside form whose name is "message".My problem is that when user get this page on his/her computer as a response means they can simply see this form code on their browser. Let assume a user changed the value of the name attribute of input tag and submit the form then I don't get the value of 'message'.
Can you tell me how i can write a view to validate my form on the server-side? So that my website stays safe from a malicious user and from a hacker?
Answer: Let assume a user changed the value of the name attribute of input tag such as:
    <input id="in" required minlength="5" name="message" type="text">

to:
    <input id="in" minlength="500" name="hacked_message" type="text">

Yes, you will not get the value of message for that particular user, why would you want someone's message if they are malicious ?
But you will get the value of message for other users who don't manipulate their code.
Comment: Then how is the stack-overflow is working? When I change the name attribute of the input tag in the stack-overflow site in their comment section my comment get published, how this thing work I want to know.
Comment: ok did you change the comment name by doing inspect element and changing name of this textarae ?
Comment: yes you are right. i did my comment got saved but how.
Comment: because stack-overflow, is not depending on name attribute maybe, maybe they use #id instead. if you look, in the console(XHR tab). there will a post request for each comment made, click on Params, it will show what excatly was send to server. this is mainly done using ajax,
Answer: You can use the django forms.
Here you have the link for the documentation about that :
Django Forms
Why use django forms ?
Because you have methods that you can use in your view like this :
form.is_valid()

Quick example here:
form validation
And here, your have more informations about is_valid() method:
is_valid() doc
Comment: is_valid() method only valid form data, not form attributes and their values .thanks for the answer.

How to do form validation with Django?


Fazer validação reativa no angular com formgroup

Question: Estou tentando colocar uma mensagem de erro no template, porém não estou conseguindo chegar no validator que criei.
Esse é o validator:
  criarFormularioDeUsuario() {
    this.formularioLogin = this.fb.group({
      email: ['', Validators.compose([Validators.required, Validators.email])],
      password: ['', Validators.compose([Validators.required])],
    });
  }

No template eu tentei:
  <mat-form-field class="full-width">
    <input [errorStateMatcher]="matcher" formControlName="email" matInput placeholder="Email">
    <mat-error *ngIf="formularioLogin.email.errors.email">
        Você precisa entrar com um e-mail válido.
    </mat-error>
  </mat-form-field>

Também tentei com hasError:
<mat-error *ngIf="formularioLogin.hasError('email') || formularioLogin.hasError('required')">

Também não deu certo.
Answer: Primeiro vc não precisa do compose.
this.formularioLogin = this.fb.group({
      email: ['',[Validators.required, Validators.email]],
      password: ['', [Validators.required]],
});

Tenta:
<mat-error *ngIf="formularioLogin.get('email').errors">
        {{formularioLogin.get('email').errors|json}} //aqui vc vai ver os erros que estao dando
</mat-error>

Ou então

    Email é requirido.


Imagem desaparece depois da animação + window resize

Question: Estou a construir um menu para o meu blog, encontrei alguns códigos na net, e estou a tentar implementar um deles. O problema é o seguinte: a imagem (logo) desaparece do menu (header) quando eu faço o seguinte:

encolho a janela para tamanho de um telemóvel
Abro o burger menu, volto a fechar
expando a janela

e puff... não tenho o logótipo. O que me está a escapar? Tenho em baixo o código:
CSS
     /* Interface - Mobile */

    .fa:before {
    font-family: FontAwesome;
    }

    header .bgMenu {
     height: 80px;
    background-color: #fff;
    box-sizing: border-box;
    text-align: right;
    }

header.fixedMenu {
    position: fixed;
    width: 100%;
}

.navMenu {
  z-index: -1;
  position: relative;
}

.linksMenu {
  display: none;
  list-style: none;
  margin: -4px 0 0;
  padding: 0;
}

.linksMenu.showMenu {
  display: block;
  background-color: #148dcd;
  padding-top: 2em;
  margin-top: -2.25em;
}

.linksMenu a {
  color: #ECEFF1;
  text-align: left;
  font: 1em Oswald;
  font-family: 'Exo', sans-serif;
  padding: .8em;
  display: block;
  text-decoration: none;

}

.linksMenu a:before {
  margin: 0 1em 0 .25em;
}

.linksMenu li:nth-child(1) a {
  background-color: rgba(0,116,166,.4);
}

.linksMenu li:nth-child(2) a {
  background-color: rgba(0,116,166,.55);
}

.linksMenu li:nth-child(3) a {
  background-color: rgba(0,116,166,.7);
}

.linksMenu li:nth-child(4) a {
  background-color: rgba(0,116,166,.85);
}

.linksMenu li:nth-child(5) a {
  background-color: rgba(0,116,166,1);
}

.burgerMenu {
  position: relative;
  width: 50px;
  height: 50px;
  cursor: pointer;
  background-color: #148dcd;
  border-radius: 50%;
  display: inline-block;
  margin: 15px;
}

.burger {
  top: 22px;
  right: 10px;
  opacity: 1;
}

.burger::before {
  top: 10px;
  content: "";
  display: block;
}

.burger::after {
  bottom: 10px;
  content: "";
  display: block;
}

.burger::after, .burger::before, .burger {
  transition: all .3s ease-in-out;
  -webkit-transition: all .3s ease-in-out;
  background-color: #fff;
  border-radius: 2px;
  width: 29px;
  height: 5px;
  position: absolute;
}

/* Shade from Burger Menu */

.bgShade {
  background-color: rgba(0,0,0,.75);
  height: 100vh;
  position: fixed;
  top: 0;
  width: 100vw;
  visibility: hidden;
  transition: .25s linear;
  opacity: 0;
}

.bgShade.showShade {
  opacity: 1;
  visibility: visible;
}

.bgShade.hideShade {
  opacity: 0;
  visibility: hidden;
}

/* Scroll locked */

body.bodyStopped {
  overflow: hidden;
}

/* Transition from Burger menu to X */

.burgerMenu.showMenu .burger::after{
  transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
  bottom: 0px;
}

.burgerMenu.showMenu .burger::before{
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  top: 0px;
}

.burgerMenu.showMenu .burger{
  background: rgba(111,111,111,.0);
}

/* Interface - Desktop */

@media screen and (min-width: 768px) {

  header .bgMenu {
    background-color: rgba(20,141,205,1);
  }

  div.burgerMenu {
    display: none;
  }

  .navMenu {
    z-index: 0;
  }

  .linksMenu {
    display: block;
    text-align: center;
    box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
  }

  .linksMenu li {
    display: inline-block;
  }

  .navMenu .linksMenu li a {
    background-color: transparent;
    color: #0c547b;
    font-family: 'Exo', sans-serif;
    font-weight:bold;
    font-size: 1.3em;
    padding: 33px 1.2em 24px .8em;
    transition: .25s;
  }

  .navMenu .linksMenu li a:hover {
    color: #fff;
  }

  .navMenu.bounceOutUp {
    animation-name: unset;
  }

  .figureProfile.animated.zoomInUp img {
    max-width: inherit;
    width: 360px;
  }

  .bgShade.fadeIn,
  .bgShade.fadeOut {
    display: none;
  }
}

JQuerry
// Burger Menu transitions
var count = 0;
$(".burgerMenu").click(function() {
    count++;
    // Var to identify even or odd click
    var isEven = function(someNumber) {
        return (someNumber % 2 === 0) ? true : false;
    };
    // Odd clicks
    if (isEven(count) === false) {
        $("header").addClass("fixedMenu");
        $(".burgerMenu").addClass("showMenu");
        $(".linksMenu").addClass("showMenu");
        $(".navMenu").removeClass("bounceOutUp");
        $(".navMenu").addClass("bounceInDown");
        $(".bgShade").removeClass("hideShade");
        $(".bgShade").addClass("showShade");
        $("body").addClass("bodyStopped");
    }
    // Even clicks
    else if (isEven(count) === true) {

        //$("header").removeClass("fixedMenu");
        $(".burgerMenu").removeClass("showMenu");
        $(".navMenu").removeClass("bounceInDown");
        $(".navMenu").addClass("bounceOutUp");
        $(".bgShade").removeClass("showShade");
        $(".bgShade").addClass("hideShade");
        $("body").removeClass("bodyStopped");
    }
});

// Burger menu without one extra click
$('.linkHeader').click(function() {
    count++;
});

HTML

Início

Artigos

Cursos

Ferramentas

Sobre

Se quiserem ver por vocês é aqui: http://www.doveloper.com/
Answer: Consegui resolver o problema usando este "desvio":
    $(window).on('resize', function(){

    if ($(window).width() < 768) {
       $("#logo_mobile").css("display","block");
        $("#logo_desktop").css("display","none");

    }
    else {
          $("#logo_mobile").css("display","none");
        $("#logo_desktop").css("display","block");
    }

});

Assim garanto que a imagem volta a aparecer. Teoricamente isso quase nunca vai ser executado pois o utilizador geralmente não muda o tamanho da janela.
Answer: O problema é que você está adicionando a classe .showMenu ao elemento $(".linksMenu") quando o burger é aberto e não está removendo essa classe quando o burger é fechado. Desta forma, estava dando conflito nos elementos e deixando a div da logo escondida.
A solução é adicionar a linha abaixo no script, dentro do bloco else if (isEven(count) === true) { para remover a tal classe:
$(".linksMenu").removeClass("showMenu");

Outra coisa, é fazer uma função que feche o burger automaticamente (caso esteja aberto) quando o tamanho da janela for maior ou igual a 768px (mesmo tamanho referido no CSS em @media):
$(window).on("load resize", function(){
    if(window.innerWidth >= 768){
        $(".linksMenu").removeClass("showMenu");
        if($("nav.navMenu").hasClass("bounceInDown")){
            $(".burgerMenu").trigger("click");
        }
    }
});

// Burger Menu transitions
var count = 0;
$(".burgerMenu").click(function() {
    count++;
    // Var to identify even or odd click
    var isEven = function(someNumber) {
        return (someNumber % 2 === 0) ? true : false;
    };
    // Odd clicks
    if (isEven(count) === false) {
        $("header").addClass("fixedMenu");
        $(".burgerMenu").addClass("showMenu");
        $(".linksMenu").addClass("showMenu");
        $(".navMenu").removeClass("bounceOutUp");
        $(".navMenu").addClass("bounceInDown");
        $(".bgShade").removeClass("hideShade");
        $(".bgShade").addClass("showShade");
        $("body").addClass("bodyStopped");
    }
    // Even clicks
    else if (isEven(count) === true) {

        //$("header").removeClass("fixedMenu");
        $(".burgerMenu").removeClass("showMenu");
        $(".linksMenu").removeClass("showMenu");
        $(".navMenu").removeClass("bounceInDown");
        $(".navMenu").addClass("bounceOutUp");
        $(".bgShade").removeClass("showShade");
        $(".bgShade").addClass("hideShade");
        $("body").removeClass("bodyStopped");
    }
});

$(window).on("load resize", function(){
 if(window.innerWidth >= 768){
        $(".linksMenu").removeClass("showMenu");
  if($("nav.navMenu").hasClass("bounceInDown")){
   $(".burgerMenu").trigger("click");
  }
 }
});

// Burger menu without one extra click
$('.linkHeader').click(function() {
    count++;
});
/* Interface - Mobile */

    .fa:before {
    font-family: FontAwesome;
    }

    header .bgMenu {
     height: 80px;
    background-color: #fff;
    box-sizing: border-box;
    text-align: right;
    }

header.fixedMenu {
    position: fixed;
    width: 100%;
}

.navMenu {
  z-index: -1;
  position: relative;
}

.linksMenu {
  display: none;
  list-style: none;
  margin: -4px 0 0;
  padding: 0;
}

.linksMenu.showMenu {
  display: block;
  background-color: #148dcd;
  padding-top: 2em;
  margin-top: -2.25em;
}

.linksMenu a {
  color: #ECEFF1;
  text-align: left;
  font: 1em Oswald;
  font-family: 'Exo', sans-serif;
  padding: .8em;
  display: block;
  text-decoration: none;

}

.linksMenu a:before {
  margin: 0 1em 0 .25em;
}

.linksMenu li:nth-child(1) a {
  background-color: rgba(0,116,166,.4);
}

.linksMenu li:nth-child(2) a {
  background-color: rgba(0,116,166,.55);
}

.linksMenu li:nth-child(3) a {
  background-color: rgba(0,116,166,.7);
}

.linksMenu li:nth-child(4) a {
  background-color: rgba(0,116,166,.85);
}

.linksMenu li:nth-child(5) a {
  background-color: rgba(0,116,166,1);
}

.burgerMenu {
  position: relative;
  width: 50px;
  height: 50px;
  cursor: pointer;
  background-color: #148dcd;
  border-radius: 50%;
  display: inline-block;
  margin: 15px;
}

.burger {
  top: 22px;
  right: 10px;
  opacity: 1;
}

.burger::before {
  top: 10px;
  content: "";
  display: block;
}

.burger::after {
  bottom: 10px;
  content: "";
  display: block;
}

.burger::after, .burger::before, .burger {
  transition: all .3s ease-in-out;
  -webkit-transition: all .3s ease-in-out;
  background-color: #fff;
  border-radius: 2px;
  width: 29px;
  height: 5px;
  position: absolute;
}

/* Shade from Burger Menu */

.bgShade {
  background-color: rgba(0,0,0,.75);
  height: 100vh;
  position: fixed;
  top: 0;
  width: 100vw;
  visibility: hidden;
  transition: .25s linear;
  opacity: 0;
}

.bgShade.showShade {
  opacity: 1;
  visibility: visible;
}

.bgShade.hideShade {
  opacity: 0;
  visibility: hidden;
}

/* Scroll locked */

body.bodyStopped {
  overflow: hidden;
}

/* Transition from Burger menu to X */

.burgerMenu.showMenu .burger::after{
  transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
  bottom: 0px;
}

.burgerMenu.showMenu .burger::before{
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  top: 0px;
}

.burgerMenu.showMenu .burger{
  background: rgba(111,111,111,.0);
}

/* Interface - Desktop */

@media screen and (min-width: 768px) {

  header .bgMenu {
    background-color: rgba(20,141,205,1);
  }

  div.burgerMenu {
    display: none;
  }

  .navMenu {
    z-index: 0;
  }

  .linksMenu {
    display: block;
    text-align: center;
    box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);
  }

  .linksMenu li {
    display: inline-block;
  }

  .navMenu .linksMenu li a {
    background-color: transparent;
    color: #0c547b;
    font-family: 'Exo', sans-serif;
    font-weight:bold;
    font-size: 1.3em;
    padding: 33px 1.2em 24px .8em;
    transition: .25s;
  }

  .navMenu .linksMenu li a:hover {
    color: #fff;
  }

  .navMenu.bounceOutUp {
    animation-name: unset;
  }

  .figureProfile.animated.zoomInUp img {
    max-width: inherit;
    width: 360px;
  }

  .bgShade.fadeIn,
  .bgShade.fadeOut {
    display: none;
  }
}

Início

Artigos

Cursos

Ferramentas

Sobre


Erro RSelenium - Selenium message:Java heap space

Question: Olá, estou tentando fazer um scraping do http://acervo.estadao.com.br/ usando o RSelenium, porque a página só gera as informações no html quando é carregada no browser.
Bem quando acontece isso não sei fazer de outra forma que não seja com o RSelenium. Mas quando o loop executa cerca de 250 vezes, ele encerra e aparece a mensagem abaixo:

Selenium message:Java heap space
Erro:      Summary: UnknownError       Detail: An unknown server-side error
  occurred while processing the command.     Further Details: run
  errorDetails method

informação da secão
R version 3.4.0 (2017-04-21) Platform: x86_64-apple-darwin15.6.0
  (64-bit) Running under: macOS Sierra 10.12.6
Matrix products: default BLAS:
  /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
  LAPACK:
  /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib
locale: [1]
  pt_BR.UTF-8/pt_BR.UTF-8/pt_BR.UTF-8/C/pt_BR.UTF-8/pt_BR.UTF-8
attached base packages: [1] stats     graphics  grDevices utils
  datasets  methods   base
other attached packages: [1] wdman_0.2.2     magrittr_1.5
  rvest_0.3.2     xml2_1.1.1      [5] httr_1.3.1      XML_3.98-1.9
  RSelenium_1.7.1
Answer: Problemas relacionas a heap estão ligados a memória, neste caso a memória que o java alocou, quando tente achar o comando para compilar com mais memória, ou se isto não for compilado tente achar um modo para seu programa usar mais memória do que já est asendo fornecida.


Hardware for Capturing Packets

Question: One of my clients is a small school district in Texas.  Like any school, they often have problems with network'd peripherals such as printers, et al.
It would be nice to be able to simply "listen" to what the printer and PC are saying to each other (or not saying more importantly)...  The problem is that I can't find old-style "hubs" anymore, and even if I could, it's not a long-term solution.
All of the devices that I have found to replicate the purpose of a simple hub are either $100+ or are difficult to throw into a networking tool kit (aka my backpack)...
Now that hubs are dead, what's the new low-cost standard for simple packet capture in the networking world?
Comment: A small managed switch that supports port mirroring/monitoring/spanning.
Comment: @joeqwerty, that's not something you can safely label as "low-cost"...
Comment: A NetGear ProSafe 8-port Gigabit Smart Switch can be had for US $119.00. A Dell PowerConnect 2808 can be had for US $149.00. They both support port mirroring. Yes, they're more than $100.00 but I'd hardly call them expensive.
Comment: Not as cheap as you like, but I have a couple of these.  http://store.netgate.com/Netgate-m1n1wall-2D3-2D13-Silver-P219C83.aspx.  I linux installed.  It bridges a pair of the ports, will run DHCP, and establish a VPN to my management system.  That way I can ship the box off to somebody, and they can plug it in.
Answer: I see only these ways to do this:

Ultra low cost: Get a old PC with two network cards. Not portable, but cheap.
The same with a laptop with two network cards. Might need a cardbus/PCMIA card for the second NIC. This is probably the best solution if you already have a laptop.
Find an old fashioned hub. Many people tend to keep at least one of those around for precisely this purpose.
Look for old (read: 100mbit only) managed switches with port mirroring. Buying these new is not cheap, but in the last 3 years I got half a dozen of those of scrap heaps because they were replaced with more modern switches with Gbit or PoE features.

I would love to add poke you boss for the tools needed to do your job. Given your question I suspect that is not an option, but 'It saves me X hours per year' 'Price is Y' 'Return on investment is <=3 years' is a powerful argument.
Answer: Does it have to be hardware? If you're troubleshooting traffic to/from a particular PC, could you run a program to capture packets? I guess you probably don't want to install WireShark, but there are programs that will run directly from a USB stick without requiring installation (SmartSniff is one example).
Comment: Software can not capture packets unless they are on the line. That is fine with hubs or managed switches with port mirroring, but with unmanaged switches these packets never arrive at the PC with the software. Which makes it hard to capture what is not there. :)
Comment: From the original question, he wants to "listen" to what the printer and PC are saying to each other. I'm talking about running the software on the PC in question - hence a piece of software that doesn't require installation :-). Completely agree that hardware is a better idea since you're monitoring from a neutral position but if there's no other option then this might be second best.
Comment: You make a good point for that specific case. I was still thinking in the general 'intercept from sysadmin PC' scenario.

Hardware for Capturing Packets


Left and Right region is not showing on ZEN sub theme

Question: I've been working right now on a custom sub theme via ZEN for a certain Drupal site. I had it first developed in my localhost. Right after I had the half of the basic design implemented, I uploaded it immediately to the site and had it enabled. Now, something is wrong. The two regions are not showing up when I tried to view them on the block administration page. Even if I put a block on each of them, still they don't display on the page... what could it be?
In my localhost, it's working fine. I'm not sure why it's not working well on the live site. Has anyone of you experienced the same issue? Any help or suggestion is very much appreciated.
thanks in advance.
Comment: Did you clear the theme cache?
Comment: yes.. many times already.. I also had it disabled and enabled again. Further actions I did was to disable, and remove the theme and re upload it again.. still the result is the same T_T
Comment: i found the solution..
Answer: I finally found the solution for this problem. That is the put 'zen' folder under the same location of the sub-theme folder. Actually, the site I've been working on is a multi site setup and there is also an entity there that is also using zen as it's theme. I thought putting just my sub-theme is enough since the site still recognized the main theme, which is Zen.
The reason why the two region of the theme I uploaded is not being recognized, is because it's info file is not being read properly. The info file that is being read by the site is found, on the other zen sub-theme I mentioned above.


Enumerating python matrix by cell value

Question: Given a matrix:
m = np.matrix('1 2; 3 4')

I would like to enumerate its cells (not rows\columns) in descending order of the value in the matrix. So in my example i would like to enumerate: 4,3,2,1 and have the indexes for each.
I could flatten the matrix to 1d array, order the array and use its index to recover to the original matrix index. But it feels wrong.
Is there some built-in ability in python for that?
Answer: You could use np.ndenumerate to get an iterator of indices and values.
You could convert it to a list:
>>> import numpy as np
>>> m = np.matrix('1 2; 3 4')
>>> list(np.ndenumerate(m))
[((0, 0), 1), ((0, 1), 2), ((1, 0), 3), ((1, 1), 4)]

sort by values:
>>> sorted([(v, i) for (i,v) in np.ndenumerate(m)], reverse=True)
[(4, (1, 1)), (3, (1, 0)), (2, (0, 1)), (1, (0, 0))]

and extract the indices:
>>> [i for (_, i) in sorted([(v, i) for (i,v) in np.ndenumerate(m)], reverse=True)]
[(1, 1), (1, 0), (0, 1), (0, 0)]

I don't know if it's possible to do it in less steps. Here's an example with another matrix:
>>> m = np.matrix('1 4; 3 2')
>>> [i for (_, i) in sorted([(v, i) for (i,v) in np.ndenumerate(m)], reverse=True)]
[(0, 1), (1, 0), (1, 1), (0, 0)]

It might seem messy to mix numpy and vanilla list comprehensions. The problem is that ndenumerate returns an iterator. You could use:
np.fromiter(np.ndenumerate(m), np.dtype('2i, 1i'))

but it's a 1-D array of tuples, which doesn't makes indexing or sorting easier.

Enumerating python matrix by cell value


Socket Communication in C# - IP-Port

Question: I am testing my socket programs at home, in local network.
Server and client programs are running on seperate machines.
Server program socket is binded as: serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8999));
Client program (on the other computer) is connected as: clientSocket.Connect(IPAddress.Parse("192.168.2.3"), 8999);
Why can Client not communicate with server?
Do I need to make some firewall configuration or something like that?
Or am I writing Server Ip incorrectly to the Client? (I got it from cmd->ipconfig of server)
Comment: Doesnt the IPEndPoint need to be the ip which you use to connect to that server?
Answer: You are only binding to local 127.0.0.1 IP therefore your server would be accessible only from the same machine. Try the following:
serverSocket.Bind(new IPEndPoint(IPAddress.Any), 8999));
Answer: Because your server is binding to the localhost loop-back address 127.0.0.1.  This means nothing except what's running on the server can communicate with the socket.
You need to:

verify the server has a network connection on the same subnet as the client (192.168.2.0 or 192.168.0.0) - call it the "public" IP address
bind your socket to the server's "public" IP address or bind your socket to all interfaces - usually with the special IP address 0.0.0.0

Socket Communication in C# - IP-Port


Send JSON and blob together

Question: I'm writing a simple streaming service.
A browser An open a web socket to a server, then another browser B open a new socket to the same server.
Browser A register a video by its camera (MediaRecorder API) and send it to the server.
The server broadcast this video to others connected browsers.
I have a working version with Socket.IO, but I'd like to do it in vanilla JavaScript (WebSocket.Server on Node.js server and webSocket on client).
This is the problem:
With socket.io a can write something like this:
<code>  this.socket.emit('broadcast', {
    stream: new Blob(stream, {'type': `video/webm${MEDIA_CHARSET}`}),
    from: {id: this.socket.id}
  });
</code>
Stream comes from mediarecorder -> dataavailable event listener
But with native websocket I can't send blob embed in a JSON object, because websocket can send only string or arraybuffer.
I tried many different ways in order to send JSON and blob together, but nothing works.
Any help?
Is it possible to use only Engine.IO on client side in order to pack a message with blob and JSON together? Any ideas about this way?
Answer: There are many ways to serialize your data for sending over a binary web socket.  I would recommend considering CBOR, which serializes to binary and also has support for binary data within it.
There are several CBOR libraries to choose from on NPM.
Comment: I checked out https://github.com/paroga/cbor-js, but it seems I still can't send blob or arraybuffer.
It seems the lib doesn't manage ArrayBuffer data type, and it send an empty object.
Thre is also an opened issue about this.
Comment: @wiulma It seems as though you just need to use Uint8Array instead...  In any case, there are several other packages for CBOR.

Send JSON and blob together


Let $f$ a continuous function on $\mathbb R$ such that $f(0)=f(2)$.

Question: Let $f$ a continuous function on $\mathbb R$ such that $f(0)=f(2)$. Answer by true or false. There exists $\alpha\in[0,1]$ such that $f(\alpha)=f(\alpha+1)$.
I think that it's wrong but I'm not able to find a counter exemple.
Comment: See [this](http://math.stackexchange.com/questions/16374/universal-chord-theorem).
Answer: Hint:
consider $g(x)=f(x)-f(x+1)$, note we always have $g(0)=-g(1)$. Discuss the value of $g(0),g(1)$. Also remember intermediate value theorem.
Comment: This is certainly the way to go. One should note that $g:[0,1]\rightarrow \mathbb{R}$


Simulating a price series using GARCH

Question: I need to simulate a price series based on a GARCH(1,1) specification for the returns (price changes). I currently have this:
<code>    d_price = diff(price) #the price changes
    garch.model = garch(d_price) #a GARCH(1,1) model
    specs = garchSpec(model = list(omega = garch.model$coef[1],
        alpha = garch.model$coef[2], beta = garch.model$coef[3]))

    sim = garchSim(spec = specs, n = t) #simulated GARCH returns
    mu = mean(price) #the starting value is the mean of the series
    sim.series = rep(mu, t)

    #create the simulated price series
    for(i in 2:t){
      sim.series[i] = sim.series[i-1] + sim[i-1]
    }
</code>
My problem is that this series often becomes negative. I can't have negative prices in my model.
I thought about using percentage price changes instead, but I experience a similar problem - the price series sometimes decreases to arbitrarily small values that are completely unrealistic.
So, my question is this: Is there a best option for simulating a series so that the price never becomes negative or unrealistically small? That is, without putting artificial barriers on the price process (P must be greater than 20, for example).
Thanks!!!
Answer: Your problem is that the GARCH model assumes the error terms have normal distributions with zero mean and variance that changes over time.  If you want to restrict prices to be positive you have to create a model that has error terms compatible with that assumption.
Percentage doesn't help because you still have the nonnegativity assumption and the model you choose still assume normal error distributions.
There is no easy solution.  If you could construct a model with an error distribution that is non-negative you will always get positive values but the error term would have a non-zero mean.
Comment: Thanks for your response. I do want my error term to have a mean of zero. I had the same problem when simulating multiple AR(1) price series. I simulated the Ornstein-Uhlenbeck process instead - the continuous time version of an AR(1) process that is guaranteed to be positive. I'll see if I can convert the O-U process into a GARCH process and hopefully I'll be able to post an answer.
Answer: You can try and simulate logReturns as Garch process  i.e. rather than difference in the prices, you can use difference in the log prices. Even if error is very negative, prices would always be positive.
Answer: Depending on the use case it might be sufficient to calculate the returns for the series and then convert the returns back to prices. In the end add the minimum value + a small delta (e.g. 1).
<code>r = diff(log(priceSeries))
... do your model estimation
priceSeries = diffinv(aramSim)
priceSeries = priceSeries + min(priceSeries) + 1
</code>
This just shifts up the whole price series. Don't do it if absolute prices for some reasons are critical. But you preserve imho the structure and I don't see big issues with doing this. Please correct me if I am wrong. But this is an easy solution.
Answer: My solution: I added GARCH volatility to an Ornstein-Uhlenbeck process. Prices are never negative and price volatility is non-constant. Hope this helps someone!!!
<code>    T=500
    #process parameters
    eta = 0.2 #eta = 0 is equivalent to Geometric Brownian Motion
    mu = 100 #the mean of the process

    #GARCH volatility model
    specs = garchSpec(model = list(omega = 0.000001, alpha = 0.5, beta = 0.4))
    sigma = garchSim(spec = specs, n = T)

    P_0 = mu #starting price, known
    P = rep(P_0,T)

    for(i in 2:T){
      P[i] = P[i-1] + eta * (mu - P[i-1]) + sigma[i] * P[i-1]
    }

    #prices and returns
    par(mfrow=c(2,1))
    plot(P,type="l",xlab="Time", main="", ylab = "Price")
    plot(diff(P), type = 'l', ylab = 'Price Changes', xlab = 'Time')
</code>

Simulating a price series using GARCH


Example of not locally finitely generated sheaf

Question: Take the sheaf $\mathbf{H}_{\mathbb{C}}$ of holomorphic functions on $\mathbb{C}$. In a book I am reading they define the subsheaf $I$ by setting the stalks to be
$I_{z}:=\begin{cases}
0\quad \text{if } z=0\\
\mathbf{H}_{\mathbb{C},z} \quad \text{else}
\end{cases}$
and claim that this sheaf is not locally finitely generated as $\mathbf{H}_{\mathbb{C}}$-module.
Could anyone explain to me why this is true?
Let $U$ some neighbouhood of $0$. I will have to show that there is no surjective morphism of sheaves
$(\mathbf{H}_{\mathbb{C}}^{n})_{\vert U}\rightarrow I_{\vert U}$.
(Clearly, the only point around which finding a suitable surjective map could possibly fail is $0$.)
Answer: We can actually show that there is no non-zero morphism $f:\mathbf{H}_{\mathbb{C}}|_U\to I|_U$ if $U$  is connected. This will prove what you want. To show this, note that $s=f(1)$ (where 1 is the constant unit section of $\mathbf{H}_{\mathbb{C}}$) is a section of $I_z$ hence a section of $\mathbf{H}_{\mathbb{C}}$ since $I$ is a subsheaf of $\mathbf{H}_{\mathbb{C}}$. We have $s_0=0$ since $I_0=0$ hence $s|_V=0$ in some neighborhood $V$ of $0$. By the principle of isolated zeros, $s=0$. It follows that $f=0$.


Como fazer um INSERT de múltiplas rows, onde algumas rows terão menos valores do que colunas

Question: Vou tentar dar um exemplo simples do meu problema.
Tenho as seguintes colunas numa tabela chamada "Teste":

Nome | Idade | Sexo | Nota1 | Nota2 | Nota3

Desejo inserir múltiplas linhas na tabela, porém nem todos os alunos terão todas as notas. Exemplo:
INSERT INTO "Teste" ("Nome", "Idade", "Nota1", "Nota2", "Nota3") VALUES("Caio","19", 10, 9, 8), ("João","17", 10, 9);

Gostaria de saber se tem alguma forma de fazer essa inserção.
OBS: Eu poderia botar null ou uma string vazia(" "), mas não posso.
Desde já, obrigado!
Comment: Alguém poderia, por exemplo, ter as notas 2 e 3 mas não ter a 1?
Comment: Sim. Os alunos podem ter 1 das 3, nenhuma e assim por diante.
Comment: Se a nota faltante pode ser qualquer uma das três não vejo como você informar tal situação sem ser não informando o(s) campo(s) correspondente(s) à(s) nota(s) inexistente(s) na lista de campos ou informando NULL na lista de valores no(s) valor(es) correspondente(s) à(s) nota(s) faltante(s). Não há como o SGBD saber sem você informar explicitamente.
Comment: Então não há como fazer oq eu quero?
Answer: Não há uma sintaxe para inserir linhas múltiplas, onde uma linha afete determinados campos, e outra linha afete outros campos.
Cada INSERT deverá especificar as colunas a serem inseridas, e todos os valores se referirão àquelas colunas.
No fundo, para que cada linha se referisse a campos diferentes, teríamos que explicar a cada linha o que deve ser feito, então no fundo isto se reduz ao problema de fazer um INSERT para cada situação. Sendo que neste caso, concordo que há uma simplificação, pois as colunas a não serem inseridas seriam sempre as últimas, então seria como enviar uma lista de valores mais curta. De qualquer forma, não é possível.
Porém, a restrição de que não pode enviar NULL ou string vazia não faz muito sentido. Pois, se o banco de dados aceitasse informar menos colunas no INSERT, significaria que as outras colunas receberiam um valor default, ao ser inserido o registro no banco de dados. Normalmente este valor seria NULL, mesmo, então por que não colocá-lo no próprio INSERT?
Talvez uma outra solução seria renormalizar o banco de dados para ter, de um lado, os atributos da pessoa numa tabela, contendo nome e idade. E, noutra tabela, a descrição da nota ('Nota 1', 'Nota 2'), etc e seu valor, além da identificação do aluno. Assim as notas poderiam ser inseridas somente quando disponiveis.
Comment: Obrigado pela resposta. No final tive que reestruturar o banco de dados com algumas regras diferentes. Mas até agora não entendi no que eu errei haha, mas vamos aprendendo com o tempo... Obrigado!


DirectAccess status codes

Question: does anyone know if there exists information on the possible Status en Substatus connection states in Microsoft Direct Access? The information on MSFT_DAConnectionStatus class (Windows) | msdn.microsoft.com states that both properties are uint32's but that's not really helpful.
I know by experience that status code 2 means ConnectedRemotely...
Thanks, David
Answer: Have you tried using the Get-DAConnectionStatus PowerShell commandlet? That gives you the current status in text form.
PS C:\Users\administrator> Get-DAConnectionStatus

Status    : ConnectedLocally
Substatus : None

Also, if you're trying to troubleshoot DA connection issues, have you seen the "DirectAccess Client Troubleshooting Tool"?
Answer: I am late to the party, but I ran into the same issue today. I quickly determined that Get-DAConnectionInfo automatically generates some runtime types based on the output of the WMI class, they are:
"Microsoft.PowerShell.Cmdletization.GeneratedTypes.DAConnectionStatus.Status" and "Microsoft.PowerShell.Cmdletization.GeneratedTypes.DAConnectionStatus.Substatus"
Meaning, you can query them directly in Powershell, I use the script provided here. For sake of convenience I've included the list below:
Status Enum:
Name              Value
----              -----
ConfigChanged         0
ConnectedLocally      1
ConnectedRemotely     2
ActionableError       3
Error                 4

SubStatus Enum:
Name                                    Value
----                                    -----
Invalid                                     0
None                                        1
NAPUnhealthy                                2
StrongAuthorizationCredentialsNeeded        3
LocalDNSNamesPreferred                      4
NoDirectAccessPolicy                        5
InternetConnectivityDown                    6
CouldNotContactDirectAccessServer           7
NameResolutionFailure                       8
RemoteNetworkAuthenticationFailure          9
RemoteNetworkConnectivityDown              10
SomeRemoteNetworkResourcesNotResponding    11
MissingDAClientExperienceConfiguration     12
MissingProxyConfiguration                  13
ProxyCredentialsNeeded                     14
IPHTTPSCertificateNeeded                   15
IPv6Disabled                               16
FirewallDisabled                           17

DirectAccess status codes


Question on the Lebesgue-Radon-Nikodym Theorem (Folland, page 90, theorem 3.8)

Question: I might be missing something simple here because I can't seem to find someone asking/answering this question anywhere..
In the third paragraph of this proof (begins with "We claim that...") Folland gives the definition
$$d \lambda = d \nu - f d \mu.$$
I don't understand what this definition means? What exactly is $d \lambda$? One page before (page 89) Folland gives the general definition
$$d \nu = f d \mu$$
$$\implies v(E) = \int_E f d\mu$$
Trying to apply this definition, to the definition I am confused about gives me
$$d \lambda = d \nu - f d \mu$$
$$ = f d \mu - f d \mu$$
$$ = 0$$
which doesn't make sense. What am I missing here? Can someone help me out by explaining what
$$d \lambda = d \nu - f d \mu$$
means?
Answer: $d\lambda=d\nu-f\;d\mu$ means
$$ \lambda(E)=\nu(E)-\int_Ef\;d\mu$$
The measure $\nu$ in the theorem is some $\sigma$-finite signed measure. It does not necessarily have any relation to $\mu$.
Comment: What exactly is the difference then between $d\lambda$ and $\lambda$ (if any)? He seems to use them interchangeably in that paragraph.
Comment: $d\lambda=d\nu-f\;d\mu$ is a convenient shorthand for "$\lambda$ is the signed measure defined by $\lambda(E)=\nu(E)-\int_Ef\;d\mu$". So $d\lambda$ and $\lambda$ can be used interchangeably.


XML sitemap rebuild links on cron run

Question: I've installed XML Sitemap. I can manually rebuild the link in /admin/config/search/xmlsitemap/rebuild. Is there any way to automatically rebuild the links (e.g. when cron runs XML sitemap would rebuild the links) ?
Answer: you need to set frequency of sitemap you can change it on daily,weekly,monthly basis
How add frequency in sitemap
Answer: Hello you can do it by another way by adding to your cron server your settings.
Comment: Can you expand on how this is done?

XML sitemap rebuild links on cron run


Determining whether following sequences are Cauchy

Question: $\newcommand{\absval}[1]{\left\lvert #1 \right\rvert}$
I'm self-learning mathematical analysis from Understanding Analysis by Stephen Abbott. I'd like someone to verify my solution, if the proof checks out.
Additionally, if $(a_n)$ is Cauchy, is $[[a_n]]$ also Cauchy? Because, there is no strict relationship between $\absval{[[a_n]] - [[a_m]]}$ and $\absval{a_n - a_m}$ or so I think.
Exercise 2.6.4

Let $(a_n)$ and $(b_n)$ be Cauchy sequences. Decide whether each of the following sequences is a Cauchy sequence, justifying each conclusion.

(a) $c_n = \absval{a_n - b_n}$

(b) $c_n = (-1)^n a_n$

(c) $c_n = [[a_n]]$, where $[[x]]$ refers to the greatest integer less than or equal to $x$.

Proof.
(a) The following inequalities hold for any reals $a,b \in \mathbf{R}$:
\begin{align*}
 \absval{a + b} \le \absval{a} + \absval{b}
\end{align*}
Replacing $b$ by $-b$, we have:
\begin{align*}
 \absval{a - b} \le \absval{a} + \absval{b}
\end{align*}
Writing $a = a - b + b$, we have:
\begin{align*}
 \absval{a} &= \absval{a - b + b}\\
  &\le \absval{a - b} + \absval{b}\\
 \iff \absval{a} - \absval{b} &\le \absval{a - b}
\end{align*}
Writing $b = b - a + a$, we have:
\begin{align*}
 \absval{b} &= \absval{b - a + a}\\
  &\le \absval{a - b} + \absval{a}\\
 \iff -(\absval{a} - \absval{b}) &\le \absval{a - b}
\end{align*}
Consequently,
\begin{align*}
 \absval{\absval{a} - \absval{b}} \le \absval{a - b}
\end{align*}
Now, the distance between any two terms of the sequence $(c_n)$ is given by,
\begin{align*}
 \absval{c_n - c_m} &= \absval{\absval{a_n - b_n} - \absval{a_m - b_m}}\\
 &\le \absval{{a_n - b_n} - ({a_m - b_m})} = \absval{(a_n - a_m) - (b_n - b_m)}\\
 &\le \absval{a_n - a_m} + \absval{a_m - b_m}
\end{align*}
We desire each of these distances to be smaller than $\epsilon/2$.
Since $(a_n)$ and $(b_n)$ are Cauchy sequences, given any $\epsilon > 0$, there exists $N_1,N_2$ such that for all $m,n \ge N_1$, $\absval{a_n - a_m} < \epsilon/2$ and for all $m,n \ge N_2$, $\absval{b_n - b_m} < \epsilon/2$. Altogether, define $N = \max \{ N_1,N_2 \}$, if $m,n \ge N$, the terms in the above inequality are each smaller than $\epsilon/2$, which is what we required.
(b) $c_n = (-1)^n a_n$
If $(a_n)$ is Cauchy, $((-1)^n a_n)$ is also Cauchy, because
\begin{align*}
 \absval{(-1)^n(a_n - a_m)} = \absval{a_n - a_m}
\end{align*}
Comment: (b) is false. Take $a_n=1$
Answer: (a) It is correct, but you can use the inequality $\bigl||a|-|b|\bigr|\leqslant|a-b|$ without proving it. It's a standard inequality. Besides, when you wrote $|a_n-a_m|+|a_m-b_m|$, what you meant was $|a_n-a_m|+|b_n-b_m|$.
(b) That is wrong. The constant sequence $1$ is a Cauchy sequence, but $\bigl((-1)^n\bigr)_{n\in\Bbb N}$ isn't.
(c) The statement is false. For instance, the sequence $\left(\frac{(-1)^n}n\right)_{n\in\Bbb N}$ is a Cauchy sequence, but$$(\forall n\in\Bbb N):\left\lfloor\frac{(-1)^n}n\right\rfloor=\begin{cases}-1&\text{ if $n$ is odd}\\0&\text{ if $n$ is even.}\end{cases}$$and therefore $\left(\left\lfloor\frac{(-1)^n}n\right\rfloor\right)_{n\in\Bbb N}$ is not a Cauchy sequence.
Comment: Your mistake lies in assuming that $(-1)^ma_m-(-a)^na_n=(-1)^n(a_m-a_n)$. That's true only when $m$ and $n$ have the same parity.
Comment: For (b) I didn't think of constant sequences. But, why doesn't the $\epsilon$ argument work? Isn't $\lvert (-1)^n \rvert = 1$, or am I goofing up something?