Grammar: difference between a top down and bottom up? (Example)

Question: This is a follow up question from Grammar: difference between a top down and bottom up?
I understand from that question that:

the grammar itself isn't top-down or bottom-up, the parser is
there are grammars that can be parsed by one but not the other
(thanks Jerry Coffin

So for this grammar (all possible mathematical formulas):
    E -> E T E
    E -> (E)
    E -> D

    T -> + | - | * | /

    D -> 0
    D -> L G

    G -> G G
    G -> 0 | L

    L -> 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

Would this be readable by a top down and bottom up parser?
Could you say that this is a top down grammar or a bottom up grammar (or neither)?

I am asking because I have a homework question that asks:

"Write top-down and bottom-up grammars for the language consisting of all ..." (different question)

I am not sure if this can be correct since it appears that there is no such thing as a top-down and bottom-up grammar.  Could anyone clarify?
Comment: Can you provide the full question?  Maybe something will become clearer.
Comment: Maybe it would help to look up what the textbook defines as a "top-down" grammar? I think top-down parsers only fail when they do something like recursive descent instead of a breadth-first-search-like technique (e.g. queueing edges to try).
Answer: That grammar is stupid, since it unites lexing and parsing as one. But ok, it's an academic example.
The thing with bottoms-up and top-down is that is has special corner cases that are difficult to implement with you normal 1 look ahead. I probably think that you should check if it has any problems and change the grammar.
To understand you grammar I wrote a proper EBNF
expr:
    expr op expr |
    '(' expr ')' |
    number;

op:
    '+' |
    '-' |
    '*' |
    '/';

number:
    '0' |
    digit digits;

digits:
    '0' |
    digit |
    digits digits;

digit:
    '1' |
    '2' |
    '3' |
    '4' |
    '5' |
    '6' |
    '7' |
    '8' |
    '9';

I especially don't like the rule digits: digits digits. It is unclear where the first digits starts and the second ends. I would implement the rule as
digits:
    '0' |
    digit |
    digits digit;

An other problem is number: '0' | digit digits; This conflicts with digits: '0' and digits: digit;. As a matter of fact that is duplicated. I would change the rules to (removing digits):
number:
    '0' |
    digit |
    digit zero_digits;

zero_digits:
    zero_digit |
    zero_digits zero_digit;

zero_digit:
    '0' |
    digit;

This makes the grammar LR1 (left recursive with one look ahead) and context free. This is what you would normally give to a parser generator such as bison. And since bison is bottoms up, this is a valid input for a bottoms-up parser.
For a top-down approach, at least for recursive decent, left recursive is a bit of a problem. You can use roll back, if you like but for these you want a RR1 (right recursive one look ahead) grammar. To do that swap the recursions:
zero_digits:
    zero_digit |
    zero_digit zero_digits;

I am not sure if that answers you question. I think the question is badly formulated and misleading; and I write parsers for a living...


Appoggiatura chord

Question: While learning one of the Mazurka's of Chopin, I came across a chord that I think is an appoggiatura chord but I need a second opinion. The piece is Chopin Mazurka in A minor Op. 68 No. 2 and the chord is on the third beat of the second measure. The notes of the chord are E B on the bass clef and D on the treble (E B D).
I tried to analyze it by thinking that it's major or minor but that obviously doesn't make sense because the chord doesn't have a third to make it minor or major. From E to B is a perfect fifth, then there's a D.
The D has a trill so that it becomes a D#. I'm aware that the chord then becomes E B D# which makes me assume that it's another appoggiatura chord.
I've been studying the Harmony and Voice Leading  book by Carl Schachter and Edward Aldwell and in the book you learn about complete and incomplete chords and it states that the third is never omitted out of a triad except for special effects, and the fifth is sometimes omitted. It seems that Chopin wanted the third of this chord omitted. It's definitely not Bmin/E or a slash chord, it's a nonfunctional chord like an appoggiatura chord, double appoggiatura, triple appoggiatura, something like that. Or maybe it's just an incomplete chord? Am I correct?
Here's a picture of the chord:

Here's the piece of music, the sheet music is in the video. Give it a listen:
Comment: @nick_n_a Is B to D♯ 3 half steps, or 4?
Comment: @Richard. Yes. 4. Look. E - is bass. The B D# have distance 4 half steps. Chord is G#-B-D# (3-4 is minor) G#-minor. Result: G#m/E. http://jguitar.com/chordsearch?chordsearch=G%23m%2FE
Comment: @nick_n_a And where is the G♯?
Comment: @Richard minor chord is 3 and 4 half steps. Between B-D# is 4 half steps, and.. B and 3 half steps down is G#.
Comment: @nick_n_a Yes, but where is the G♯ in the music? Normally we would have the root of the chord played in the music, right?
Comment: In this case, we play bass E instead G#.  G#m is G#-B-D#, but G#m/E is E-B-D#. Bmin/E - is wrong (how autor written). G#m/E  must be answer.
Comment: Remark: This could be an Esusmaj7/A probably
Answer: I would actually recommend you view this less as a chord and more as a result of voice leading. More specifically, I recommend you think of this entire measure as a tonic A-minor chord with lower neighbor tones in two voices:

When viewed this way, we understand that the B and D♯ are just non-chord tones that embellish the C and E that surround them. This third beat thus isn't really a chord at all!
Given that you're studying from the Aldwell/Schachter book, I think it's especially important that you try and view it this way. Those authors shy away from treating every vertical sonority as its own harmony, often preferring instead to understand those sonorities as results of voice leading.
Comment: B and D♯  is path of G#m chord. Guitar, accordion can play second path of chord (two last sounds).
Answer: I agree that the two notes appear to be arising in voice leading, but that's still too simple. If the tempo was faster I would be more in agreement. We'd should remember, maybe, that the lydian mode features prominently in the mazurkas. The lydian mode has a major 3rd and a tritone (raised 4th), but this is in a minor key. The slow tempo causes the d# to sound more powerful and eery. The pattern is repeated in C major with an f# in the second phrase, which is perfectly lydian. The half steps are retained in both voices in the second phrase as well.  Chopin was a daring harmonizer. He could have left out the left hand b (which is a. diatonic pitch) and written another c in the left hand, but the effect wouldn't be as strong. I concede that the second phrase includes a chromatic variant in the tenor voice (d# with the right hand f#), but again, the effect in the major key is strengthened by the chromatic choice of d#. Danced mazurkas are usually pretty jolly, but Chopin's are hybrids, using elements of three different dances: mazurek, obradek and kujavjak (spelling?). This isn't a jolly mazurka. Chopin is borrowing from both major and minor modes alternately. He's also trying to use a 'jolly' rhythmic pattern in a rather unjolly musical climate (I mean the atmosphere of this particular piece). I believe Chopin invented the mazurka as a vehicle to combine the effects of those three dances. I may be mistaken, but mazurkas don't appear (in art music) before his time, and are uncommon in art music afterwards.

Appoggiatura chord


Does the number of rows really matter beyond a point?

Question: While working with any machine learning algorithm, does the number of rows really matter beyond a certain point?
I have kept some algorithms(decision tree in this instance) running for days, and the accuracy I get is similar to those I get immediately for 5000 rows. I'm kind of feeling that running it on the entire data set is more like a 'check' to verify the results you get with 5000 rows.
Is there any study on how many rows are actually needed and how much results vary when increasing the number of rows?
Answer: Answer here will probably be application-specific, data-set specific. In any given situation you can try yourself, select $m$ (say, 5000) rows at random, do the same again, again, ... and compare results.
You could also exploit your situation to draw some hold-out sample, to use for independent model verification.  If you are using some kind of automatic variable selection, that could be very valuable.
If you need confidence intervals for model parameters, those may be to long with this "use only a large random subsample" procedure, but, anyhow, the confidence intervals calculated with the full dataset are probably too short ... they depend on assumptions such as "the model is absolutely correct", "all variables measured without error", and so on, which might be fairly innocuous with small data sets, but not trustworthy with large data sets. Things like variables only measured with a finite (small) number of correct decimals will ultimately limit how short confidence intervals can be! You can yourself, with your data, investigate such questions by redoing the random subsampling many times, plotting the different coefficients obtained from each subsample, and compare the variation between them to the length of calculated confidence intervals.
Comment: +1 it also depend on the number of feautures. See [curse of dimensionality](http://en.wikipedia.org/wiki/Curse_of_dimensionality).
Comment: Yet another factor that the answer depends on is the model or statistical procedure you're using. In general, the more complex the model, the larger a sample is required before the model ceases to benefit from additional data. So, observing this sort of saturation is a clue that you have enough data to possibly benefit from trying a more complex model.


Select the most confident variable that has two features

Question: Suppose now I have a group of students, and for each student two measurements are given: one is the height of the student and the other is the weight of the student. Then my question is how I can select a student that have both decent height (the higher, the better) and decent weight (the heavier, the better)? One solution I can give is as follows:
Step 1: Normalize the weight and the height for each student, and the normalization is performed in the following way:
1) Calculate the average m and standard derivation s of the height (or the weight) of all the students.
2) The up-threshold and down-threshold is defined as:
upThreshold = m+3*s

downThreshold = m-3*s

So if the student's height is higher than upThreshold, then its normalization value will become 1. If the student's height is lower than downThrehold, then its normalization value will become 0.
3) For the height in between, I use the following formula to normalize the height:
 (height-m)/(3*s)*0.5+0.5

Step 2: calculate the sum of the normalized height and normalized weight for each student, and select the one with the maximum sum.
I do not know whether there are some problems in my solution, and any comments will be appreciated.
Answer:
Simply speaking, you normalize weights and heights to mean=1/2 std.deviation=1/6, then force them into [0,1] interval.  The same thing could be achieved simpler if you'd normalize them to mean=0, std.deviation=1, and force them into [-3,3] interval.
The problem with you approach is: suppose that one student has very high weight, but height below the average.  He may be selected over all others.  Another problem is, you have an arbitrary constant 3.
Therefor, if you want "both decent height and decent weight", I suggest to normalize weights and heights to mean=0, std.deviation=1, then just select the student with highest max(weight, height).  If the value is same for two students, select one with highest weight+height.


Rules for naming borrowed chords in Roman numeral analysis

Question: I don't seem to find an extensive resource on how to name out of scale chords in Roman numeral analysis.
E.g., let's look at this piece from "All imperfect things" of Michael Nyman:

I'm stuck on M5 and M7. In my very inexperienced mind there's tons of possibilities here, and maybe I started all wrong to begin with.
I'm assuming this is in A minor, even though the key signature's G/Em, and I think M5 & M7 are borrowed from the relative major: i.e., that would make them the IV from C major.
I have no idea however how to notate that. And have tried to look that up, but only ever see the solution to a specific question. I haven't been able to find a clear explanation on how to notate borrowed chords in general.
Comment: This is minimal music, a theme is just 2 bars, so you could set the tonality and then the RN (e.g. bars 1-4 G: ii, vii6, I6  and measure  5-8 C: IV46, vii7, V6 ... the chord in question C-F-A resp. C-F-B could be analyzed as IV and vii above the pedal tone C. But I say: forget it :)
Answer:
It doesn't make much sense to analyze music like temporary film music  that is not written in this spirit or context by Roman numbers. You can compare this minimal music with the chord material of early Renaissance music.
We even don't know actually the key. Has the key sign f# been set originally  by the composer or by the editor? Compare the added sheet music!

"After a fixed process, Nyman chooses [...] very short verbatim quotes from the classic template and subjects them to a minimalist repetition.  The tonal orientation is retained, but the harmonic progression is changed.  Finally, whole bars of the source material are missing and the harmonic stages are abruptly juxtaposed, instead of logically following a cadence. "  Michael Nymans Musik als Musikgeschichte von Volker Straebel, 1999
http://www.straebel.de/praxis/index.html?/praxis/text/t-nyman.htm
The result is music that has both charmed initiates and uneducated listeners of the same musical appeal because it plays intelligently with tradition  but on the other hand never becomes atonal.
https://de.wikipedia.org/wiki/Michael_Nyman
(The German wiki commentary is more extended than the English ...)
Edit: Well, if I had to analyze this piece with RN
I would first define whether it is in a minor, G major or e minor:
F/C in
a minor => IV46
G major => bVII 46 (the flat sign notated below the RN
and then the other RN should be adjusted to the key and also the half note changes  in the r.h. could be determined. But as I said: it doesn't make sense!
Answer: For a start, if it IS considered to be in A minor, V would be E major. The E minor chord in bar 2 could be labelled v. You could call the F chord ♭VI. Roman numeral analysis covers chromatic chords. No need to 'borrow' unless a chromatic chord DOES lead into a new tonality, and this one doesn't.
But this isn't functional harmony. Functional analysis doesn't tell us anything much useful about it.
Comment: Wth that key sig. it might have been in A Dorian. But then why naturalise(?) the F#?
Answer: Leaving aside the specific piece that prompted the question, the core of what's being asked is:
How does RNA label out-of-key chords?
There are three primary ways
1. Just add a sharp or flat before the Roman numeral
Suppose we're in A minor and encounter a Bb major chord. This can be labeled bII ("flat two"). Similarly, in A major, and F major chord could be labeled bVI.
However, there is a significant caveat.
The core purpose of RNA is to describe the function of a chord. Within RNA, bII and bVI have understood meanings in terms of how those chords are expected to behave, or the contexts in which they appear. However, in terms of chord function, there's no such thing in RNA as a #III chord.
In literal terms, of course, a C# major chord occurring in the context of A minor would be #III. So if your purpose is to use Roman numerals as a generic substitute for chord symbols, then calling it #III is fine. It gets the point across. However, in functional terms, #III is meaningless and is not part of "true" RNA.
For the case of C# major in the key of A minor, we need...
2. "Secondary" chords
A secondary chord is a chord that functions in a key other than the primary one of the piece. OP proposes that a piece is in A minor, but that an F major chord could be the IV chord in the key of C major. That is to say, the F major chord functions in a key (C major) other than the primary one (A minor). Thus the F chord would be a "secondary" chord.
RNA employs a slash notation to show that a Roman numeral should be interpreted relative to another key. For example, suppose a piece in A minor modulates to C major. C major is considered the "key of III"; that is, the key based on the third scale degree of A minor. Thus, an F major chord would be IV/III: the IV chord relative to the "key of III", C major.
Let's return fully now to the piece that prompted the question. Taking at face value the OP suggestion that the piece is in A minor, then the F major chord in measure 5 and 7 is actually in key. It's the VI chord.
However, let's follow the train of thought that it is actually operating as the IV chord of C major (i.e., the "key of III"). In that case, the RNA label would be IV/III ("four of three"), meaning "the four chord relative to the 'key of III'", as explained above.
Taking this idea a step further, consider the preceding chord in measure 4. Again allowing we're in A minor, labeling this G major chord as VII makes perfect sense. But let's consider that its function is actually to lead us to the F chord in measure 5. In that case, we'd want its label to reflect its use relative to that F chord. Measure 4 would therefore be labeled II/VI ("two of six"), meaning "the two chord relative to the 'key of VI'".
Similarly, suppose measure 5 is actually the beginning of a modulation to G major. Measure 5 now becomes VII/VII, and measure 6 becomes iii/VII.
There is extensive discussion of this type of RNA notation in What is a secondary dominant chord? Although that Q&A focuses on the use of V chords, it should give a thorough understanding of the concept of "secondary chords", as these "slash chords" are known. And as shown here, the concept isn't limited only to V chords.
3. Indicate a key change and use RNA in that key
When there are a significant enough number of chords functioning in a different key — an extended modulation, for example — the new key is indicated directly and then the RNA proceeds in that key. This removes the clutter of slashes on every single chord.
This method is discussed in Use of Roman Numeral Notation when a new key is introduced within original key


About the continuity of a function $f$ such that $f^{-1}(x)=\frac 1 {f(x)}$

Question:
Let $a \gt 1$ and $f: [\frac 1 a, a] \rightarrow [\frac 1 a, a]$
  bijective such that $f^{-1}(x)=\frac 1 {f(x)}, \forall x \in [\frac 1
a, a]$ ($f^{-1}$ is the inverse). Then:
1) $f$ cannot be continuous
2) If $f$ continous in x= 1 then there are infinitely many
  discontinuity points for $f$
3) Give an example of such function, having finite number of
  discontinuity points.

Because 2) implies 1), only 2) + 3) are to be proved.
Ironically, I have only proved 1) using the fact that $f$ continuous and bijective implies $f$ strict monotone. If, let's say, $f$ is increasing then $f^{-1}$ is increasing which is false because $f^{-1}(x)=\frac 1 {f(x)}$
Comment: is the superscript for f denoting its inverse or its reciprocal?
Comment: @Alephnull Inverse
Comment: If it is continuous, show endpoints map to endpoints.
Comment: 1 seems to be special because the product of the function with its inverse is 1.
Comment: @Alephnull It's possible
Comment: Related: http://math.stackexchange.com/questions/260278
Answer: To prove 2), it is convenient to show that such a function, if it has only finitely many discontinuities, must be discontinuous at $1$.
So let $f$ be such a function, and suppose it has only finitely many discontinuities. So we have a finite partition
$$\frac{1}{a} = t_0 < t_1 < \dotsc < t_{n-1} < t_n = a$$
of the interval, so that $f$ is continuous on each open interval $I_K := (t_k, t_{k+1})$, $0 \leqslant k < n$, and $f$ is discontinuous at $t_k$ for $0 < k < n$. Whether $f$ is continuous at $t_0$ or $t_n$ isn't of interest now. We want to show that $t_k = 1$ for some $0 < k < n$.
For each $0 \leqslant k < n$, the restriction $f_k = f\lvert_{I_k}$ is a continuous injective function, hence it is strictly monotonic. And $f_k(I_k) = f(I_k)$ is an open interval on which $f^{-1}$ is continuous. Since $f^{-1} = \frac{1}{f}$, $f$ is continuous at $x$ if and only if $f^{-1}$ is continuous at $x$, so there is an $0 \leqslant \ell < n$ with $f(I_k) \subset I_\ell$. We can apply the same argument to $f^{-1}$ and $I_\ell$ to see that $f^{-1}(I_\ell) \subset I_m$ for some $0 \leqslant m < n$. But
$$I_k = f^{-1}(f(I_k)) \subset f^{-1}(I_\ell) \subset I_m$$
implies $m = k$, and thus $f(I_k) = I_\ell$. If $f$ is increasing (decreasing) on $I_\ell$, then $\frac{1}{f} = f^{-1}$ is decreasing (increasing) on $I_\ell$. But $f^{-1}\lvert_{I_\ell} = (f_k)^{-1}$, so then $f_k^{-1}$ and therefore $f_k$ is decreasing (increasing). Thus none of the $I_k$ can be mapped to itself.
Now suppose $f$ were continuous at $1$, say $1 \in I_\ell$. Let $I_k = f^{-1}(I_\ell)$. Since $f$ attains values less than $1$ and values greater than $1$ on $I_k$, so does $\frac{1}{f} = f^{-1}$. Therefore we have $f(I_k) = I_\ell = f^{-1}(I_k)$, and hence $f(I_\ell) = I_k = f^{-1}(I_\ell)$. But if $f(I_\ell) = I_k \subset (1,a)$, then $f^{-1}(I_\ell) \subset (1/a,1)$, so $f^{-1}(I_\ell) \neq f(I_\ell)$ and if $f(I_\ell) \subset (1/a,1)$, then $f^{-1}(I_\ell) \subset (1,a)$, which again implies $f(I_\ell) \neq f^{-1}(I_\ell)$, and we've reached a contradiction.
For part 3), the above considerations show that we need at least four intervals of continuity. Let's try with the partition
$$\frac{1}{a} = t_0 < t_1 < t_2 = 1 < t_3 < t_4 = a.$$
If $f(I_k) = I_1$, then we must have $f^{-1}(I_k) = I_2$, and that shows that necessarily $t_1 = t_3^{-1}$, and we can have either the cycle $I_0 \to I_1 \to I_3 \to I_2 \to I_0$ or $I_0 \to I_2 \to I_3 \to I_1 \to I_0$. Let's take $t_3 = \sqrt{a}$, and the first cycle and see where we get. For the map $I_0 \to I_1$, we can try the straightforward $x \mapsto \sqrt{a}\cdot x$, and from this we find $f^{-1}(x) = \frac{x}{\sqrt{a}}$, so $f(x) = \frac{\sqrt{a}}{x}$ on $I_1$. This forces $f(x) = \frac{1}{\sqrt{a}\cdot x}$ on $I_2$, therefore $f^{-1}(x) = \sqrt{a}\cdot x$ on $I_2$, and that means $f(x) = \frac{x}{\sqrt{a}}$ on $I_3$. We can extend this to one of the boundary points of the respective intervals, and thus obtain
$$f(x) = \begin{cases} \sqrt{a}\cdot x &, \frac{1}{a} \leqslant x < \frac{1}{\sqrt{a}} \\ \frac{\sqrt{a}}{x} &, \frac{1}{\sqrt{a}} \leqslant x < 1 \\ 1 &, x = 1 \\ \frac{1}{\sqrt{a}\cdot x} &, 1 < x \leqslant \sqrt{a} \\ \frac{x}{\sqrt{a}} &, \sqrt{a} < x \leqslant a.\end{cases}$$
This function satisfies the requirements.
Comment: About your example, for $\frac{1}{a} \leqslant x < \frac{1}{\sqrt{a}}, f^{-1}(x)= \frac 1 {\sqrt a} x$ and it doesn't seem to follow $f^{-1}(x)=\frac 1 {f(x)}$ requirement
Comment: No, we have $f^{-1}(x) = \frac{1}{\sqrt{a}}x$ on $I_1 = [1/\sqrt{a},1)$, not on $I_0$. Note that $(f^{-1})\lvert_{I_0} = (f\lvert_{I_2})^{-1}$. Pick $x \in [1/a,1/\sqrt{a})$, and let $y = f^{-1}(x)$. That means $f(y) = x$. This can only be for $1 < y \leqslant \sqrt{a}$, and there we have $f(y) = \frac{1}{\sqrt{a}\cdot y}$. Isolating $y$ in $\frac{1}{\sqrt{a}\cdot y} = x$ yields $y = \frac{1}{\sqrt{a}\cdot x} = \frac{1}{f(x)}$.
Answer: If it is continuous, then its inverse is also continuous because it is a composition of continuous functions (by the functional equation). Thus it is a homeomorphism and endpoints map to endpoints.
Comment: I already proved it cannot be continuous. Only 2) and 3) have to be proved
Comment: @EugenCovaci The tears of a stranger are just water. Plus I need to come up to that point before I can take down the rest of the proof.


RHEL 7 security patch installation from tar

Question: Novice Linux guy here

I have a huge (5G) linux-security-patches tar. Upon extracting, I see its got loads of rpms. What is the most efficient way to install them all ? Also, is it same as installing each rpm individually ?
Answer: RPMs should be with rpm or yum. If there is no some kind of install script within the tar file, the simplest (and cleanest) way to install all of them in one go with yum:
yum localinstall *.rpm

Answer: Both rpm & yum support wildcards. In RHEL 7 and later yum is suggested for rpm packages also - it'll handle dependencies better than rpm.
So issue the command:
yum install *rpm
(yum localinstall is not needed in RHEL 6 and later)
Still due to the number of RPMs (you mention loads of them) you might face dependency problems; in that case try to install in batches of fewer RPMs. Move some of them to another directory for example and repeat.


Finding the sign of a dot product

Question: If $|\vec{a}|=2$,  $|\vec{b}|=5$  and $|\vec{a}\times\vec{b}|=8$,
find $(\vec{a }\cdot\vec{b})$
Using $|\vec{a}\times\vec b|^2 + (\vec{a }\cdot\vec{b})^2=|\vec{a}|^2|\vec{b}|^2$
we get two answers +6 and -6. Are both of them correct or should we take the positive value?
Answer: If you have vectors $\vec a$ and $\vec b$ that satisfy the given conditions, then replacing $\vec a$ by its inverse will flip the sign of $\vec a\cdot \vec b$, but leave the givens unchanged.
So you can't hope to find the sign of $\vec a\cdot \vec b$ based on those given values.
Answer: This question is equal to say:

One parallelogram has sides with lengths $2$ and $5$, and area $8$, what is the angle between them?

And it's clear that we have two answer:
Answer: The fact that $\vec{a}$ and $\vec{b}$ are vectors is really a red herring.  With the  information given, the equation is $64+ x^2= 100$ so $x^2= 36$ which has roots x= 6 and x= -6.  There is no reason why the dot product of two vectors cannot be negative so both are solutions.
Answer: Both of them are correct since $$\vec|a\times\vec b| = 8 \implies ||a||b|\sin\theta| = 8 \implies |sin \theta| = \frac{4}{5}$$
So $$\sin \theta = \pm \frac{4}{5} \implies \cos \theta = \pm \frac{3}{5}$$
Thus,$$(\vec a \cdot \vec b) = |a||b|\cos\theta = \pm 6$$
Comment: That's not really a valid argument that both signs are possible -- your calculations show (like the OPs do) that the dot product must be one of $-6$ and $6$, but not that both results are _possible_.
Answer: You said this:
$$|\vec{a}\times\vec b|^2 + (\vec{a }\cdot\vec{b})^2=|\vec{a}|^2|\vec{b}|^2$$
But you did omit intermediate steps to reach the conclusion:
$|\vec{a}\times\vec b|^2 + (\vec{a }\cdot\vec{b})^2=|\vec{a}|^2|\vec{b}|^2\sin(\alpha)^2+|\vec{a}|^2|\vec{b}|^2\cos(\alpha)^2=|\vec{a}|^2|\vec{b}|^2(\sin(\alpha)^2+\cos(\alpha)^2)=|\vec{a}|^2|\vec{b}|^2$
The key here is the 1-sized circle equation relating sin and cos:
$$(\sin(\alpha)^2+\cos(\alpha)^2) = 1$$
So: Provided you use always the same angle (i.e. the same order between vectors a and b), that will be true due to the identity. If you have two different values, it is because you can choose to multiply a with b, or b with a (getting $\alpha = |\alpha|$ or $\alpha = -|\alpha|$). You must take that into account beforehand: $\alpha$ will be determined by the operands order, and will determine the sign of both products operations. Finally: Yes, both values will be valid depending on the quadrant of $\alpha$.

Finding the sign of a dot product


C# Exception Handling specific classes

Question: What is the main advantage to have specific exception classes , as we can have all exceptions in System.Exception class.
Why would one use specific error handling class?
Comment: What is the main advantage to have classes at all, as we can have all objects as System.Object class? Why would one use specific classes at all? :)
Comment: just came out of interview?
Comment: Possible duplicate of [When should we create our own java exception classes?](https://stackoverflow.com/questions/22698584/when-should-we-create-our-own-java-exception-classes)
Comment: @farrukhmask: The linked potential duplicate question primarily answers exactly that.  Did you read it?
Comment: The answer really depends on your needs - sometimes you need things to be more granular.
Comment: If you want to add specific structured information to your exception, a custom exception class allows you to add your own properties.  It also allows consuming code to catch specifically that exception if the logic requires.
Comment: no alex its not a duplicate questions.
Just wana know the fact that what is the use of specic exception classes such as IndexOutOfRangeException and ArgumentException
Answer: Exception handlers work on a class by class basis. If you only had one exception class, you couldn't do this:
<code>try
{
    //Do something that might raise different types of exceptions
}
catch(ArgumentException e1)  //Catch any exception that is an ArgumentException or one its derived types
{
    //Do something to handle the invalid argument
}
catch(NetworkException e2)  //Catch any exception that is a NetworkException or one of its derived types
{
    //Do something to handle the issue with the network
}
catch(Exception e3)
{
    //Do something to log the unexpected exception
    throw;
}
</code>
Note that you should not catch the base exception unless the only thing you are doing is logging it and rethrowing.

C# Exception Handling specific classes


Equivalence of reflexive and weakly compact

Question: In a normed space $X$ is there an equivalence between these two proposition?
$1)$ $X$ is reflexive;
$2)$ $B$, the unit ball of $X$, is weakly compact.
Comment: http://books.google.com/books?id=Hcqm4_lW4EkC&pg=PA75&lpg=PA75&dq=weakly+compact+reflexive&source=bl&ots=_YW7BRi8tl&sig=5_bVXWyr2u_7nApt6vCQ3SWHB14&hl=en&sa=X&ei=UpZaUK_kG6q00AGY-4DABw&ved=0CDwQ6AEwBA#v=onepage&q=weakly%20compact%20reflexive&f=false
Comment: @Nate: I would suggest yours is an answer and not a comment.
Comment: Dear Maria, Since the double dual of $X$ will necessarily be complete, you will need $X$ to be Banach (i.e. normed *and complete*).  Regards,
Comment: Dear Maria, Regarding my previous comment: in fact weak compactness implies complete, as Nate noted in the edit to his answer.  Best wishes,
Answer: Yes.
A proof of this theorem can be found in:

Marian Fabian, Petr Habala, Petr Hajek, Vicente Montesinos Santalucia, Jan Pelant, Vaclav Zizler.  Functional Analysis and Infinite-Dimensional Geometry.

See Theorem 3.31.
Google Books link
Edit: The referenced theorem assumes that $X$ is Banach; however, this automatically follows from either of conditions (1) and (2):

Since $X^{**}$ is always complete, if $X$ is reflexive then it is complete (as noted in Matt E's comment).
Suppose $B$ is weakly compact.  Let $\{x_n\}$ be Cauchy in $X$.  Cauchy sequences are bounded so by rescaling we may assume $\{x_n\} \subset B$.  By weak compactness, $\{x_n\}$ has a weak cluster point $x$.  Fix $\epsilon > 0$ and choose $N$ so large that $\|x_n - x_m\| < \epsilon$ for $n,m \ge N$.  Let $n \ge N$.  Now choose an arbitrary $f \in X^*$ with $\| f \| \le 1$.  As $x$ is a weak cluster point, there exists $m \ge N$ with $|f(x_m) - f(x)| < \epsilon$.  We also have $|f(x_m) - f(x_n)| \le \|x_m - x_n\| < \epsilon$.  Hence $|f(x_n) - f(x)| < 2 \epsilon$.  Taking the supremum over $f$ and using the Hahn-Banach theorem, we have $\|x_n - x\| < 2 \epsilon$.  Thus $x_n \to x$ in norm, and we have shown that $X$ is complete.
Comment: Dear Nate, As you know, you need $X$ to be complete (i.e. a Banach space), not merely normed.  Regards,
Comment: @MattE: You actually don't; completeness follows from either of the given conditions.  I added a proof.
Comment: Dear Nate, Thanks for this; I hadn't realized that weak compactness of the unit ball implies completeness.  Best wishes, Matt
Comment: Hi, the following link says that it could be the case that a closed and convex subset of unit ball in L^1 is weakly compact?So the theorem does not apply to this case? http://math.stackexchange.com/questions/420778/l1-weak-topology
Comment: @user91360: In that question, it is shown that a *particular* closed convex subset $S$ of the unit ball (defined in the question) is weakly compact.  It is not claimed, and not true, that *every* closed convex subset of the unit ball of $L^1$ is weakly compact.  In particular, the unit ball itself is not weakly compact in $L^1$.  There is no contradiction here.
Comment: Thanks. If in that question, the functions are bounded by 1 everywhere is replaced by almost everywhere, that claim is still true? What is the most important element for that particular set to be weakly compact?
Comment: @user91360: Yes, almost everywhere would be fine.  The key point is that the set is bounded in $L^p$ norm for some $p > 1$ (here we can take $p=\infty$).  More generally, you can look at the [Dunford-Pettis theorem](http://math.stackexchange.com/questions/134376/dunford-pettis-theorem) which says that the essential condition for weak compactness is uniform integrability; when working with a finite measure, an $L^p$ bounded set ($p > 1$) is always uniformly integrable.
Comment: Thanks. This would be very helpful.


Updating zoom parameters in onTouchEvent ImageView class that hosts a drawable

Question: I was able to use a class created by one of the StackOverflow users for my needs.
The class was working fine, but It did not include scrolling(vertically, horizontally). I modified the following class by including the code under MotionEvent.Action_Up , which now provides scrolling both horizontally and vertically. The main problem I am having is with the ZOOM mode.
If you look closely, Zoom mode happens on MotionEvent.ACTION_POINTER_DOWN:
The logic is that it calculates the distance between two fingers and figures out the midpoint between them on the midpoint method. The center of the Zoom must be this midpoint. The code under MotionEvent.ACTION_POINTER_DOWN takes care of
saving and scaling the matrix.
This class is an ImageView and it hosts a drawable graph. The graph draws nicely and the horizontal and vertical scrolling are now enabled, but the zoom is causing problems: When the drawable loads and I try zooming it works fine, but if I try scrolling after that, the drawable gets lost in the view. Likewise, when I scroll at first and then Zoom, the drawable gets lost in the view very fast. It seems like the matrix changes the ImageView coordinates and therefore the midpoint is not the one that I need as the origin of the zoom.
Inside the drawable class onDraw() I implement the following logic:
canvas.save();

    GraphImage.translateX = GraphImage.translateX + MainActivity.keeper14;
    GraphImage.translateY = GraphImage.translateY + MainActivity.keeper15;

    canvas.translate(GraphImage.translateX, GraphImage.translateY);
    canvas.scale(GraphImage.main_scale, GraphImage.main_scale, MainActivity.middy.x , MainActivity.middy.y);

//do my draw calls here

MainActivity.keeper14 = GraphImage.translateX;
MainActivity.keeper15 = GraphImage.translateY;

canvas.restore();

As you can see, I use values updated inside the ImageView onTouch method.
I think the problem might be that the matrix is not coordinating well with the
canvas.scale()  and canvas.translate() calls.
Here is the ImageView class. By the way, what is the purpose of the matrix in this class. Does it work only on the ImageView or also on the drawable that it has? Also, I use a scaleType = Matrix for this view.
public class GraphImage extends android.support.v7.widget.AppCompatImageView {

Paint paint;
Context c;
int color;
Matrix matrix;
Matrix savedMatrix;
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
static PointF start,mid;
float oldDist;
static float main_scale;
static float translateX,translateY;
String savedItemClicked;
String TAG = "Batman";
float mx , my, curX, curY;

public GraphImage(Context context, AttributeSet attrs) {
    super(context,attrs);
    //all the variables are init here
    setFocusable(true);

}

@Override
public boolean onTouchEvent(MotionEvent event) {

    dumpEvent(event);

    // Handle touch events here...
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            mx = event.getX();
            my = event.getY();
            savedMatrix.set(matrix);
            start.set(event.getX(), event.getY());
            Log.d(TAG, "mode=DRAG");
            mode = DRAG;
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            oldDist = spacing(event);
            Log.d(TAG, "oldDist=" + oldDist);
            if (oldDist > 10f) {
                savedMatrix.set(matrix);
                midPoint(MainActivity.middy, event);
                mode = ZOOM;
                Log.d(TAG, "mode=ZOOM");
            }
            break;
        case MotionEvent.ACTION_UP:
            curX = event.getX();
            curY = event.getY();
            matrix.set(savedMatrix);
            matrix.postTranslate(curX - mx, curY - my);
            translateX = curX - mx;//event.getX() - start.x;
            translateY = curY - my;//event.getY() - start.y;
            this.invalidateDrawable(this.getDrawable());
            break;
        case MotionEvent.ACTION_POINTER_UP:
            mode = NONE;
            Log.d(TAG, "mode=NONE");
            break;
        case MotionEvent.ACTION_MOVE:
            if (mode == DRAG) {

                // ...
                /*
                matrix.set(savedMatrix);
                matrix.postTranslate(event.getX() - start.x, event.getY()
                        - start.y);
                translateX = event.getX() - start.x;
                        translateY = event.getY() - start.y;
                                this.invalidateDrawable(this.getDrawable());
                                */

            } else
            if (mode == ZOOM) {
                float newDist = spacing(event);
                Log.d(TAG, "newDist=" + newDist);
                if (newDist > 10f) {
                    matrix.set(savedMatrix);
                    float scale = newDist / oldDist;
                    main_scale = scale;
                    matrix.postScale(scale, scale, MainActivity.middy.x, MainActivity.middy.y);
                    this.invalidateDrawable(this.getDrawable());
                }

            }

            break;

    }

    this.setImageMatrix(matrix);
    //invalidate();
    return true;
}

/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
    float x = event.getX(0) - event.getX(1);// Math.abs(event.getX() - mx);//event.getX(0) - event.getX(1);
    float y = event.getY(0) - event.getY(1);//Math.abs(event.getY() - my);//event.getY(0) - event.getY(1);
    return  (float)Math.sqrt(x * x + y * y);
}

/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
    float x = event.getX(0) + event.getX(1);//mx + event.getX();//event.getX(0) + event.getX(1);//
    float y = event.getY(0) + event.getY(1);//my + event.getY();//event.getY(0) + event.getY(1);
    point.set(x / 2, y / 2);
    MainActivity.middy = point;
}

private void dumpEvent(MotionEvent event) {
    String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
            "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
    StringBuilder sb = new StringBuilder();
    int action = event.getAction();
    int actionCode = action & MotionEvent.ACTION_MASK;
    sb.append("event ACTION_").append(names[actionCode]);
    if (actionCode == MotionEvent.ACTION_POINTER_DOWN
            || actionCode == MotionEvent.ACTION_POINTER_UP) {
        sb.append("(pid ").append(
                action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
        sb.append(")");
    }
    sb.append("[");
    for (int i = 0; i < event.getPointerCount(); i++) {
        sb.append("#").append(i);
        sb.append("(pid ").append(event.getPointerId(i));
        sb.append(")=").append((int) event.getX(i));
        sb.append(",").append((int) event.getY(i));
        if (i + 1 < event.getPointerCount())
            sb.append(";");
    }
    sb.append("]");
    Log.d(TAG, sb.toString());
}

}
Thanks for any suggestions
Answer: I added a few static variables on MainActivity class: translationXX, translationYY , drawing__scale.
Whenever ACTION_UP came up, I updated translationXX and translationYY, as such:
translationXX = translationXX + (curX - mx); //Likewise for translationYY

To coordinate with the changes that occurred whenever the drawable was invalidated:
canvas.translate(MainActivity.translationXX , MainActivity.translationYY);// inside onDraw of the drawable

Likewise, for zoom: Instead of MainActivity.middy as the midpoint of the finger placement on the screen that signified a zoom gesture, I went back to the variable static "mid" defined on GraphImage class. It happened that Mainactivity.middy kept the
old values assigned to it when the mode was ZOOM. Therefore, the zoom was really not doing good things. Inside the method midpoint of the GraphImage class I replaced the following line:
MainActivity.middy = point;

with the line:
mid = point;

To coordinate the zoom  changes that took place inside GraphImage, inside my drawable class onDraw method I scaled the canvas, as such:
canvas.scale(MainActivity.drawing_scale, MainActivity.drawing_scale, GraphImage.mid.x,GraphImage.mid.y);//MainActivity.drawing_scale was updated when the mode was ZOOM inside the onTouch method of GraphImage

Also, inside ACTION_POINTER_UP: I had to invalidate the drawable since without this
the drawable would zoom as ACTION_MOVE was being called but then, it went back to its previous non-zoom state as soon as the fingers stopped touching the screen.
inside ACTION_POINTER_UP:
MainActivity.middy = mid; //this line was called on ACTION_MOVE  when the mode = ZOOM

matrix.postScale(MainActivity.drawing_scale, MainActivity.drawing_scale,MainActivity.middy.x,MainActivity.middy.y)//middy was updated with the latest midpoint "mid" on a previous called to ZOOM inside ACTION_MOVE

After this line we simply call invalidate on the drawable. Also, I created a Boolean called moveit = false inside the onTouch(). Whenever ZOOM mode was on, moveit = true
Whenever ACTION_UP was called it would excute the code needed for the translation of the drawable only if(!moveit){//code that translates drawable}
 This changes provide an acceptable view that zooms and scrolls in all directions. I might need to use the onFling() of the GestureDetector class to make it feel more realistic but it works very well. I avoided the nested scrolling (vertical and horizontal). But, I still will like to learn more about the details on using a matrix.


Post image using UrlRequest in Kivy

Question: How to make post image request using urlrequest in Kivy (Python).
How to open a image and send and
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Answer: Well I tried to  use the URLRequest witch is supported by kivy, but couldn't make post with image so i used threading to make a post, using request in the background while the camera is open and don't freeze when we make the upload.
Part of code: https://github.com/c-mike/kivy-Image-Request

Post image using UrlRequest in Kivy


Remove all zero rows and columns in one go in Python

Question: I want to remove all zero rows and columns in one line from the array A1. I present the current and expected outputs.
import numpy as np

A1=np.array([[0, 0, 0],
            [0, 1, 2],
            [0, 3, 4]])

A1 = A1[~np.all(A1 == 0, axis=0)]
print([A1])

The current output is
[array([[0, 1, 2],
       [0, 3, 4]])]

The expected output is
[array([[1, 2],
        [3, 4]])]

Comment: Are you sure the example outputs are from the same A1 matrix? I don't see 2 and 4 in there.
Comment: A1[~np.all(A1 != 0, axis=0)] ?
Answer: Not really sure your example works, but given the description in the title - for a matrix matrix, you can use
mask = matrix != 0
new_matrix = matrix[np.ix_(mask.any(1), mask.any(0))]

you can check out this post about np.ix_


the best practice to integrate arFragment (sceneForm) with existing Fragment APP

Question: We have been working on adding AR features to our existing APP for a couple of months with limited progress. Very excited to read the recent development from google on sceneForm and arFragment. our current APP consists three Fragments and one of them will need AR features.
It looks straight forward to us,so We replaced the Fragment in our APP with arFragment. The build is successful and stopped during running with little information for debugging. any suggestion on the proper steps for us to upgrade from Fragment to arFragment? or maybe I missed the points of arFragment here?
in order to show the problem without for you to go through our length code (yet valuable to us), we constructed a dummy project based on the sample project from Google: HelloSceneform. Basically, we changed the static Fragment to dynamic Fragment. Only two files are changed and two files are added, which are attached thereafter. The modified project can be built successfully, but stopped when starting to run.
Thank you
Peter
/////// File modified, HelloSceneformActivity.java:
import android.support.v4.app.FragmentTransaction;

// private ArFragment arFragment;
private ItemOneFragment arFragment;
//arFragment = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.ux_fragment);
arFragment =  ItemOneFragment.newInstance();

//Manually displaying the first fragment - one time only
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_layout, arFragment);
transaction.commit();

/////// File modified, activity_ux.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".HelloSceneformActivity">

</FrameLayout>

////// File added   fragment_item_one.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frame_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ItemOneFragment">
</FrameLayout>

/////// File added, ItemOneragment.java:
package com.google.ar.sceneform.samples.hellosceneform;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.ar.sceneform.ux.ArFragment;

public class ItemOneFragment extends ArFragment {

  public static ItemOneFragment newInstance() {
    ItemOneFragment fragment = new ItemOneFragment();
    return fragment;
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_item_one, container, false);
  }

}
Comment: Can you share what the problem is? This isn't a lot of information to understand your question.
Comment: Hi Clayton, Thank you for the response. in order to show the problem without for you to go through our length code (yet valuable to us), we constructed a dummy project based on the sample project  from Google: HelloSceneform. Basically, we changed the static Fragment to dynamic Fragment. Only two files are changed and two files are added, which are attached thereafter. The modified project can be built successfully, but  stopped when starting to run.
Comment: Where you able to achieve it ?
Answer: I have experienced the same when I try to add the ArFragment dynamically to my activity.
It is crashing because I was trying to access the ArSceneView right after I commit the fragment which appeared to be null at that point.
The solution that worked for me was to implement a completion listener that will provide a callback in the Activity when the fragment is done configuring the ARSession.
Below is the basic idea.
public class MyActivity implements MyArFragment.OnCompletionListener{

     @Override
     protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
      getSupportFragmentManager().beginTransaction().add(R.id.fragment_holder,  new
        MyArFragment(), "my_arfragment").commit();
     }

     @Override
     public void onComplete() {
       ArFragment arFragment = (ArFragment) getSupportFragmentManager().findFragmentByTag("my_arfragment");
       ArSceneView view = arFragment.getArSceneView();
       Scene scene = view.getScene();
       scene.addOnUpdateListener(this::onUpdateFrame);
     }
}

And the fragment:
public class MyFragment extends ArFragment{
  public static interface OnCompleteListener {
        public abstract void onComplete();
  }

  private OnCompleteListener mListener;

   @Override
   public void onAttach(Context context) {
      super.onAttach(context);
      try {
         this.mListener = (OnCompleteListener)context;
      }
      catch (final ClassCastException e) {
         throw new ClassCastException(context.toString() + " must implement
          OnCompleteListener");
      }
   }

   @Override
   protected Config getSessionConfiguration(Session session) {
      //Update session config...
      mListener.onComplete();
      return config;
   }

}

Answer: In one of my project I've used the following structure to accomplish the integration of ArFragment. Maybe this will give you some new hints.
I have a root layout with the first element that is a FrameLayout called "body".
This "body" is used as a placeholder to switch the 3 Fragment that exist into the app.
One of these 3 is called "SimulationFragment" and extends ArFragment of Sceneform.
The corresponding layout is composed by the root FrameLayout with some elements and another nested FrameLayout called "ar_frameLayout".
At Runtime I've changed the implementation of onCreateView for the SimulationFragment with a direct call of super.onCreateView() that gives me the base view of ArFragment (this call initializes also the scene from getArSceneView().getScene()).
After that I've added this view into the container view of the simulation fragment that I've previously inflated and then returned it.
Something like this:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View containerView = inflater.inflate(R.layout.fragment_simulation, container, false);
    FrameLayout arCoreFrameLayout = containerView.findViewById(R.id.ar_core_frame_layout);
    // Inflate the layout for this fragment
    View view = super.onCreateView(inflater, container, savedInstanceState);

    arCoreFrameLayout.addView(view);
    return containerView;
}

Answer: ItemOneFragment extends ArFragment but overrides its onCreateView method to inflate its own layout file. I think that's the problem. ArFragment can't find its ArSceneView and other code elements and will just not work.
Comment: Thank you Steven, for your answer. The bad news is that we still can not make it work following your hint. we are pretty new here and the documentations are NOT supper clear. The good news is that we got what we need. We did not use the framework from ArSenceView, we used the framework of the demonstration "hello_ar_java" and switch displays among one view and two Fragments. It is a  ugly structure to me. but we will stay with it for a while until then :-)
Comment: If you need further help just send me an email. My contact information can be found here: https://www.smartasapps.de/en/contact-us
Answer: I really liked the solution of @kdroider, but he forgot to remove reference to activity in onDetach(), which might be quite important. Also, rewote the code in Kotlin:
import android.content.Context
import com.google.ar.core.Config
import com.google.ar.core.Session
import com.google.ar.sceneform.ux.ArFragment

class AsyncArFragment : ArFragment() {
    private var onArReadyListener: OnArReadyListener? = null

    interface OnArReadyListener {
        fun onArReady()
    }

    override fun getSessionConfiguration(session: Session): Config {
        onArReadyListener?.onArReady()
        return super.getSessionConfiguration(session)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        try {
            onArReadyListener = context as OnArReadyListener
        } catch (e: ClassCastException) {
            throw ClassCastException(context.toString() + " must implement OnArReadyListener")
        }
    }

    override fun onDetach() {
        super.onDetach()
        onArReadyListener = null
    }
}

And don't forget to implement OnArReadyListener interface.
WARNING. Replacing fragments with transaction

AnotherFragment -> AsyncArFragment works okay
AsyncArFragment -> AnotherFragment -> AsyncArFragment doesn't work for some reason (onResume() and then immediately onDestroy() are called). If you know how to fix it, please write in comments.
Answer: For anyone coming here through google (like me):
Depending on your use case it might not be necessary to override the ArFragment - simply make sure to access the scene after arFragment.setOnSessionInitializationListener is called.


What is the use function in c++?

Question: I'm currently reading a c++ book and one of the function is
void fp(char v[]){
   for(char* p = v; *p!=0;p++) use(*p);
}

I wrote this into my editor and compiled it. I also included the headers
#include <iostream>
#include <string.h>

But my terminal returns the following message:
use of undeclared identifier 'use'

I also google it and its nowhere to be found online, the function doesn't exist.
Comment: Apparently you missed something in your book where they wrote a function called `use`. It's not part of any standard library, so it's either something that was written by the book author or a typo. You should re-read that section of the book and its code to see if you can find the mistake.
Comment: Bjarne Stroustrup declared use() somewhere in the book. Its not a standard function in any C/C++ library.
Comment: You are simply iterating over the character string `v` using the pointer `p` until the *nul-termiating* character is encountered passing each character to the `use` function as you go. (which has no special meaning until your write a *type* `use (int c) { /* stuff */ }` function) For example `void use (int c) { printf ("%c has ASCII value %d\n", c, c); }`
Comment: Or for C++ use `std::cout << (char)c << " has ASCII value " << c << '\n';` instead of `printf`...
Comment: @DavidC.Rankin: Wrong sentence on EBCDIC platforms ;-)
Comment: Yep, that's an ASCII only job `:)`
Answer: That's because there is no such standard library function.
The author is either using pseudo-code here, or has defined this function somewhere else in the book.

What is the use function in c++?


Loop and Reference array's elements in a range excel macros

Question: I have a database (table) and need to copy several specific columns to another worksheet (sheet3). In addition, Each column should be pasted in an specific column of sheet3. To accomplish this, I created two arrrays: arrSht contains the headers of the columns to be copied, and Arrcol contains the numbers that reference the columns.
Then, I try to loop through each element of both arrays to find the column, copy and paste it. My try goes as follows:
Sub copia()

Dim f As Range
Dim arrSht, Arrcol As Variant, j As Long

arrSht = Array("a","b","c")
Arrcol = Array(5, 6, 8)

For j = LBound(arrSht) To UBound(arrSht)

Set f = Sheet1.Cells.Find(arrSht(j), searchorder:=xlByRows, LookAt:=xlPart)

 If Not f Is Nothing Then
 Sheet1.Range(f, Sheet1.Cells(Rows.Count, f.Column).End(xlUp)).Copy _
             Sheet3.Range(Sheet3.Cells(2, Arrcol(j)))
 Else
 MsgBox arrSht(j) & "Header not found!"
 End If
Next j
end sub

To clarify, the first iteration of the loop should find the range whose header is "a" (first element of arrSht) and store it in f. Then, copy the column that f corresponds to. And finally paste it in Sheet3 column 5 (i.e. the first element of Arrcol)
when I run the code I get the error: "Method 'Range' of object '_worksheet' failed" in the line that corresponds to Sheet1.Range(f, Sheet1.Cells(Rows.Count, f.Column).End(xlUp)).Copy _
                 Sheet3.Range(Sheet3.Cells(2, Arrcol(j))). So, I am probably referencing the array's element in the wrong way or just writing a wrong loop.
Thank you in advance for your help.
Comment: Not sure but try changing to `Sheet1.Range(f, Sheet1.Cells(Rows.Count, f.Column).End(xlUp)).Copy _
Sheet3.Cells(2, Arrcol(j))`
Answer: In this code...
Sheet3.Range(Sheet3.Cells(2, Arrcol(j)))

...Sheet3.Cells(2, Arrcol(j)) is returning a Range.  You're then passing that to Sheet3.Range as a parameter.
Since you only care about 1 cell, skip the .Range call and just use the .Cells:
Sheet3.Cells(2, Arrcol(j))


How to change method not marked with @Test (mean it is not into current test class), but marked by my annotation

Question: The project has the test Test_FindYNetNewsViaGoogle.java
public class Test_FindYNetNewsViaGoogle extends TestBase {

    @Test
    public void testGoToYNNHomeUrl(){
        app.google().goToGoogleHome();
        app.google().search("class_name");
        app.google().enterSite(webElement2);
        assertThat(app.browser().whatSiteIsOpened(), equalTo("urlYNetNews"));
    }
}

A test scenario includes performance of app.google().search("www.ynetnews.com") that is located in GoogleHelper.class
public class GoogleHelper extends HelperBase{

    private final String googleHomeUrl = "https://www.google.com/";

    public GoogleHelper(WebDriver wd) {super(wd);}

    public void goToGoogleHome() {
        String curUrl = wd.getCurrentUrl();

        if (googleHomeUrl.equals(curUrl)) {return;}
        wd.navigate().to(googleHomeUrl);
    }

    @StaleElementAnnotation(retries = 2, seconds = 1)
    public void search(String search) {
        WebElement we_search = wd.findElemnt(By.className(search));
        click(we_search);
    }

    public void click(WebElement search) {
        // was refresh page
        throw new StaleElementReferenceException("test exception");
    }

    public void enterSite(WebElement url){
            click(url.locator));
    }

}

I special write throw the StaleElementReferenceException exception, in order to image that after the previous step there were refresh of page.
So, to resolve this I need to change search(String) to
public void search(String search) {
    int count = 0;
    while (count < DEFAULT_RETRIES) {
        try {
            ++count;
            return searchService(search);
        } catch (StaleElementReferenceException e) {
            Thread.sleep(1000);
        }
    }
    return null;
}

private void searchService(String search) {
    WebElement we_search = wd.findElemnt(By.className(search));
    click(we_search);
}

This okay if you have few those methods. But if there are many of it. So I think that there is solve in which we can invoke some Listener that can call in this case our initial method by surrounded it with as above written.
I have not found any TestNg listeners can give only test method name where was throw the exception. In my case it is Test_FindYNetNewsViaGoogle.testGoToYNNHomeUrl() and not GoogleHelper.click(WebElement search).
Please assist me!
Comment: why have you added `reflection` as the tag?
Comment: by reflection I want to send reties and timeout values
Answer: First, you need to have a static method to retry the required methods. Maybe you can add this to your GoogleHelper class.
public static void retry(Runnable method, int maxTries, long seconds) throws InterruptedException {
    int count = 0;
    while (count < maxTries) {
        try {
            ++count;
            method.run();
        } catch (RuntimeException e) {
            TimeUnit.SECONDS.sleep(seconds);
        }
    }
}

Now you could use the above method in your test.
public class Test_FindYNetNewsViaGoogle extends TestBase {

    @Test
    public void testGoToYNNHomeUrl(){
        app.google().goToGoogleHome();
        GoogleHelper.retry(() -> app.google().search("class_name"), 2 , 1);
        app.google().enterSite(webElement2);
        assertThat(app.browser().whatSiteIsOpened(), equalTo("urlYNetNews"));
    }
}

Comment: that gets the same result : the String testName = result.getName() returns "testGoToYNNHomeUrl" but not "search".  Because the method "search" is located into business logic class and not test class.
Comment: @MaximS Okay, so you want only the search method to be retried instead of the full test ?
Comment: @MaximS Also, is `StaleElementReferenceException` a runtime exception. From the code I assume it is a runtime exception rather than a compile time exception
Comment: sorry for my late. Yes, you are right - I want only the search method to be retried instead of the full test
Comment: @MaximS does the updated answer solve your question
Comment: Thanks for your full support. I think this is what I need. Now there is no time to check it, because my manager asked me to solve another, more priority problem. I'll get my full answer back in a week.


Looking for simple "WebHelper" C# class

Question: I'm looking for a WebHelper class for C#, one that wraps and stuff all the common requests, such as like POSTing and GETting http requests etc.
Comment: Can you give us more detail on your requirements and needs? Maybe a bit on why built in .Net functionality like Mehrdad points out below doesn't work?
Comment: It works but I want a wrapper around it!
Answer: Aren't System.Net.WebClient and System.Net.WebRequest already doing this for you pretty elegantly?
Comment: Yea, I want like a wrapper for all that though.  I wanna do like string html = WebHelper.Post(string url, Dictionary postdata) etc.etc. I mean I could write my own WebHelper class to do this but I'm sure better ones are out there.
Comment: I agree. These are wrappers around the HttpWebRequest/Response, which is what you'd be doing if you rolled your own "WebHelper."
Comment: `new WebClient().UploadString` pretty much does something like what you want.
Answer: Look at Data Extracting SDK which has features you need.

Looking for simple "WebHelper" C# class


Import Values in lookup Columns in Sharepoint Online using CSOM powershell

Question: I am trying to import values in lookup columns, i have country parent list and a child list which has lookup column as Region, am trying below code but it does not seem work at all, i think i am wrong with the syntax may be
###### Add all functions here##########
foreach($row in $CSVLocation)
{
$item["ABC_x0020_DEF"]=$row.'ABC DEF'

 ##############
#Get the Lookup Item from Parent List
 $LookupItem = $country.GetItems | Where-Object { $row.'Region' -eq $row["Region"]}

if($LookupItem -ne $null)
{
$RegionLookup = New-Object Microsoft.Sharepoint.SPFieldLookupValue($LookupItem.ID,$row.Region)

#Set the Lookup field value
$item["Region"] = $RegionLookup
}
}
}
 ##############
     $item.Update();
     $spoCtx.ExecuteQuery();

Comment: What error you are getting? or What is the output you are getting ?
Comment: Hi Ranadip, i am not getting any error, but i am not getting any value in $LookupItem, and it is not going inside if condition also. that is why all other columns's value are getting imported except the lookup one
Comment: I am using the http://www.sharepointdiary.com/2013/04/import-from-csv-file-to-sharepoint-list-using-powershell.html reference link to accomplish the same, but it doesn't work
Comment: Give a sample file
Answer: First of all, you are not using CSOM object but server side object. It is not Microsoft.SharePoint.SPFieldLookupValue but it is Microsoft.SharePoint.Client.FieldLookupValue.
Create function for finding the right item in items collection.
function Get-Item($Items, $ColumnName, $Value)
{
    foreach ($item in $Items.GetEnumerator())
    {
        if ($item[$ColumnName] -eq $Value)
        {
            return $item
        }
    }

    return $null
}

You are using the method GetItems() incorrectly. It should leverage the CamlQuery object.
$query = New-Object Microsoft.SharePoint.Client.CamlQuery
$LookupItems = $country.GetItems($query)

# Execute query and get items from SharePoint
$spoCtx.Load($LookupItems)
$spoCtx.ExecuteQuery()

You don't have to create this FieldLookupValue object, just set the lookup item ID.
#Get the Lookup Item from Parent List items collection
$LookupItem = Get-Item -Items $LookupItems -ColumnName "Region" -Value $row.'Region'

if($LookupItem -ne $null)
{
    #Set the Lookup field value
    $item["Region"] = $LookupItem.Id
}

Comment: Thank you for the reply,tried this and got error

collection has not been initialized.It has not been requested or the request has not been executed.It may need to be explicitly requested.

$query1 = New-Object Microsoft.SharePoint.Client.CamlQuery
$LookupItems = $list.GetItems($query1)

$LookupItem = $LookupItems | Where-Object { $_["Template_x0020_Regi"].ToString() -eq $row.'Template Region'}

if($LookupItem -ne $null)
{
$RegionLookup = New-Object Microsoft.SharePoint.Client.FieldLookupValue($LookupItem.ID,$row.'Template Region')
 $item["Template_x0020_Regi"] = $LookupItem.ID
}
Comment: I modified my answer. You have to call Load and ExecuteQuery methods to get the items.
Comment: Thank you, no errors now but $Lookupitem is null :(
Comment: See the modification. I added Get-Item function which will find the item in items collection. It seems that Where-Object is not working as expected. Now it should be ok :)
Comment: Sorry to trouble you so much, got this error now
A parameter cannot be found that matches parameter name 'Items'. :( :/
Comment: Did you copy the Get-Item function to your script, right? Where do you get this error? On this line: ``$LookupItem = Get-Item -Items $LookupItems -ColumnName "Region" -Value $row.'Region'``?
Comment: yes getting on this line, as soon i execute this line it throws exceptio


I have deleted Redirect module and have lost alias-to-alias redirects as well as the ability to show aliases in some nodes

Question: I uninstalled and removed the Redirect module using these commands.
<code>vendor/bin/drush un redirect
composer remove drupal/redirect
</code>
This caused me to lose about 15 alias-to-alias redirects.
I have also noticed that now, if I visit /node/1 and click on a link to /node/2, its path alias (/node/my-second-node) is not used.
Would re-installing the Redirect module be enough, or must I retrieve data from a backup as well?
Comment: This is not a duplicate. Here I ask about how to revert problems from deleting it, not if deleting it can cause problems.
Comment: As said in the duplicate the information of the old aliases is lost. But it should be no problem to enter 15 alias-to-alias redirects manually in the Redirect UI once you have the module installed. Redirects from /node/1 to the current alias don't need data, this works automatically when installing the module.
Answer: Restore the site from a backup or replace the redirects manually after reinstalling the module.


Nagios check_udp_ports returning critical: result to scheduled check, runs fine manually

Question: We use a Nagios core 4.3.2 solution on Ubuntu 14.04 to do simple host check monitoring on remote client equipment.  One type of device we use is not availible to ping, but as part of it's proprietary control system has the UDP port 5246 open responding to 'capwap-control'.  I am attempting to use the check_udp_port plugin availible from
https://exchange.nagios.org/directory/Plugins/Network-Protocols/*-TCP-and-UDP-(Generic)/check_udp_port/details
However when trying to implement on a test device it shows as down with Status Information: "CRITICAL:"
No further info is given or any entries in the logs other than the host check was ran.
It uses the nmap utility for the check which requires sudo, I added the entry to the last line of /etc/sudoers to skip password per instructions in the link above.
nagios ALL = NOPASSWD:/usr/local/nagios/libexec/check_udp_port *
Here is how it looks in the define command{
    command_line    sudo $USER1$/check_udp_port -H $HOSTADDRESS$ -p $ARG1$ -s $ARG2$

I turned on debuging and watched the log entries as I ran the check a few times in the nagios web admin, the final output command each time looked perfectly correct.
[1497380591.600863] [2048.1] [pid=1259] **** BEGIN MACRO PROCESSING ***********
[1497380591.600880] [2048.1] [pid=1259] Processing: 'sudo $USER1$/check_udp_port -H $HOSTADDRESS$ -p $ARG1$ -s $ARG2$'
[1497380591.600893] [2048.1] [pid=1259]   Done.  Final output: 'sudo /usr/local/nagios/libexec/check_udp_port -H 188.8.131.52 -p 5246 -s capwap-control'
[1497380591.600901] [2048.1] [pid=1259] **** END MACRO PROCESSING *************

First I checked that the pid was running under the nagios user
 1259 nagios    20   0   37404  17036   2800 S   0.3  0.2  12:21.88 nagios

Then I logged in as nagios user and ran the command from the debug log directly and it runs without issue.
nagios@Monitoring:/usr/local/nagios/libexec$ sudo /usr/local/nagios/libexec/check_udp_port -H 188.8.131.52 -p 5246 -s capwap-control
UDP OK - capwap-control listening on port 5246: 5246/udp open capwap-control

I have tested without the line in sudoers and the system info in nagios changes to an error about requiring sudo as expected.
Even though from command line it runs flawlessly and logs show it is running the command properly it still fails and simply shows "CRITICAL:" for information.
Answer: It could be sudo's requiretty setting. Try adding Defaults:nagios !requiretty to sudoers (or in /etc/sudoers.d somewhere).
A safer option would be to modify the plugin to call nmap via sudo, instead of running the entire plugin through sudo.
Or, better yet, just use the stock check_udp plugin, that doesn't require root/sudo.
Additionally, when testing manually on the command-line, it can be helpful to run your plugin through env -i to simulate what it will do with no $ENV defined.
Comment: Hello, I tried both of your suggestions, but it made no change in what is occuring.  How it shows in the logs looks same as before minus the sudo in front of the plugin command, I made sure to add it before the call to nmap in the plugin itself.

I've also tried to use the built in check_udp plugin but I could not get it to work from CLI or nagios itself.  It always returns a socket timeout no matter the host or port/service with proper send/expect options.


Different outputs using ggpredict for glmer and glmmTMB model

Question: I am trying to predict and graph models with species presence as the response. However I've run into the following problem: the ggpredict outputs are wildly different for the same data in glmer and glmmTMB. However, the estimates and AIC are very similar. These are simplified models only including date (which has been centered and scaled), which seems to be the most problematic to predict.
yntest<- glmer(MYOSOD.P~ jdate.z + I(jdate.z^2) + I(jdate.z^3) +
             (1|area/SiteID), family = binomial,  data = sodpYN)

> summary(yntest)
Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod']
 Family: binomial  ( logit )
Formula: MYOSOD.P ~ jdate.z + I(jdate.z^2) + I(jdate.z^3) + (1 | area/SiteID)
   Data: sodpYN

     AIC      BIC   logLik deviance df.resid
  1260.8   1295.1   -624.4   1248.8     2246

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.0997 -0.3218 -0.2013 -0.1238  9.4445

Random effects:
 Groups      Name        Variance Std.Dev.
 SiteID:area (Intercept) 1.6452   1.2827
 area        (Intercept) 0.6242   0.7901
Number of obs: 2252, groups:  SiteID:area, 27; area, 9

Fixed effects:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  -2.96778    0.39190  -7.573 3.65e-14 ***
jdate.z      -0.72258    0.17915  -4.033 5.50e-05 ***
I(jdate.z^2)  0.10091    0.08068   1.251  0.21102
I(jdate.z^3)  0.25025    0.08506   2.942  0.00326 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Correlation of Fixed Effects:
            (Intr) jdat.z I(.^2)
jdate.z      0.078
I(jdat.z^2) -0.222 -0.154
I(jdat.z^3) -0.071 -0.910  0.199

The glmmTMB model + summary:
Tyntest<- glmmTMB(MYOSOD.P ~ jdate.z + I(jdate.z^2) + I(jdate.z^3) +
                (1|area/SiteID), family = binomial("logit"), data = sodpYN)

> summary(Tyntest)
 Family: binomial  ( logit )
Formula:          MYOSOD.P ~ jdate.z + I(jdate.z^2) + I(jdate.z^3) + (1 | area/SiteID)
Data: sodpYN

     AIC      BIC   logLik deviance df.resid
  1260.8   1295.1   -624.4   1248.8     2246

Random effects:

Conditional model:
 Groups      Name        Variance Std.Dev.
 SiteID:area (Intercept) 1.6490   1.2841
 area        (Intercept) 0.6253   0.7908
Number of obs: 2252, groups:  SiteID:area, 27; area, 9

Conditional model:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  -2.96965    0.39638  -7.492 6.78e-14 ***
jdate.z      -0.72285    0.18250  -3.961 7.47e-05 ***
I(jdate.z^2)  0.10096    0.08221   1.228  0.21941
I(jdate.z^3)  0.25034    0.08662   2.890  0.00385 **
---

ggpredict outputs
testg<-ggpredict(yntest, terms ="jdate.z[all]")
> testg

# Predicted probabilities of MYOSOD.P
# x = jdate.z

     x predicted std.error conf.low conf.high
 -1.95     0.046     0.532    0.017     0.120
 -1.51     0.075     0.405    0.036     0.153
 -1.03     0.084     0.391    0.041     0.165
 -0.58     0.072     0.391    0.035     0.142
 -0.14     0.054     0.390    0.026     0.109
  0.35     0.039     0.399    0.018     0.082
  0.79     0.034     0.404    0.016     0.072
  1.72     0.067     0.471    0.028     0.152

Adjusted for:
* SiteID = 0 (population-level)
*   area = 0 (population-level)

Standard errors are on link-scale (untransformed).

testgTMB<- ggpredict(Tyntest, "jdate.z[all]")
> testgTMB

# Predicted probabilities of MYOSOD.P
# x = jdate.z

     x predicted std.error conf.low conf.high
 -1.95     0.444     0.826    0.137     0.801
 -1.51     0.254     0.612    0.093     0.531
 -1.03     0.136     0.464    0.059     0.280
 -0.58     0.081     0.404    0.038     0.163
 -0.14     0.054     0.395    0.026     0.110
  0.35     0.040     0.402    0.019     0.084
  0.79     0.035     0.406    0.016     0.074
  1.72     0.040     0.444    0.017     0.091

Adjusted for:
* SiteID = NA (population-level)
*   area = NA (population-level)

Standard errors are on link-scale (untransformed).

The estimates are completely different and I have no idea why.
I did try to use both the ggeffects package from CRAN and the developer version in case that changed anything. It did not. I am using the most up to date version of glmmTMB.
This is my first time asking a question here so please let me know if I should provide more information to help explain the problem.
I checked and the issue is the same when using predict instead of ggpredict, which would imply that it is a glmmTMB issue?
GLMER:
 dayplotg<-expand.grid(jdate.z=seq(min(sodp$jdate.z), max(sodp$jdate.z), length=92))
    Dfitg<-predict(yntest, re.form=NA, newdata=dayplotg, type='response')
    dayplotg<-data.frame(dayplotg, Dfitg)
    head(dayplotg)
    > head(dayplotg)
        jdate.z      Dfitg
    1 -1.953206 0.04581691
    2 -1.912873 0.04889584
    3 -1.872540 0.05195598
    4 -1.832207 0.05497553
    5 -1.791875 0.05793307
    6 -1.751542 0.06080781

glmmTMB:
dayplot<-expand.grid(jdate.z=seq(min(sodp$jdate.z), max(sodp$jdate.z), length=92),
                     SiteID=NA,
                     area=NA)

Dfit<-predict(Tyntest,  newdata=dayplot, type='response')
head(Dfit)

dayplot<-data.frame(dayplot, Dfit)
head(dayplot)
> head(dayplot)
    jdate.z SiteID area      Dfit
1 -1.953206     NA   NA 0.4458236
2 -1.912873     NA   NA 0.4251926
3 -1.872540     NA   NA 0.4050944
4 -1.832207     NA   NA 0.3855801
5 -1.791875     NA   NA 0.3666922
6 -1.751542     NA   NA 0.3484646

Comment: If you use `predict()` directly with `type = "response"` do you see a similar issue?  Note you'll need `re.form = NA` for the merMod object for population-level predictions but you'll have to manually set your grouping variables to NA for the glmmTMB objects to get the same (see the help page for `predict.glmmTMB`).
Comment: Yes it is the same using predict, I've edited the above question to reflect that. So it seems like it is a glmmTMB issue perhaps?
Comment: Well, now that I've looked more at the documentation for glmmTMB it says that "Models with different versions of
the same data-dependent basis type in different components (e.g. formula= y ~ poly(x,3), dispformula= ~poly(x,2))
will probably not produce correct predictions."
Comment: Per `r` tag (hover to see): *Use `dput()` for data and specify all non-base packages with `library()` calls.*
Answer: I contacted the ggpredict developer and figured out that if I used poly(jdate.z,3) rather than jdate.z + I(jdate.z^2) + I(jdate.z^3) in the glmmTMB model, the glmer and glmmTMB predictions were the same.
I'll leave this post up even though I was able to answer my own question in case someone else has this question later.
Comment: aaand this bug (your original code *should* have worked, using `poly()` is a workaround) should be fixed soon in the development version: https://github.com/glmmTMB/glmmTMB/issues/512


Integrate with substitution. Evaluate $ \int \frac{\sin\sqrt x}{\sqrt x} \ dx$.

Question: How do I integrate with substitution only this integrand? :
$$ \int \frac{\sin\sqrt x}{\sqrt x} \ dx$$
I tried to solve it with the fact that $$(\sqrt x )'= \frac {1} {2 \sqrt x}$$ But got lost.
Thanks for your help.
Comment: what is "sen" ?
Comment: @RaziehNoori It's commonly used in Italy for the sine function, that we call "seno". I hope this usage will vanish.
Answer: You may just substitute $\sqrt{x}=u$, $\dfrac{1}{2\sqrt{x}}dx=du$ giving
$$
\int\frac{\sin (\sqrt{x})}{\sqrt{x}}dx=2\int\sin (u)\:du=-2\cos (u)+C=-2\cos (\sqrt{x})+C.
$$
Answer: Let $f(x)=-\cos(x)$ and $g(x)=\sqrt{x}$. Then you may write your intégral as
$$
\int \frac{2}{2}\cdot\frac{\sin(\sqrt{x})}{\sqrt{x}}dx=\int 2f^{'}(g(x))g^{'}(x).
$$
From the chain rule, we know an antiderivative for $f^{'}(g(x))g^{'}(x)$ given by $f(g(x))$. Your integral is then
$$
\int \cdot\frac{\sin(\sqrt{x})}{\sqrt{x}}dx=-2(f(g(x))+C)=-2\cos(\sqrt{x})+C
$$
Note that the rightmost $C$ is different than the middle one, but it doesn't matter as $2C$ can be seen as an integration constant.
Answer: Notice, let $$\sqrt x=t\implies \frac{dx}{2\sqrt x}=dt$$$$\frac{dx}{2t}=dt\iff dx=2tdt$$ Now, substituting $\sqrt x=t$ & $dx=2tdt$ we get $$\int \frac{\sin(\sqrt x) \ dx}{\sqrt x}dx$$$$=\int \frac{\sin t\ (2tdt)}{t}$$ $$=2\int \sin t\ dt=2(-\cos t)+C$$
$$=\color{red}{-2\cos (\sqrt x)+C}$$


An infinite fraction

Question: Here's a problem I saw on the AoPS twitter. I thought I might as well post it so that it could be discussed and a solution recorded.
What is the value of the following?
$$\cfrac{4}{{1 + \cfrac{1^2}{2 + \cfrac{3^2}{2 + \cfrac{5^2}{2 + \cfrac{7^2}{2 +  \cfrac{9^2}{\ddots} }}}}}}$$
As an aside, I find it cool that it can be compressed to the size of a tweet. The actual tweet is just this single line of symbols and nothing more:
$$4 / (1 + (1^2/(2 + 3^2/(2 + 5^2/(2 + 7^2/(2 + 9^2/(2 + ... ) ) ) ) ) ) ).$$
Comment: Better? ${}{}{}{}$
Comment: Long live `\cfrac`.
Comment: @PeterTamaroff Just click "edit" on the question and look at the code...long live reverse engineering.
Comment: @AsafKaragila How does it work?
Comment: Like `\dfrac`, only it doesn't set the next level of text to have inline font size.
Comment: @FixedPoint I made the edit, just wondered if `\cfrac` was a better option, since I don't know how it works.
Comment: @Peter: Less braces. Take a look.
Answer: $$\arctan(x) = \cfrac{x}{1+\cfrac{1^2x^2}{3-x^2+\cfrac{3^2x^2}{5-3x^2+\cfrac{5^2x^2}{7-5x^2 + \cfrac{7^2x^2}{9-7x^2 + \ddots}}}}}$$
Take $x=1$ to get what you want.

EDIT
The proof for the above is the observation that if
$$S_n = a_1 + a_1 a_2 + a_1 a_2a_3 + a_1 a_2 a_3 a_4 + \cdots + (a_1 a_2 \cdots a_n)$$ then
$$S_n = \cfrac{a_1}{1-\cfrac{a_2}{1+a_2 - \cfrac{a_3}{1+a_3 - \cfrac{a_4}{1+a_4 - \ddots \cfrac{a_n}{1+a_n}}}}}$$where the last term ends as $1+a_n$. Hence sending $n \to \infty$, we get that if
$$S = a_1 + a_1 a_2 + a_1 a_2a_3 + a_1 a_2 a_3 a_4 + \cdots + (a_1 a_2 \cdots a_n) + \cdots,$$ then
$$S = \cfrac{a_1}{1-\cfrac{a_2}{1+a_2 - \cfrac{a_3}{1+a_3 - \cfrac{a_4}{1+a_4 - \ddots}}}}$$
Now we know that
$$\arctan(x) = x - \dfrac{x^3}3 + \dfrac{x^5}5 = \cdots$$
Set $a_1 = x$, $a_2 = -\dfrac{x^2}3$, $a_3 = -\dfrac{3x^2}5$ and in general $a_n = - \dfrac{(2n-3)x^2}{2n-1}$ to get what we want.
Comment: Perfect observation. How'd you think of that?
Comment: Would you mind including a derivation? (Also, I miss your old name!)
Comment: @Parth I was brought up as an engineer and hence the secret of all nice innovative novel (an throw in other bunch of adjectives) proofs is reverse engineering :)
Comment: @Potato Sure. Will do it.
Comment: @Potato Done... :)

An infinite fraction


Integral of $\int^1_0\frac{dx}{\sqrt{x+3}-1}$

Question: I want to solve this integral and need some directions.
$$\int^1_0\frac{dx}{\sqrt{x+3}-1}$$
I decided to call $x+3 = t^2  \rightarrow 2tdt = dx$ then : $$\int^1_0 \frac {2tdt}{t^2-1}$$ Now what should I do? call $t^2-1 = u$ ? and do the same thing on u?

Thanks!
Comment: I write it again: $$\int \frac{dx}{\sqrt{x+3}-1}$$ then: $t^2=x+3$ and $t=\sqrt{x+3}$ and the derivative is: $2tdt=dx$ after that we get : $$\int \frac{2tdt}{t-1}$$ now what? I can seperate them like : $$\int (2+ \frac{2}{t-1})dt$$?
Comment: Indeed. You could write this as an answer to your own question (presumably you know how to do the last integral).
Comment: OK, but after I do that I get this: $$\int^1_0 \frac{du}{u} \rightarrow ln|t^2-1| = ln|x+3-1| = ln|x+2| $$ and this is not the F(x) of this function.
Comment: You have got your expression wrong in the second expression. $\sqrt{x+3}=t$ right? Your expression is $\int\dfrac{2tdt}{t-1}$
Comment: no I set it $t^2$ ( without the square root ).
Comment: Your $x+3$ is $t^2$ , but $\sqrt{x+3}$ is $t$.
Comment: One of my pet peeves: Integrals aren't "solved", they are computed/evaluated.
Answer: Hints:
Plug in $\sqrt{x+3}=t^2$, $dx=4t^3 dt$
$\int \dfrac{4t^3}{t^2-1}=\int\dfrac{2t^2}{t-1}+ \int\dfrac{2t^2}{t+1}$
Now use integration by parts for the each of the expression.
Answer: Let  $\sqrt{x+3}-1=t\implies x=(t+1)^2-3=t^2+2t-2\implies dx=2(t+1)dt$
If $x=0\implies t=\sqrt{3}-1, x=1\implies t=\sqrt{1+3}-1=1$
$$\int^1_0\frac{dx}{\sqrt{x+3}-1}=\int_{\sqrt3-1}^1\frac{2(t+1)}t dt$$
$$=2\int_{\sqrt3-1}^1\left(1+\frac1t\right) dt$$
Can you take it from here?


Does an average person know to switch to head/falsetto voice if a note is too high?

Question: I'm planning to lead a small congregation in musical worship soon, just me and a guitar. I'd say the average person there is above average in singing ability simply by virtue of singing at church regularly, several also sing and play instruments.
However I'm still nervous of pushing the pitch high enough that some men might be beyond their natural range, one song in particular is quite low but has a high bridge with a big sustained E4. For me that's a comfortable power note right at the top of my chest voice but even a few months ago before I started vocal lessons it wouldn't have been.
I'm wondering if congregationally this is OK and people will naturally falseto that note or drop down, or will be awkward as half the men struggle.
I don't believe the song can easily be dropped a tone as then it is too low in the verse.
What advice would people offer - is this a problem and what should I do about it? I need to be able to sing confidently but so does the congregation.
Comment: @Mr.Boy It's not _exactly_ a dupe, is it?  (And I'm hesitant to push it any more, in case people think I'm just trying to promote my excellent-but-IMHO-underrated answer to it :-)
Comment: Also is their a tag for "people singing who aren't singing" e.g. congregation, audience sing-along, etc?
Comment: The "average person" can hardly sing in tune :-( .  Just having sung for years in some random choir is no guarantee of musical ability.   Why not move the offending part to the altos and save the worry?
Comment: @CarlWitthoft there are no parts, or altos. Just me and my guitar leading the congregation. And I'm just guiding people, not performing to them. Though you're right - probably they are quite a bit above average, most can sing at least in tune most of the time
Comment: I had similar problems on occasions with choirs and public. Solution - choose a more suitable song.
Comment: Can you run small auditions, and target that passage with the high note? Then for those who do find it too high, coach them through switching?
Comment: Seems strongly related to [this question](/questions/114819/vocal-range-of-a-crowd).
Comment: @gidds you should link that as a dupe :)
Answer: An "average person" (by which you mean a man) may accidentally flip into falsetto and then stop singing.  He will not have either good tone quality or pitch control in falsetto.  When somewhat more experienced, he will strain his voice in order not to get into falsetto.
You'll already have a problem getting an average man to sing from the diaphragm since that will push out his belly instead of his chest.
Getting a sizable group of average males to agree to singing falsetto is likely as much work as getting a sizable group of average females to appear without makeup.  It's a self-image thing.  For some it will be a no-brainer, for some it will mean that they silently stop turning up altogether.
Maybe try finding alternative notes to sing for the exposed passages, and if all else fails, a different piece.
Comment: Women just have a single register?
Comment: @Mr.Boy No, not true. Women do have at least two or more registers *(some argue that women do not have a "falsetto range", but there's at least something similar, whatever one decides to call it)*.
Answer: I've in a very similar position, except I play piano, and can't sing that well.
From my experience, these songs can be really hard to lead. They're often written by male singers with a high voice and a full band behind them. So they are hard to translate to an average congregation.
You've already mentioned changing the key. It's usually my first port of call, but if the range is too big, it's not possible. I'd then consider changing the bridge melody to a lower harmony (I did this last week with a song). If that doesn't work, can you drop the bridge altogether, or make it an instrumental break? The final option would be to find another song. It's rarely my preferred option, but some songs that sound really great on the recording just don't work when you have limited resources.
Answer: Agreed!
user33593 hit the nail on the head. Most untrained male voices will 'strain', rather than sing in their "young boy's voice"/falsetto.  The general rule of thumb in worship singing is to choose keys (transpose if you need to) that suit the majority of singers.  As an aside, and if coaching singers for this reason or others, let's also try and avoid disseminating the unfortunate "sing from the diaphragm" misnomer and focus on breathing into the lower abdominals and obliques, and allowing lower rib expansion, ensuring one's rear-end isn't "sway backed", etc.


Change div content and url on single click using jquery

Question: I am very new to jquery.
I just need to update div content and link url on single click.
here I am working on this code.

$14.50

$15.50

$16.50

$20.50

I need to update price div based on above link click.

$0.00

    Pay Now

Thanks
Comment: So what did you already tried?
Answer: You can try something like"

$(".price").on('click', function(){
    var clickedPrice = $(this).data('price');
    $('#result_price').html("$" + clickedPrice);
  });

$9

$5

$3

$0

Answer: Use .class selector and .attr() to change the href.
$('ul > li').click(function(){
   $('.price').html($(this).text());
   $('.buy').attr('href', 'http://google.com');
});

$('ul > li').click(function(){
   $('.price').html($(this).text());
   $('.buy').attr('href', 'http://google.com');
});

$14.50

$15.50

$16.50

$20.50

$0.00

Pay Now
Answer: You can update price div based on ul > li > a click. Try below code
$(document).on('click', 'ul > li > a', function(){
    $('.price').text($(this).text());
});

$(document).on('click', 'ul > li > a', function(){
    $('.price').text($(this).text());
});

$14.50

$15.50

$16.50

$20.50

$0.00

Pay Now

Thank you.


Cálculo do múltiplo de 10 maior ou igual a um valor

Question: Utilizar módulo 10;
Exemplo:
7  4  8  9  3  1  0  7  2 <== Dados
x  x  x  x  x  x  x  x  x
2  1  2  1  2  1  2  1  2 <== Peso
=  =  =  =  =  =  =  =  =
14 4  16 9  6  1  0  7  4 <= Resultado
1+4=5 1+6=7
//resultado da multiplicação, cujo valor for maior que 10 (dez), os dígitos do resultado devem ser
//somados, resultando um valor menor que 10 (dez);

5 4 7 9 6 1 0 7 4 = 43 <== Resultado Final
//Somatório do resultado das multiplicações = 43

Até aqui tudo certo. Agora vem meu problema. Como achar Múltiplo de 10 maior ou igual ao somatório que 43?
Meu código atual:
for (int i = 0; i <= soma; i += 10) {
    if ((i % 10) == 0) {
       if (i >= soma) {
          Multiplo = i;
       }
    }
}

Comment: Não entendi qual é o resultado esperado.
Comment: O valor que você espera encontrar é 50 ?  Não entendi muito bem o que você perguntou.
Comment: @FabrícioSimoneAlanaMendes Sempre que tiver um código poste para ajudar as pessoas entenderem o problema e até onde você chegou.
Comment: isso mesmo, preciso encontrar, 50 veja meu cód.
for (int i = 0; i <= soma; i += 10)
{
                if ((i % 10) == 0)
                {
                    if (i >= soma)
                    {
                        Multiplo = i;
                    }
                }
            }
Comment: Não é necessário verificar se `i mod 10` é igual a 0, pois você sempre incrementa a variável com 10.
Answer: Para encontrar o multiplo de 10 mais próximo, você pode fazer uso do seguinte pseudo-código:
int multiplo;
if(quociente % 10 != 0)
{
  int quociente = soma / 10;
  multiplo = (quociente+1)*10;
} else
{
  multiplo = soma;
}

A primeira variável vai pegar apenas a parte inteira do quociente da divisão por 10, e então o multiplo mais próximo é o sucessor do quociente multiplicado por 10.
Evitei de declará-las na mesma linha para evitar qualquer problema com declaração simultânea das variáveis, já que uma depende da outra, se a dependência não existe, ocorre erro.
Comment: Bem tinha chegado ao resultado com uma POG, kkk Mas esse seu cód é muito mais enxuto. valeu, Deu certo aqui. Bem agora tenho que calcular o 2º e o 3º campo da linha digital. Af
Comment: Haha, sem problemas.
Comment: @mutlei, parece-me que esta resposta falha quando a soma já é multiplo de 10.
Comment: @JJoao verdade... Corrigindo.
Answer: Sei que é antigo mas tem um jeito mais simples....
if(soma%10==0){
    multiplo = soma;
}else{
    multiplo = (soma-(soma%10))+10
}

Comment: Porquê o downvote?
Comment: @DarioTeodoro, sua resposta é completamente válida. O comentário do ramaral foi direcionado para o usuário que votou negativamente na sua resposta.
Comment: @GuilhermeNascimento, talvez tenha sido por isso. Não acho que seja razão suficiente, o código é fácil de entender. Além que deve ser levado em consideração o facto do AR ser novo por aqui.
Comment: Foi só para registrar mais uma alternativa de calculo.
Comment: @ramaral Eu não sei o motivo, mas suponho que quem negativou foi porque só apresentou o código, mas não explicou o cálculo, fora que se olharem bem as variaveis tinham (eu editei) acentos.
Comment: @GuilhermeNascimento E que não há problemas em criar variáveis com acento.
Comment: @jbueno não estou habituado ao c#, só comentei isto pois imagino que na maior parte das linguagens a sequencia de caracteres para criar uma variavel seja `[a-z][a-z0-9_]`


Add Glyphicon to titles?

Question: I am attempting to add glyphicon options to titles. Is there a way I can add a field to a content type in order to render the html showing the glyphicon? I am trying to add it to just the basic page content type and the page it shows on title click.
I tried adding a select list with the  inside as options for example, but it would not render the html.
EDIT:::
I tried the title html module, but it only allows a few elements. I would ideally like to add a select list to my content type that contains all the glyphicons i'd like to use on the page and i could just select which one to show before the title from that select list. It would then show the glyphicon before the title on save.
Comment: can you clarify the question a bit?

You want to have HTML in your title fields?
Comment: @jdu Updated the question a little.
Answer: I think you're on the right track with adding a second custom field to allow the user to choose the glyph.
Once the user has set the title, selected the glyph and saved,  you can merge the two using a template file.
https://api.drupal.org/api/drupal/modules!field!theme!field.tpl.php/7
The one you'd want I think would be named something like this:  field--title--basic-page.tpl.php
In there, you can stick the value of the glyph next to the title.  Does that make sense?
Comment: I'll give that a shot. Any example code you might have?
Comment: This exact approach is going to be tricky because the title for node pages isn't rendered out in the node template (it's in the page template).
Answer: an easier way to do this will be using this module:
Icon API

Add Glyphicon to titles?


Prove that function transforms $S$ into $S$

Question: I have to prove, that function $\Phi(z):=\frac{1-\overline a z}{z-a}$ transforms $S$ into $S$ where $S:=\{|z|=1\}$ and $|a|>1$
I don't know where can I start. Any hint?
Comment: Hint: If $|z| = 1$, then $\dfrac{1}{z} = \bar{z}$.
Answer: Factor out the $z$ from the numerator, so you have $$z(\dfrac{1}{z} - \bar{a})$$
in the numerator. Now, what happens when you use the hint I gave you in the comment? Can you figure it out from there?
Answer: If $|z|=1$ then $$\Phi(z)=\frac{z(\overline z - \overline a)}{z-a}=\frac{z \overline{(z - a)}}{z-a}$$
And now $|\cdot|$ of the right hand side is equal to 1. Thanks!


apply jQuery on specific resolution

Question: I am using jQuery for mobile Hamburger menu:
jQuery( function($) { 'use strict;
$( '
≡

' ).insertBefore( 'nav.nav-header ul.genesis-nav-menu' );

$( 'nav.nav-header ul.genesis-nav-menu' ).addClass( 'hide' );

$('#header-mobile-menu').on( 'click', function() {
    $('nav.nav-header ul.genesis-nav-menu').slideToggle();
    $(this).toggleClass('active');
});

});

The problem is that the menu doesn't close itself after been clicked. So I have added this:
    $('.menu-item').on( 'click', function() {
    $('nav.nav-header ul.genesis-nav-menu').slideToggle();
    $('#header-mobile-menu').toggleClass('hide');

But now its being aplied to all resolutions. And it is not good. So I tried to change it with this:
if($(window).width() < 992 ){}

And the final look would be:

jQuery( function($) { 'use strict';
// Insert mobile menu before the Genesis Header Right widget navigation menu
$( '
≡

' ).insertBefore( 'nav.nav-header ul.genesis-nav-menu' );

// Add .hide class to .nav-header .genesis-nav-menu to hide it for small screen sizes
$( 'nav.nav-header ul.genesis-nav-menu' ).addClass( 'hide' );

// Toggle Header Right widget navigation menu for mobile menu
$('#header-mobile-menu').on( 'click', function() {
    $('nav.nav-header ul.genesis-nav-menu').slideToggle();
    $(this).toggleClass('active');
});

    if($(window).width() < 992 ){
// Hide Header Right widget navigation menu for mobile menu if clicked
    $('.menu-item').on( 'click', function() {
    $('nav.nav-header ul.genesis-nav-menu').slideToggle();
    $('#header-mobile-menu').toggleClass('hide');
})};

});

And its not working... Please help who knows jQuery syntax.
Comment: Can you format your code, and white you're at it, make it a complete inline snippet?
Answer: If you want that click handler to only execute when the window's width is < 992, check inside the handler:
// Hide Header Right widget navigation menu for mobile menu if clicked
$('.menu-item').on( 'click', function() {
    if( $(window).width() < 992 ){
        $('nav.nav-header ul.genesis-nav-menu').slideToggle();
        $('#header-mobile-menu').toggleClass('hide');
    }
});

apply jQuery on specific resolution