Sum of series with binomial

Question: How to calculate
$$\sum_{n=0}^{\infty}\binom{2n}{n}\frac{2n}{2^{2n}(2n-1)}$$
?
I tried to use residues, generating function, combinatorics formulas, but unsuccessfully.
Answer: Hint: $~\displaystyle\sum_{n=0}^{\infty}\binom{2n}{n}~x^n~=~\frac1{\sqrt{1-4x}}~.~$ Now ask yourself how you can employ differentiation
and integration so as to force an extra $~\dfrac{2n}{2n-1}~$ into the formula.
Comment: See [binomial series](http://en.wikipedia.org/wiki/Binomial_series) for more information.
Comment: $\sum_{n=0}^{\infty} \binom{2n}{n} \frac{2n}{2n-1}x^{2n-1}=\int_{0}^{x}\frac{1}{y}\frac{d}{dy}\left(\frac{1}{\sqrt{1-4y^2}}\right)dy$. If $x=\frac{1}{2}$ then we have $\sum_{n=0}^{\infty} \binom{2n}{n} \frac{2n}{2n-1}\frac{1}{2^{2n}}=\infty$.
Comment: @mikis: Yes, $~\displaystyle\sum_{n=0}^{\infty}\binom{2n}{n}~\frac{2n}{2n-1}~x^n~=~\frac{4x}{\sqrt{1-4x}}~,~$ which indeed diverges for $x=\dfrac14~.$
Answer: There is a simple way for proving that your series is divergent. Since:
$$ \frac{1}{4^n}\binom{2n}{n}=\frac{(2n-1)!!}{(2n)!!}=\prod_{k=1}^{n}\frac{2n-1}{2n}\tag{1}$$
it follows that:
$$ (2n+1)\left(\frac{1}{4^n}\binom{2n}{n}\right)^2 = \prod_{k=1}^{n}\left(1-\frac{1}{4n^2}\right)\tag{2} $$
and since the product in the RHS of $(2)$ is convergent, we have that $\frac{1}{4^n}\binom{2n}{n}$ behaves like $\frac{1}{\sqrt{n}}$ for large $n$s, so your series is divergent by the $p$-test. Anyway, a related convergent series is presented in this question.

Sum of series with binomial


Relative Pitch and Solfege

Question: Can one teach themself relative pitch by using solfege?
Any tips or recommendations that I can implement in my journey to learning relative pitch? I understand fixed and moveable do already. Just unsure how to translate effectively to relative pitch.
Comment: Does this answer your question? [Is relative pitch trainable from scratch?](https://music.stackexchange.com/questions/77054/is-relative-pitch-trainable-from-scratch)
Comment: No Brian it doesn't @BrianTowers
Answer: What you bring up is a lovely question that generally comes within the study of ear training, but there are many ways to go about it. I think solfege can definitely help, particularly if you use moveable Do (that's my preference, and I know you can start hours of discussion among musician about the relative--no pun intended--value of moveable Do versus fixed Do solfege). I taught high school music for many years and used moveable Do with my students, to good effect, I believe. You could start by taking melodies you like that you have the written notation for and figuring out the solfege syllables to sing to them. I recommend you start with diatonic melodies until you feel more confident. The next step would be doing the same with melodies you hear, without the written notation. This gets into a very wonderful and valuable activity: transcribing. As a jazz musician, I've had a fair amount of practice doing that, and it always strengthens the ears. Just start simple, and with short examples.  You could also go about this in the opposite direction: try writing a simple melody away from any instrument, directly to score paper. Then try playing what you wrote and see how much you got right! I hope this is helpful--happy learning!
Answer: Yes. There is actually a specific method of ear training that uses solfege to teach to teach relative pitch. The method is most prominent taught by educator Alain Benbassat. He has some software and an app that teaches the method, but you can learn the basics with just a piano.
Here is an introductory lesson you can do at the piano (in the key of C):

Play the tonic note (C), sing the pitch (Do, in solfege), and get it firmly memorized in your mind
Play one the first five notes of the scale (C-D-E-F-G), for example F, and then sing that note in solfege and also sing all the pitches back down to the tonic (Fa-Mi-Re-Do). Practice this repeatedly from each of the first five steps. The key is to hear the tonic in your mind while the new pitch is being played and feel the pull of these notes down to the tonic.
Next, do a similar exercise but using the last for notes of the scale (G-A-B-C). For example, play an A on the piano and then sing the pitch and all the notes back up to the tonic (La-Ti-Do). The key here is to hear the tonic in your mind while new pitch is being played and feel the pull of these notes up to the tonic (Sol is the pivot point and can go either up or down).

Once you master this, the technique begins adding in different keys, different octaves, chromatic pitches, chords, and many other facets of ear training, but the whole technique is based off of the idea of hearing each pitch in relation to a tonic pitch.
Answer: It'll work using solfege, but avoid fixed do, or you could use simple numbers, 1-7.
By initially 'fixing' the first note you hear as 'do', or '1', all the other diatonic notes can be practised with regard to where they are in the diatonic scale.
I say avoid fixed do, but using the method above is a sort of offshoot from that - making your own 'fixed do'. Using fixed do works easily in key C, but I feel there's no need in early stages to consider what the note names, or keys, actually are. That will inevitably come later, especially when chromatic notes, thus non-diatonic intervals are encountered.
Once you can recognise intervals using the lower note as 'do', (or 1), then try considering, say mi to ti - which is the same as do to so, but mentally thinking in a different key. Let's face it, if you're trying to establish notes by relative pitch, the lower one won't always be 'do'.
And don't forget, relative pitch needs to be working descending, too. Here, perhaps you may need to swap the notes round, so the first, now, is heard as the lower. Intervals seem easier to identify going up - rather like it's easier to count up, or say the alphabet, days of the week, months, forwards...
Comment: The system you're describing of "making your own 'fixed do.'" Is called moveable-do, in which you Do can be any pitch.
Comment: @Peter - well aware, thanks! But moveable do in most cases, actually specifies what do is to be. With my 'making up your own do', it could be any note you hear or sing, regardless of what it actually is: no need to reference it on an instrument. If that makes sense.
Comment: Yes, that makes sense, but you're still describing moveable-Do. I'm not implying that you aren't aware, but it would be helpful to the questioner if you included that info.
Comment: This was my first too: use _moveable_ DO
Answer: Yes, it is: absolutely!
After  practicing the scales and modes, intervals and triads try to start with singing and transcribing in movable doremi baby songs, children songs, folksongs church chorals:

songs that start with the root note doremido (frère Jacques)

pentatonic melodies

With up beat so do

With triad domiso

With solasomi (silent night, we shall over come, how many roads ...

then tunes in minor

sing along with doremi when you play piano or guitar.
Try to notate the melody notes and play control you writing by  playing.
sing a song sheet music (Baroque, classic melodies) from sight reading and control by playing.
Notate your own melodies you have in mind: ear training  by reading by writing.
Play along with songs you're listening and notate the tunes (and harmony).
Very helpful is also singing with hand signs showing the pitch lever regarding the root note.
Answer: The aim is to 'grok' music.  To look at (any form of) notation and just KNOW what it will sound like.
Yes, learning to sight-sing using solfege can be very helpful in achieving this.  Also sight-sing from notation.   And try to live in a musical world that constantly uses notation.  The strange fact is that band and orchestra players are often better at sight-singing than singers are!  EVERYTHING they play is from notation.  See-play-hear.  Grokking it just comes naturally.
https://en.wikipedia.org/wiki/Grok
Comment: "...try to live in a musical world that constantly uses notation..." that's such good advice.
Answer: You might consider what the "relative" relationship is comparing.
In moveable DO solfege the point is to relate the syllables to the tonality, where the tones fit into the key. Or, you could say it relates them to the tonic.
That is different that the relative pitch difference of intervals.
For example MI to SOL is a minor third, but to it's also the mediant and dominant of the key and pretty strongly associated with the tonic chord. Note the difference with DO and MA for a minor third on a tonic and minor third above it.
Another example is a minor sixth. In one context it is the major tonic MI up to DO, but if DO is the bottom, then the minor sixth above is LO and suggests a minor key.
To me, solfege is more about about the identity of degrees in the key than the relative pitch difference of intervals. DO MI SOL are tonic tones and the others RE FA LA TI are tendency tones to the tonic and harmonically subdominant/dominant.
I suppose for relative pitch of any arbitrary interval you could just consider the bottom tone as DO. If the interval wasn't diatonic with DO supposed as the bottom, try a sensible diatonic interval. For example, a tritone, sing TI FA rather than DO SE.
BTW, there is solfege for minor and chromatic tones.

Relative Pitch and Solfege


Determine $r\in\mathbb{R}$ subject to $\frac{(2r+\sqrt{2r})^2}{(2r-\sqrt{2r})^2}=34$

Question:
Determine $r\in\mathbb{R}$ subject to $\frac{(2r+\sqrt{2r})^2}{(2r-\sqrt{2r})^2}=34$.

I had tried using rationalisation but its not getting me the correct answer and instead I got one irrational number in root which does not approximately equal to $34$.
Comment: Prove? Maybe "Find $r$ such that"
Comment: yeah u can say so
Comment: How is this question 'abstract'? 'algebra-precalculus' is indeed a more appropriate tag.
Answer: Let $\sqrt{2r}=x$
Your equation is
$$\frac{x+1}{x-1} = \pm \sqrt{34}$$
or $$x =\frac{\pm \sqrt{34}+1}{\pm \sqrt{34}-1}$$
Therefore, $$r =\frac{1}{2} \left(\frac{\pm \sqrt{34}+1}{\pm \sqrt{34}-1} \right)^2$$
Answer: $$\frac{(2r+\sqrt{2r})^2}{(2r-\sqrt{2r})^2} = 34\\
\Leftrightarrow (2r+\sqrt{2r})^2 = 34(2r-\sqrt{2r})^2\\
\Leftrightarrow 4r^2 + 2\sqrt{2r}+2r=34(4r^2 - 2\sqrt{2r}+2r)\\
\Leftrightarrow -132r^2+70\sqrt{2} \sqrt{r}-66r = 0
$$
Substitute $u=\sqrt{r}$ to get
$$
-132u^4-66u^2+70\sqrt{2} u = 0
$$
which is a biquadratic formula. Can you take it from here?
Comment: It is probably easier to solve $$
 \pm \sqrt {34}  = \frac{{2r + \sqrt {2r} }}{{2r - \sqrt {2r} }} = 1 + \frac{2}{{\sqrt {2r}  - 1}}.
$$


Anotations in Beethoven original score of the 9th symphony

Question: I once heard that in the original handwritten score of the first movement of Beethoven's 9th symphony there are references to the creation myth as annotations. However, these were not replicated in later copies and can only be found in the original manuscripts in the Beethoven Haus in Bonn.
This would fit the tone of the music (starting of very light and then suddenly exploding etc.). However, I can't find any reference to back this story up, so I might remember it incorrectly or it was just a myth. Can somebody conclusively confirm or deny this story? If this is true, it would be great if there were some reference anywhere, which parts of the first movement correspond to which parts of the creation myth.
Comment: @CamilleGoudeseune Yoa can find the scans here https://imslp.org/wiki/Symphony_No.9%2C_Op.125_(Beethoven%2C_Ludwig_van)
Comment: An interesting point. I haven't heard about it before.As you say this seems to be a common interpretation.  I can't tell you the original source but I've found an interpretation that is quoting your assumption. So your memory is quite correct. (s. my answer below.)
Comment: Does anyone have access to the (expensive) [facsimile edition](https://www.baerenreiter.com/en/shop/product/details/BVK2471/)?
Answer: There seem to be several sources that confirm your question. Here is an analysis or better a text with information round the 9th symphony
The opening of the first movement (Allegro ma non troppo, un poco maestoso) grows out of a void. Against the murmur of the deep strings falling fifths appear in the violins, which develop into a loud and imposing first theme; everything was compared to the creation of the world, and certainly no symphony had ever sounded like that before. Beethoven changed the expected order of the movements (another feature that the composers would later imitate) by placing the Scherzo (Molto vivace) next. From the beginning a favorite of the audience (especially the outstanding role of the timpani), it exudes both humor and strength. The lyrical slow movement (Adagio molto e cantabile) explores more personal, even more spiritual realms.
translation of Eine genauere Betrachtung in the following article:
https://www.npr.org/templates/story/story.php?storyId=5487727&t=1562331053351
Comment: Although written by an eminent [professor](https://music.columbia.edu/bios/christopher-howard-gibbs), this is still just a 21st century program note that claims, without substantiation, that the first movement has "been likened to the creation of the world."  Wikipedians would complain: [citation needed].
Answer: The public domain scan of the manuscript found by @PiedPiper, IMSLP19389-PMLP01607-Beethoven-Op125mss.pdf, has no extramusical annotations that I could find in the first 50 of its 425 pages.  Despite this scan's low resolution, low contrast, and strong noise, it's still clear enough to reveal any textual phrase long enough to refer to a creation myth, or a grocery list, or anything else.  I find only the usual Italian musical directions: Allo ma non troppo, a tempo, in 8va, loco, etc.  (And there's no black-rectangle redactions for the conspiracy theorists!)
Any program music explanation of the first three movements must then depend on something outside the score.  Unlike, say, the Sixth.
Comment: Did composers often write their grocery lists on scores,
Comment: Just as often as creation myths, apparently.
Comment: Yes, I have noticed the same number of each.


Convert date to number in excel; e.g. Jan-01 -> 1/1

Question: Having an issue with excel mistaking address information for date.
I have a column that contains apartment/floor information, generally in the format of a single digit, or maybe a digit and a number. A number of entries however are in the format of 4/5; 5/12; etc. which is causing issue as excel is reading them as a date and displaying as 4-May; or May-12.
I need to convert these back to the desired format, however within excel I can only seem to convert to 4/5/2017; or 45537; etc.
Any ideas on how to achieve the above without having to manually parse the entire document would be appreciated.
Comment: Write a macro to write a single quote **`'`** in the beginning of each cell where you have data in that particular column. Single quote will force those cells to be in text format.
Comment: @ManishChristian This will not work because excel will already have changed the content of the formula bar to a date. So effectively the apostrophe will be placed before 4/5/2017 instead of 4/5.
Comment: Make sense. Then in this case I would suggest format that whole column with Text type before you even put any data to that column. I've tested it and its working fine.
Answer: Please note that I have assumed that you already have a column filled with addresses. However if you are ENTERING the addresses, it is best to use apostrophe (') before the address is entered or format the column as text as ManishChristian and Krunch has suggested
Assuming your addresses are in column A:
<code>=IF(LEFT(CELL("format",A1),1)="D",TEXT(A1,"d/m"),A1)
</code>
This works for 1/1, 4/5, 5/12.
Please test check the formula with different types of addresses you may be having to ensure it does not result in undesired outputs.
Comment: Thanks for the input, used this in combination with the above to resolve!
Answer: Unless I am mistaken in what you are trying to achieve, put a "`" in front of your entry to display exactly what you type.
Comment: Thanks for this - quite basic but did the trick to convert back to a proper string!
Comment: Excellent to here!  Just remember to make this comment as an "answer" to close out your question.


SQL query to find single, sorted record

Question: Here is the problem I am trying to solve.  I have a table where I store a StartExclusionDate and EndExclusionDate and set an ApplyDate for my object (called Exclusion).  There can be many ExtId entries in the table.
I want to get the ApplyDate from the last continuous record where a date passed to the query is included between the StartExclusionDate and EndExclusionDate.
So here is the table I created in SQL 2005:
Id int PK
ExtId int FK
StartExclusionDate datetime null
EndExclusionDate datetime null
ApplyDate not null

And here is an example dataset:
  ID  |  ExtID  |  StartDate  |  EndDate  |  ApplyDate
--------------------------------------------------------
   1      101     11/15/2005    3/15/2010   11/15/2005
   2      101                               12/30/2005
   3      101       1/1/2000     1/1/2000     1/1/2006
   4      101       4/1/2008                  4/1/2008
   5      101                    8/1/2010     6/1/2008
   6      101      11/1/2006   12/31/2010    11/1/2009

I would be passing 2 parameters, @ExtId and @dtDate.  The record I want to retrieve based on the following conditions: @ExtId = 101, @dtDate = '6/15/2008' would be ID = 4
The logic is this:
Get all records for ExtId = 101 and where ApplyDate <= '6/15/2008', sort the ApplyDate DESC
If the first record's Start and End Date are between '6/15/2008', find the record where the Exclusion was originally set by checking the next records
I wanted to find a way to do this without a CURSOR, is it possible to do with a query or CTE?
EDIT:
Here it is done with a cursor
IF OBJECT_ID('TempDB..#t_edr','U') IS NOT NULL
  DROP TABLE #t_edr

CREATE TABLE #t_edr
(
    Id INT NOT NULL,
    ExtId INT NOT NULL,
    StartDate DATETIME NULL,
    EndDate DATETIME NULL,
    ApplyDate DATETIME NOT NULL
)

DECLARE @ExtID INT, @dtDate DATETIME, @dtReturn DATETIME
SELECT @ExtID = 101, @dtDate = '6/15/2008'

SET NOCOUNT ON
INSERT INTO #t_edr VALUES (1, 101, '11/15/2005', '3/15/2010', '11/15/2005')
INSERT INTO #t_edr VALUES (2, 101, NULL, NULL, '12/30/2005')
INSERT INTO #t_edr VALUES (3, 101, '1/1/2000', '1/1/2000', '1/1/2006')
INSERT INTO #t_edr VALUES (4, 101, '4/1/2008', NULL, '4/1/2008')
INSERT INTO #t_edr VALUES (5, 101, NULL, '8/1/2010', '6/1/2008')
INSERT INTO #t_edr VALUES (6, 101, '11/1/2006', '12/31/2010', '6/1/2009')
SET NOCOUNT OFF

IF EXISTS (
    SELECT EDR.ID FROM #t_edr EDR
    INNER JOIN (SELECT TOP 1 ID FROM #t_edr WHERE ExtId = @ExtID AND ApplyDate <= @dtDate ORDER BY ApplyDate DESC) LatestEDR
    ON EDR.ID = LatestEDR.ID
    WHERE ExtId = @ExtID
    AND ApplyDate <= @dtDate
    AND (StartDate IS NULL OR StartDate <= @dtDate)
    AND (EndDate IS NULL OR EndDate >= @dtDate)
    )
    BEGIN
        DECLARE @ID INT, @StartEDR DATETIME, @EndEDR DATETIME, @ApplyDate DATETIME,
            @CurrentApplyDate DATETIME, @Continue BIT

        DECLARE c CURSOR LOCAL FAST_FORWARD FOR
        SELECT Id, StartDate, EndDate, ApplyDate FROM #t_edr
        WHERE ExtId = @ExtID AND ApplyDate <= @dtDate ORDER BY ApplyDate DESC

        OPEN c

        FETCH NEXT FROM c INTO @id, @startedr, @endedr, @ApplyDate
        IF @@FETCH_STATUS <> 0 SET @Continue = 0
        ELSE SET @Continue = 1

        SET @CurrentApplyDate = @ApplyDate
        WHILE @Continue = 1
        BEGIN
            IF @StartEDR >= @dtDate OR @EndEDR <= @dtDate
                SET @Continue = 0

            IF @Continue = 1
            BEGIN
                SET @CurrentApplyDate = @ApplyDate
                FETCH NEXT FROM c INTO @id, @startedr, @endedr, @ApplyDate
                IF @@FETCH_STATUS <> 0 SET @Continue = 0
            END
        END
        CLOSE c
        DEALLOCATE c

        SELECT @CurrentApplyDate
    END
ELSE
    PRINT 'NOT EXCLUDED'

DROP TABLE #t_edr

Answer: select top 1 * from table
where ApplyDate <= '4/15/2008'
and (startdate is null or startdate<= '4/15/2008')
and (enddate is null or enddate >= '4/15/2008')
and extid = '101'
order by  ApplyDate desc

Comment: That would return the first record (ID = 1), because it matches the StartDate and EndDate criteria
Comment: That query returns ID=4.  I incorrectly set the date that should be passed. It should be '6/15/2008' instead of '4/15/2008' =(

I have updated the example, sorry for the confusion - it's been a long day already
Comment: I accepted this because it was correct based on the original criteria.  Thanks tekBlues

SQL query to find single, sorted record


Recurrence Equation Solution / Difference equation - WolframAlpha

Question: I am given the recurrece equation
$y_k-7y_{k-1}=5^k$
and found the (hopefully correct) particular solution to be
$y_k^P=-\frac{5}{2}5^k$
WolframAlpha, however, gives the particular solution
$y_k^P=c_17^{k-1}+\frac{5}{2}(7^k-5^k)$
So my question is: How can I rewrite WA's equation to my equation? For the life of me I cannot do it...
Comment: What you have found is a certain instance of answer as $c_1$ can be anything.
Comment: there are lots of, not one, particular solutions.
Comment: $c_1=-\frac{35}2$ this will give your answer.
Comment: But can $c_1$ not be any arbitrary number? Why can we assume that it is a specific number?
Comment: The answer given by W|A _is_ the general solution.
Answer: $y_k^P=- \frac{5}{2}5^k$: $- \frac{5}{2}5^k - 7(- \frac{5}{2}5^{k-1})=5^k$ is a particular solution, but the General solution is the Superposition of the particulary and the homogenous solution $y_k^H$, i.e. $y_k = y_k^P+y_k^H$. The homogenous solution can be obtained from the equation $y_k^H-7y_{k-1}^H=0$. This equation can be solved to give $y_k^H=c 7^k = (c_1 + \frac{5}{2}) 7^k$; for arbitrary constant $c$.
Comment: Thank you, kryomaxim! Now I understand.


Defining n-fold Composition of f with itself.

Question: This is a question on the test review packet I have for discrete mathematics.

Given: $f = \{(a, b), (b, a), (c, b)\}$ a function from $X = \{a, b, c\}$ to $X.$
(a) Write $f \circ f$ and $f \circ f \circ f$ as sets of ordered pairs.
(b) Define $f^n = f \circ f \circ \ldots \circ f$ to be the $n$-fold composition of $f$ with itself. Write $f^9$ and $f^{623}$ as sets of ordered pairs.

For part (a), I believe:
$$ f(a) = b\\ f(b) = a\\ f(c) = b\\ f(f) = \{(a, a), (b, b), (c, a)\}
\\
f(f(f)) = \{(a, b), (b, a), (c, b)\}$$
I think there is a pattern here with even exponents being equal to
$$ f(f) = \{(a, a), (b, b), (c, a)\}$$
and odd being equal to
$$f(f(f)) = \{(a, b), (b, a), (c, b)\}.$$
So how do we define $f^n = f \circ f \circ \ldots \circ f$ to be the $n$-fold composition of $f$ with itself?
Also I believe, $f^9$ and $f^{623}$ would both be $\{(a, b), (b, a), (c, b)\}.$
Comment: You made a mistake. $f = \{(\color{red}{a}, \color{blue}{b}), (\color{red}{b}, \color{blue}{a}), (\color{red}{c}, \color{blue}{b})\}$ means that $f(\color{red}{a}) = \color{blue}{b}, f(\color{red}{b}) = \color{blue}{a}, f(\color{red}{c}) = \color{blue}{b}.$
Comment: But, your expressions for $f(f)$ and $f(f(f))$ are correct.
Comment: Yes, I mistyped it on accident, corrected thanks. How does part b look?
Answer: Hints:

From your solution, note that: $f^3 = f.$
Property of composition: $f^{n} = f \circ f^{n-1} = f^{n-1} \circ f$
$f^9 = f^3 \circ f^3 \circ f^3$
Think about modular arithmetic. $3 \equiv 1 \pmod{\color{red}{??}}$ and $9  \equiv 1 \pmod{\color{red}{??}}.$ Figure out $\color{red}{??}$ and think about $623 \equiv\ \color{blue}{??} \pmod{\color{red}{??}}$
The general form should be apparent: $f^n = f^{n\pmod{\color{red}{??}}}$
Comment: 3≡1 (mod 2) 9≡1 (mod 2) 623≡1 (mod 2)? I don't really understand modular arithmetic very well to be honest.
Comment: @wazy That's corrent. Alternatively, in your original post your said there are two patterns: odd and even. Do you know programming? In programming, we often use $\pmod{2}$ to test for odd/even.
Comment: So part b would be f^n=f^n(mod 2). I wrote f^623 and f^9 as sets of ordered pairs already and I know some MIPS programming with the HI storing the remainder or I guess the mod.
Comment: No. Because an even number `mod 2` = 0. You want to say even $n \to 2$, odd $n \to 1.$
Comment: If you're not comfortable with modular arithmetic. You can just write it as two cases.
Comment: Yea that is easier for me. Thanks for the help. Do you mind editing your answer? (I'm going to note this and continue on with the packet before coming back and correcting it.)


IBM DataPower - How to handle HTML Response from openurl?

Question: I tried looking for the solution in the forum but I was unable to find something similar to what I'm trying to achieve. I have a gateway script in an MPG which kinda looks like this:
session.INPUT.readAsJSON(function (error, json) {
    if (error){
            throw error;
    } else {
    var SAMLResponse = json['SAMLResponse'];
    var RelayState = json['RelayState'];
    var urlopen = require('urlopen');
    var options = {
                            target: 'https://************.com/e32d32der2tj90g8h4',
                            method: 'POST',
                            headers: { 'HEADER_NAME' : 'VALUE'},
                            contentType: 'application/json',
                            timeout: 60,
                            sslClientProfile: 'ClientProfile',
                            data: {"SAMLResponse": SAMLResponse, "RelayState": RelayState}
    };
    urlopen.open(options, function(error, response) {
      if (error) {
            session.output.write("urlopen error: "+JSON.stringify(error));
      } else {
            var responseStatusCode = response.statusCode;
            var responseReasonPhrase = response.reasonPhrase;

            response.readAsBuffer(function(error, responseData){
              if (error){
                    throw error;
              } else {
                    session.output.write(responseData);
                    console.log(responseData);
              }
            });
      }
    });
    }
});

I'm doing a POST request and the response I get from the urlopen function is an HTML page, how to I display the contents of that page in my browser? I need that to initiate a process flow. am I going in the wrong direction here? what's the best way to POST to a URI and display it's response in DataPower?
with regards to my experience with DataPower, I just started learning, So I might not be familiar with many of the concepts.
Thanks in Advance!
Answer: session.INPUT.readAsJSON() would indicate that you are receiving JSON data as the input (from the POST).
Since you are building this in a Multi-Protocol Gateway (MPGW) you need to set the Response type to non-xml if the response is HTML and if there is no backend call being made (other than the url-open()) you also must set the skip-backside=1 variable.
Is the scenario as:
JSON HTTP Request -> [MPGW] -> url-open() -> Backend server --|
      HTTP Response <-----------------------------------------|
Or:
JSON HTTP Request -> [MPGW] -> url-open() --| (skip-backside)
      HTTP Response <------------------------|
If there is no backend call I would recommend building this in a XML Firewall (XMLFW) service instead and set it to "loopback" and non-xml.
If there is a backend and that is where you are sending your HTML from the url-open() then only MPGW Response type needs to be set to non-xml.
If it is the second option the you can just set the payload and headers in GWS and just call the target (https://************.com/e32d32der2tj90g8h4) as teh MPGW backside connection, no need for the url-open().


Can a player stretch into opponent's court to play a shot?

Question: If you touch the net while playing a shot, you lose a point. (I remember seeing Federer lose a point a few years ago, as he fell on the net after hitting a smash shot.) However, a player could stand close to the net without touching it and stretch his playing arm into the opponent's court to play a shot. This seems to offer an unfair advantage, because the net is taken out of the picture, and the player only needs to aim the ball correctly into the opponent's court. Is this allowed?
Answer: A player is only allowed to stretch into the opponent's court in 2 situations:

The player is near the net and they hit the ball after it has passed over the net.  The follow through on their swing is allowed to extend into the opponent's court (provided that they do not touch the net or the ground).
The ball bounces on the player's side of the court, and due to spin or wind, it goes back over the net.  In this situation, the player is allowed to reach over the net and hit the ball (provided that they do not touch the net or the ground).

Here are a couple sources:
USTA:

A player may break the plane of the net on a follow through from a shot as long as the ball was on that player's side of the court when the ball was struck. (The player can only reach over to play a ball in the situation stated in the paragraph below).
If the spin or wind brings the ball back over the net to the side of the player(s) who hit the shot, the opponent(s) may then reach over the net and play the ball. They may not touch the net or the opponent's court. This is the only situation when a player may reach over the net to play a ball. If the opponent does not play the ball and it bounces on the side of the player who hit the spin shot, that player who hit that shot wins the point.
The player in either situation may not touch the net, or the opponent's court with anything he wears or carries or with any part of the body.

ITF:

The point is lost if:
[...]
g. The player or the racket, whether in the player's hand or not, or anything
  which the player is wearing or carrying touches the net, net posts/singles
  sticks, cord or metal cable, strap or band, or the opponent's court at any time
  while the ball is in play; or
h. The player hits the ball before it has passed the net;


How to I create a backup of my content ONLY?

Question: I'm debating between using Feeds module and Backup and Migrate and I'm not sure which would be the best option here.
Here's the scenario - I've two versions of the same site - both drupal 7, both have the same content types and taxonomy structure. One is live, one is on a development server. Due to some unclear communication a bunch of content edits were added to the live site that need to be merged in to the development site where we've made major improvements with Views and several stylistic changes, so we can't just dump the database and then move it without wiping out all the new content on the live site.
So does anyone have a good idea on how to best move JUST the content tables from the database? I know it will be different from install to install, but if you could help me get an idea of what to look for I can use the backup and migrate module and just exclude every table except those which I need.
Thanks in advance.
Comment: there really is no easy way. Figure out the tables you need: `node`, `node_revision`, `field_*` ... for your `content` and move them. It's best not to get in this situation because it's a PITA.
Answer: Node export is the best option to take backup for contents. One click export, import for the particular content types.

This module allows users to export nodes and then import it into
  another Drupal installation, or on the same site.
Using this module you can save yourself a lot of time setting up new
  websites that have similar nodes to websites you've already made,
  migrating nodes to new Drupal versions, or between
  development/staging/production sites.
You will need the same content types for the imports to work (unless
  using Feeds to import), and ideally relevant compatibility with
  fields, and modules.
Comment: This is ultimately what I used. I remember something similar for drupal 6 to 7 upgrades and this did the trick.
Comment: I was wondering if node export works with field_groups but it seems to.
Answer: You can also use feature module to import functionality
from one site to another site.

The features module enables the capture and management of features in
  Drupal. A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case. Features provides a UI and API
  for taking different site building components from modules with
  exportables and bundling them together in a single feature module. A
  feature module is like any other Drupal module except that it declares
  its components (e.g. views, contexts, CCK fields, etc.) in its .info
  file so that it can be checked, updated, or reverted programmatically.

Yon can export your views from deveolpment version of your site using feature module. It will export views into module and you can install this module like the other module into live site and views will be activate into your live site.
There are some feature related module which extend the functionality of the feature module.
Answer: Backup and Migrate won't help you here.
Options:

You could certainly use Feeds.
You could use Deploy (probably with UUID).
You could move the content manually.

Honestly, if the amount of content is under fifty-or-so nodes, I would do it manually, and call it a lesson learned. You can be done in an hour or two, and that'll be quicker than learning how to set this up with either of the other two options. Of course, if you want to learn some new tools (and probably use them in the future), options 1 and 2 would be the way to go.
Answer: For your specific scenario, Jayendra's answer is best; you should accept that answer, and do as he said (move your updated views to the live server rather than try to move just the content from live to dev). This is standard for Drupal.
If you want to move just the content, try Drupal to Drupal Migration, or one of the other answers -- but using features will be easiest.
Answer: You can use https://drupal.org/project/views_data_export to export your terms and nodes to XML into 2 separate feeds.
Then Feeds and https://drupal.org/project/feeds_xpathparser to import the content.
You can also export into CSV and import using Feeds' CSV parser. That will work for simple cases, but multi-valued fields can be problematic.
Deploy is great, but it's a lot more work to setup for a one-off job.
Answer: It really depends on how complex your data is and what you want saved. If its just a couple of fields then you could create a view that has all the data in it. Copy it into excel then import it using feeds into your new site. It sounds messy but I imported more then 4000 nodes into a site this way and it only took an hour to setup, export then import. There are more complex ways of exporting the data using different modules.


How to run powerful analyses with non-normal data

Question: I coded the amount of speech that participants used during several tasks and I want to use this information to predict performance on other tasks. I also want to test whether speech on one task is related to speech on another. Specifically, I coded whether or not speech was used on a given trial of a task, and calculated a percentage (i.e., percent of trials on which participant used X speech).
All of my data are non-normal, primarily because there were a lot of participants who didn't use any speech on any trials, and there were also many who used speech on all trials.
What is the most straightforward way to deal with these data? I could use non-parametric correlations for some analyses, but in some cases I'll want to use something equivalent to linear regression (with the speech variable as a predictor, among other predictors). Attached are some histograms of the data.
Answer: First, OLS regression makes no assumptions about the distribution of the data it makes assumptions about the distribution of the error which is estimated by the residuals.
Second, there are a lot of regression type models that do not make these assumptions: Quantile regression, various robust regression methods, regression trees and their offspring and more.


How to do I block IP & computer name from appearing in the SMTP email headers when sending from the Outlook Desktop application?

Question: I am using the Windows Outlook 2016 application, connected to 2 different hosted IMAP/SMTP email accounts (different vendors), and when I send out emails and compare the email headers, one is more "private", and the other spills out my IP address and computer name.  Is this an Outlook or email vendor setting that can block the "loose" email account from sending out my IP and computer name?
Note: I was able to use a VPN to change my "X-Source-IP", but it's a bit annoying.
Thanks.
Answer: No. Email messages typically keep a record in their headers of where they have come from. While it's optional for mail servers and clients to add custom headers like X-Source-IP, you have no control over it in Outlook.


What's the difference between these two selectors in jQuery

Question: I have these two selectors and I want to know the difference between both of them:
$("table#tabla_semiter > tbody > tr").eq(indiceSemiter).after(html1);

AND
$("table#tabla_semiter tbody tr").eq(indiceSemiter).after(html1);

Thanks
Comment: immediate child vs descendant. Would make a difference, if you nest tables, for example.
Answer:
The child combinator (E > F) can be thought of as a more specific form of the descendant combinator (E F) in that it selects only first-level descendants.

Taken from https://api.jquery.com/child-selector/
Answer: The documentation would yield the answer.

element element   div p   Selects all
 elements inside  elements
element>element div > p   Selects all
 elements where the parent is a  element
Answer: div p Selects all
 elements inside div
div > p Selects all
 elements where the parent is a div
the first Selector
select Exactly tr then child of table#tabla_semiter > tbody >
and Second Selector
 get All tr in tbody
for more Detail see this Sample

                First Row

                Second Row

                               First Child

   $("#tbl tbody tr td").css("background-color","blue");
   $("#tbl>tbody>tr>td").css("background-color","red");

Sample


The concept of efficiency

Question: I have some problems in understanding the concept of efficiency as related to an estimator. My sources (Mukhopadhyay, 2000 and Casella, Berger, 2002) do not treat this argument as I expected since they analyse only the concept of asymptotic efficiency.
I do not understand if there exist a concept of efficiency valid also (or only) in finite samples. Or if efficiency is not a per se concept and it is used only to compare estimators, talking about more efficient estimator and so on.
What I know is that an estimator is efficient if it reaches the Cramér-Rao Lower Bound. But this is a characterization, it is not a definition. And, moreover, Cramér-Rao inequality refers only to a subset of estimators, those which are unbiased for a certain $\tau(\theta)$. The concept of efficiency is meaningful only in the case of unbiased estimators?
If someone could provide me some sources or a brief excursus about the concept of efficiency and efficient estimators, I will be grateful.
Comment: Defining efficiency in terms of the Cramer-Rao lower bound is perfectly valid, and it makes sense for finite samples.  You could extend this to unbiased estimators by talking instead about minimum mean squared error (or use some other loss function), but perhaps the math doesn't work as well.  I'm guessing here but it may deal with the use of the Cauchy-Schwarz inequality.
Answer: Efficiency is a "per se" concept in the sense that it is a measure of how variable (and biased) the estimator is from the "true" parameter.  There is an actual numeric value for efficiency associated with a given estimator at a given sample-size for a given loss function.  This actual number is related to the estimator AND the sample-size AND the loss function.
Asymptotic efficiency looks at how efficient the estimator is as the sample size increases.  More important is how rapidly the estimator becomes efficient but this can be more difficult to determine.
Relative efficiency looks at how efficient the estimator is relative to an alternative estimator (typically at a GIVEN sample-size).
Efficiency requires the specification of some loss function.  Originally, this was variance when only unbiased estimators were considered.  These days, this is most often MSE (mean-squared-error which accounts for bias and variability).  Other loss-functions can be used.  The classical Cramer-Rao bound was for unbiased estimators only but was extended to many of these other loss functions (most especially for MSE loss).
An important adjunct concept is admissibility and domination of estimators.
The Wikipedia entry has many links.
Comment: Thank you for this clarification. Thus, efficiency is an estimator feature as sufficiency or completeness? I mean, there are some properties related to efficient estimators, such as uniqueness, exponential families properties, ... ?
Answer: I wonder at the global relevance of a concept of efficiency outside [and even inside] the restricted case of unbiased estimators. The general (frequentist) version is that the variance of an estimator $δ$ of [any transform of] $θ$ with bias b(θ) is
$$
I(θ)⁻¹ (1+b'(θ))²
$$
while a Bayesian version is the van Trees inequality on the integrated squared error loss
$$
(\mathbb{E}(I(θ))+I(π))⁻¹
$$
where $I(θ)$ and $I(π)$ are the Fisher information and the prior entropy, respectively. But this opens a whole can of worms, in my opinion since

establishing that a given estimator is efficient requires computing
both the bias and the variance of that estimator, not an easy task
when considering a Bayes estimator or even the James-Stein
estimator. I actually do not know if any of the estimators
dominating the standard Normal mean estimator has been shown to be
efficient (although there exist results for closed form expressions
of the James-Stein estimator quadratic risk, including one of mine in
the Canadian Journal of Statistics). Or
is there a result indicating that a (any?) proper Bayes estimator associated with the
quadratic loss is by default efficient in either the first or second
sense?
while the initial Fréchet-Darmois-Cramèr-Rao bound is restricted to unbiased estimators (i.e., $b(θ)≡0$) and unable to produce efficient estimators in all settings but for the natural parameter in the setting of exponential families, moving to the general case means there exists one efficiency notion for every bias function $b(θ)$, which makes the notion quite weak, while not necessarily producing efficient estimators anyway, the major impediment to taking this notion seriously;
moving from the variance to the squared error loss is not more "natural" than using any [other] convex combination of variance and squared bias, creating a whole new class of optimalities;
I never got into the van Trees inequality so cannot say much, except that the comparison between various priors is delicate since the integrated risks are against different parameter measures.
Answer: Yes an efficient estimator is one that attains the CRB, thus only unbiased estimators are considered. It's not a characterization it's a definition.
Comment: If you read the answer above, it says that CRLB can be used also with other loss functions than the variance, i.e. MSE and others. Thus, I think the definition of efficiency can be attributed also to biased estimators
Comment: The definition of estimator's efficiency require the inspected estimator to be at least locally unbiased in a region of interest. If an MSE of an unbiased estimator equals the Cramer Rao bound then it is efficient. Otherwise, it's not.
Comment: Thus, to be efficient, being _unbiased_ is a necessary condition?
Comment: Ok thanks. So the idea is that an **efficient** estimator must be unbiased but I can compute **efficiency** also for biased estimators?
Comment: No. You can't. You can compute it's MSE and compare it with the bound, which lacks a real mathematical meaning. Efficiency is a property of an estimator. Either it is efficient or not.
Comment: Ok I am a bit confused about terminology: then may we say that a biased estimator is **more/less efficient** than another one? Analyzing MSE I mean
Comment: There is no less or more efficient. There's efficient or not efficient. It's binary. When you compare estimator's you can compare MSEs for example which gives you an idea which estimator performs better in a mean square error sense.
Comment: Alessandro, in my opinion, you were correct in your comment above.
Comment: Alessandro, in my opinion, you were correct two comments back.  By definition, an efficient estimator is one which meets the Cramer-Rao bound which requires unbiased.  Ergo, an efficient estimator must be unbiased.  Efficiency, as a concept, does not require unbiased.  Otherwise, what would relative efficiency mean.  There are biased estimates that dominate unbiased estimates based on MSE (see James-Stein estimators, for example).
Comment: Efficiency cannot be judged as "a concept". It is a definition nothing more. It is true that there're biased estimators that outperform unbiased ones in terms of MSE. Doesn't alter the case (they're still not efficient)

The concept of efficiency


c# object reference not set to an instance of an object (no mention of null reference in stack trace)

Question: I am getting a "Object reference not set to an instance of an object" error when running my windows service in Release mode (please note, as you can see from my stack trace, it doesn't mention anything to do with a NullReference which is confusing me more). Each time i run this in debug mode, the code works beautifully, but as soon as i build it to release and start it on the server, it fails with the Object reference error. See below for my stack trace and then below that for my code;
=================================================================================

Error Message: [EventQueueBulkProcessingHandler] Failed to process events
Stack Trace:

Error Message (INNER EXCEPTION LEVEL 1): Object reference not set to an instance of an object.
Stack Trace (INNER EXCEPTION LEVEL 1):
   at Voicebox.EventTriggers.Processing.Preparation.EventContactsFilter.Filter(ContactsModel contacts, ContactsFilterModel contactsFilterModel, Int32 clientId) in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\Preparation\EventContactsFilter.cs:line 24
   at Voicebox.EventTriggers.Processing.Preparation.TriggerActionDetailsBuilder.CreateTriggerActionDetails(Trigger trigger, ITriggerEvent triggerEvent) in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\Preparation\TriggerActionDetailsBuilder.cs:line 48
   at Voicebox.EventTriggers.Processing.Handlers.UserEventsHandler.<>c__DisplayClass6_0.<MapEventsToTriggers>b__0(Trigger t, ITriggerEvent e) in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\Handlers\UserEventsHandler.cs:line 62
   at Voicebox.EventTriggers.Helpers.PermutationsHelper.<>c__DisplayClass0_1`3.<Permutations>b__1(TB b) in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Helpers\PermutationsHelper.cs:line 11
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Linq.Enumerable.<SelectManyIterator>d__17`2.MoveNext()
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at System.Linq.Enumerable.<SelectManyIterator>d__17`2.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Voicebox.EventTriggers.Processing.Handlers.UserEventsHandler.<HandleAsync>d__5.MoveNext() in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\Handlers\UserEventsHandler.cs:line 37
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Voicebox.EventTriggers.Processing.EventQueueBulkProcessingHandler.<ProcessEventsGrouppedByClient>d__8.MoveNext() in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\EventQueueBulkProcessingHandler.cs:line 107
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Voicebox.EventTriggers.Processing.EventQueueBulkProcessingHandler.<ProcessInternal>d__6.MoveNext() in D:\Websites\VoiceboxTest\Voicebox\VoiceBox.EventTriggers\Processing\EventQueueBulkProcessingHandler.cs:line 52

=================================================================================

So going off of the above stack trace, it says the issue is in the file EventContactsFilter at line 24. This is where its making no sense to me as this is the initialisation of a List. See below code;
            // this is the line 24 which the stack trace points too
            List<string> filterExpressions = new List<string>();

            foreach (var model in contactsFilterModel.Criteria)
            {
                string fieldName = GetFieldName(contacts.ListId, model.FieldID, clientId);

                FieldType fieldType = GetFieldType(model);
                FilterExpression FilterExpression = ExpressionBuilder.GetFilterExpression(fieldName, model, fieldType);
                var expression = FilterExpression.sqlExpression;
                filterExpressions.Add(expression);
            }

So as you can see, the error is being thrown on the creation of a new list, and after many many hours or searching the web, ive not been able to find out what may be causing this. If anyone is able to help, i would be forever in your debt!!
Comment: Have you checked that you are deploying the right version of the .net runtime
Comment: How have you ensured that the source code that you're currently inspecting corresponds to the code that was used to compile the executable that's currently throwing this exception?
Comment: Check your release bin have latest dll available same as debug bin else copy the dll from debug folder
Comment: @bilpor - Yeah just checked and all lib and services are on the same version (4.6).
Comment: @Damien_The_Unbeliever - If i comment out this code block, everything works around it, so def seems to be caused here :/
Comment: @Abinash - I been making sure to removed the bin folders between builds to make sure to exclude this, i will give the debug build version ago though when i next build
Comment: Try attaching a debugger? Use this: `while (!Debugger.IsAttached)
            {
                Thread.Sleep(500);
            }
            Debugger.Break();` Note: this can't be in the constructors of your service, rather in a thread somewhere. Else the service will not install.
Comment: Ok what is `contactsFilterModel` Where does that get instantiated?
Answer: I'm not really convinced that the problem is the List<string> declaration. Please use a try-catch around that declaration, and see what the actual error message is.
My intuition says the problem it's not there. Maybe something above,or under that line. My guess that foreach. Either way, try-catch that code :)
Comment: Just added a try catch and throwing the error exception, the stack trace is almost the same although now to does mention NullReferenceException. I have added a null check onto the foreach which doesn't seem to have made a difference, going to try commenting out line by line now i know it is a null reference and see what that bring.
Comment: @LouisBarker : foreach (var model in contactsFilterModel.Criteria) . Did you include the Criteria for contactsFilterModel ?
Comment: Turns out you was correct, the contact model was coming in fine, but the criteria where coming in as null due to a db context issue (next issue to figure out!!). Thanks for your help identifying the route cause :)
Comment: Glad i could help!


Trumpet Mouthpiece for Playing High Notes

Question: Any suggestions for an effective trumpet mouthpiece to be able to play above G (above the staff)? Currently using Schilke 14A4A but doesn't quite make it.
Comment: Hi! I'm afraid gear recommendations aren't among the [topics covered here](https://music.stackexchange.com/help/on-topic).
Answer: Despite what manufacturers would have you believe, there's no magic bullet/new golf clubs/shiny equipment answer to this. You can't buy a quick answer to this problem.
The actual answer is to choose a mouthpiece that's comfortable for you and then commit hours of practise over months and years doing flexibility and range expanding exercises.
And get a trumpet-playing expert to review your progress periodically to make sure you're not developing bad habits.


Going through a list to count how many times a value is there... Not working in Java

Question: I created a list from a text document. I then created a loop to go through it and count every time "strawberry" is in it. But I'm not sure why, it is not working.
I know my list gets created correctly because my print statement at the end returns the correct value. But then it doesn't add up the flavors or the number of times strawberry is present.
 import java.util.List;
 import java.util.ArrayList;

 public class IceCream {
    public static void main(String[] args) {

        int count, strawberry, average, i;

        List<String> flavors = new ArrayList<String>();
        TextIO.readFile("src/icecream.dat");

        while (TextIO.eof() == false) {
            flavors.add(TextIO.getln());
        }

        count = 0;
        strawberry = 0;

        for (i = 0; i < flavors.size(); i++); {
            count++;
            if ( flavors.equals("Strawberry")) {
                strawberry++;
            }
        }

        TextIO.putln(flavors.size());
        average = strawberry / count * 100;

        TextIO.putln("" + count + " ice cream cones were sold. "
                  + strawberry + " were strawberry flavored, "
                  + "which is a total of " + average + "% of the ice cream cones sold.");
    }
}

Comment: Should be `if ( flavors.get(i).equals("Strawberry")) {`
Comment: What Ernest said. Also be aware that .equals() is case sensitive.
Comment: @ErnestKiwele Do post as an answer, 10/10 would upvote.
Comment: If I change it, I get this error message:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 374, Size: 374
 at java.util.ArrayList.rangeCheck(ArrayList.java:657)
 at java.util.ArrayList.get(ArrayList.java:433)
 at IceCream.main(IceCream.java:19)
Answer: You are wanting to use ArrayList::get
 and compare the Object using equals
if ( flavors.get(i).equals("Strawberry")) {
    strawberry++;
}

edit
Also remove the last ; on for (i = 0; i < flavors.size(); i++);
Comment: You are going to have a `integer` division problem see http://stackoverflow.com/questions/4685450/why-is-the-result-of-1-3-0
Comment: When I do, I get this answer:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 374, Size: 374
 at java.util.ArrayList.rangeCheck(ArrayList.java:657)
 at java.util.ArrayList.get(ArrayList.java:433)
 at IceCream.main(IceCream.java:19)
Comment: `average` will be 0, because you're using integers. smaller integer devided by bigger integer gives 0. 0 * 100 gives 0.
Comment: Yes, just realized that right now. Thank you so much!
Answer: Apart from Scary's answer, you have a semicolon after your for-loop. A semicolon is an empty statement, so you're running an empty statement 374 times, while increasing i to be the size of your list. Afterwards you run the block that was supposed to be the loop's body exactly once, but now i is too big for your list.

Remove the semicolon.
Do not declare your variables god knows where, declare them where you need them. That way you would've gotten a compile error, as i would only be available inside and not outside the loop.
Answer: You are comparing the ArrayList object with the String "Strawberry". What you really want is to compare each element with the String. So the statement should be
if(flavors.get(i).equals("Strawberry")) {
    strawberry++;
}


Using fundamental theorem of calculus in Sturm-Liouville orthogonality proof

Question:
Theorem:
The eigenfunctions of the Sturm Liouville BVP
$$\int_0^a \sin \left( \frac{n \pi x}{a} \right) \sin \left( \frac{m \pi x}{a} \right) \ dx = 0$$ when $m \not= n$.
satisfy the integral relationship
$$\int^b_a r(x) \phi_n(x) \phi_m(x) \ dx = 0$$
If $m \not= n$
where $\phi_1, \phi_2, \phi_3, \dots$ are eigenfunctions, and $\phi_n$ corresponds to the eigenvalues $\lambda_n$.
Hence the set of functions for the Sturm-Liouville problem orthogonal on the interval of interest, with regards to the weight function $r(x)$.
Proof:
Since $\phi_n$ and $\phi_m$ are eigenfunctions, they must satisfy the ODE
$$\frac{d}{dx} \left( p(x) \frac{d \phi_n}{dx} \right) + q(x) \phi_n = - \lambda r(x) \phi_n \ \ \ (1)$$
$$\frac{d}{dx} \left( p(x) \frac{d \phi_m}{dx} \right) + q(x) \phi_m = - \lambda r(x) \phi_m \ \ \ (2)$$
Multiply (1) by $\phi_m$ and (2) by $\phi_n$ and subtract:
$$\phi_m \frac{d}{dx} \left( p(x) \frac{d \phi_n}{dx} \right) - \phi_n \frac{d}{dx} (p(x) \frac{d \phi_m}{dx} = (\lambda_m - \lambda_n)r(x) \phi_n \phi_m$$
The left-hand side can be expressed as
$$\frac{d}{dx} \left( p(x) \left( \phi_m \frac{d \phi_n}{dx} - \phi_n \frac{d \phi_m}{dx} \right) \right)$$
Therefore, the equation becomes
$$\frac{d}{dx} \left( p(x) \left( \phi_m \frac{d \phi_n}{dx} - \phi_n \frac{d \phi_m}{dx} \right) \right) = (\lambda_m - \lambda_n)r(x) \phi_n \phi_m$$
Integrate both sides with respect to $x$ from $a$ to $b$:
$$\left[ p(x) \left( \phi_m \frac{d \phi_n}{dx} - \phi_n \frac{d \phi_m}{dx} \right) \right]^b_a = (\lambda_m - \lambda_n) \int^b_a r(x) \phi_n \phi_m \ dx$$

What I'm trying to figure out is how integrating both sides with respect to $x$ from $a$ to $b$ gets us
$\left[ p(x) \left( \phi_m \frac{d \phi_n}{dx} - \phi_n \frac{d \phi_m}{dx} \right) \right]^b_a = (\lambda_m - \lambda_n) \int^b_a r(x) \phi_n \phi_m \ dx$
As I understand it, this is an application of the fundamental theorem of calculus part 2 (called part 2 in my textbook):

If $f$ is continuous over $[a, b]$ and $F$ is any antiderivative of $f$ on $[a, b]$, then
$$\int_a^b f(x) \ dx = F(b) - F(a)$$

Can someone please demonstrate how this was done?
Answer: Note that:
$$\int_{a}^{b}\frac{df}{dx}dx=f(b)-f(a)$$
It is the fundamental theorem of calculus. The $\lambda$'s are constant and therefore come out of the integral.
Comment: I have a set of notes on integration: http://hyperkahler.co.uk/wp-content/uploads/2011/10/integration.pdf
Answer: Your functions $f_n(x)=\sin(n\pi x/a)$ are solutions of
$$
               -\frac{d^2}{dx^2}f=\lambda f,\;\;\; 0 \le x \le a, \\
                     f(0)=f(a)=0.
$$
So you have a weight function $r(x)\equiv 1$, coefficient $p\equiv 1$, and potential $q\equiv 0$. The eigenvalues are $\lambda_n=n^2\pi^2/a^2$. Therefore, the general theory gives
$$
      \int_{0}^{a}f_n(x)f_m(x)dx = 0,\;\; n \ne m,\;\; n,m=1,2,3,\cdots.
$$


Has such an anti-musical tune ever been composed?

Question: The following part from chapter 84 of the Harry Potter and the Methods of Rationality fanfic describes a tune that appears to be designed to be unnerving.

The humming started as a simple children's lullaby, the one that in Muggle Britain begins, Lullaby, and goodnight...
This tune was hummed, without variation, over and over, for seven minutes, to establish the underlying pattern.
Then began the elaborations upon the theme. Phrases hummed too slow, with long pauses in between, so that the listener's mind helplessly waits and waits for the next note, the next phrase. And then, when that next phrase comes, it is so out of key, so unbelievably awfully out of key, not just out of key for the previous phrases but sung at a pitch which does not correspond to any key, that you would have to believe this person had spent hours deliberately practicing their humming just to acquire such perfect anti-pitch. <...>
And this horrible, horrible humming is impossible to ignore. It is similar to a known lullaby, but it departs from that pattern unpredictably. It sets up expectations and then violates them, never in any constant pattern that would permit the humming to fade into the background. The listener's brain cannot prevent itself from expecting the anti-musical phrases to complete, nor prevent itself from noticing the surprises.
The only possible explanation for how this mode of humming came to exist is that it was deliberately designed by some unspeakably cruel genius who woke up one day, feeling bored with ordinary torture, who decided to handicap himself and find out whether he could break someone's sanity just by humming at them.

Since most of the non-magical ideas in HP&MOR are supposed to be scientifically plausible, I think this kind of tune might actually be composable. So I wonder, has anyone ever tried to compose such a thing? Did they succeed, or has it proved to be very hard or impossible?
Comment: The keyboardist in one of my bands liked to play christmas songs in Lydian mode. This sounds astonishingly awful, because you get a nice bright context and expectations but then keep getting smashed about the head subdominants as diminished chords, and the dominant resolutions all go in completely the wrong direction.
Comment: There are quite a few 'pop' songs which could easily be cited..!
Comment: Les Dawson springs to mind ;) I once did a lullaby type piece where each iteration got slightly more odd, strange voice-leading, note clashes, major meets minor, in a kind of 'something's going to jump out & bite soon' kind of way, though everything is still technically just about 'in tune'. [I'll Soundcloud it if anyone's interested. It's only a demo, so 'keyboard strings' etc] I can't claim it's the 'best thing I ever did' so it never got published anywhere.
Comment: I was reading the quote and thinking is really not well written, and only then noticed it was fanfic, not Rowling herself. So many things here. First, this seems like an identification question and we don't do that here. Second, there can't really be a pitch that does not exist in any key at all, and what a "key" is can be fluid. Third, minimalism and atonality have definitely led to music that would be similar to what is sort of described here. Also setting up expectations and violating them is often exciting for listeners, not annoying.
Comment: @Tetsujin I'm interested in hearing it.
Comment: OK, I've put it up on Soundcloud, Called Lullabye-Bye - I might not leave it there long, as It's not the best thing I ever did, so grab it while it's… lukewarm ;) https://soundcloud.com/graham-lee-15/lullabye-bye
Comment: @tetsujin Maybe you should put the SC link in the book one insisted for you to write for some time now... Jokes apart, would be interested to hear that too!
Comment: @Tetsujin well, this doesn't sound too much strange to me (though I'm not musically educated, so maybe this is the reason). Maybe very slightly odd, but definitely doesn't remind me of the passage quoted in the OP.
Comment: I've been to performances and concerts of so-called "avant garde" music that this description could apply to for many listeners.  However, I sincerely doubt that most of the composers of the music I've heard intended this sort of reaction.
Answer: Music is generally composed to sound good, or at least energetic or interesting or some other positive quality. There isn't much market for music deliberately designed to drive people crazy, so examples will probably be hard to come by.
I would call the premise semi-plausible, in that the things the author mentions can be jarring or annoying. Timbre should be on that list too, as in fingernails on chalkboard, which a study found "elicits an emotion similar to but distinct from disgust".
But only semi-plausible:

Lots of perfectly ordinary music can get on people's nerves if it's repeated often enough. Just ask anyone who has worked in retail during the holiday season where the same Christmas Carols CD plays on repeat from mid-November until Christmas.
"too slow, with long pauses in between" applies to basically any beginner practicing an instrument. It can be pretty annoying when they repeatedly play through the part they know at full speed only to falter right before the resolution.
"at a pitch which does not correspond to any key" happens to any beginner on an instrument with continuous pitch, like violin. The assumption is of course that they start playing in something resembling 12-tone equal temperament with A=440 Hz (like a piano), but accidentally plays a note that isn't on the piano, and a violin can indeed produce some very ugly sounds in the hands of a beginner (although I think the ugliness comes in part from timbre, not just pitch). In the hands of an expert doing his damnedest to put people's teeth on edge it could probably be more consistenly bad, but nothing I know of indicates that "peak ugliness" could be significantly worse.
Pitches outside the ones found on a piano aren't inherently bad. E.g. quartertones in Persian, Arabic, and Turkish music are not on a piano, and they differ from each other, so-called microtonal variation. Listening with a Western ear it may sound odd or out of tune, but it doesn't take long to adapt to a different scale and tuning so it sounds natural.
The world's ugliest music was claimed by a TED talk. The idea was that beauty lies in repetition, and this music was computer-designed to avoid any repeated rhythms or intervals as far as possible. To my ears it doesn't sound like music, but neither is it objectionable, more like avant-garde or random plonking on the piano.

I doubt that it's possible to make music that literally drives people insane, at least any more than you can achieve by locking people in a basement and putting "Jingle bells" on repeat for a month.
After all, plenty of people learn to play an instrument and will produce many elements of what the author describes (I expect that's how he/she came up with the idea), and although annoyed family members aren't uncommon, there aren't many reports of insanity. You could crank it up multiple notches if you deliberately set out to annoy people, but I doubt it would be enough to "break someone's sanity".
If it could be done it would probably hinge on psychology as much as sound design, and affect different people differently.
Comment: I've read reports that governments and militaries occasionally play loud, obnoxious rock or metal to scare loiterers off - I can surely believe that locking people in a basement and putting "Jingle bells" on repeat for a month can drive them literally insane.
Comment: @Dekkadeci I expect that it could - if not in a month, then eventually.  But that's not due to some mystical property of Jingle bells. I expect that a lot of other repetitive stimuli that you can't escape can do the same, but that's beyond the scope of music. It was meant more as a baseline - if "normal" music can drive you crazy in a month, the question has to be whether there can be "evil" musical compositions that can do the same dramatically faster than than both Jingle bells and alternatives like a loop of the worst parts of a beginner violinist's practice session. I think not.
Answer: The passage means regular tempo and rhythm, and being in key, is musicality, and no one would really argue with that on a basic level. To keep things simple we can call that style tonal music.
So, is there music that deliberately uses irregular tempo, rhythm, and pitch-wise isn't in a key?
Yes.
Look at avant-garde styles serial music and aleatory music. The composers who worked in those styles deliberately eschewed regular, metrical rhythm, and especially avoided being in a key to find new modes of expression. In particular there is a strong link between harmony and rhythm in tonal music, and avant-garde composers wanted to break that link for more rhythmic freedom.
The Harry Potter passage is obviously supposed to be a joke, but the "anti" part of it could be thought of as "anti-tonal", and in fact serial music is called atonal, which of course means anti-tonal. A lot of people don't like atonal music. Their reactions are often in line with the sentiment of the Harry Potter passage. On the other hand, others say those critics are close-minded who don't want to appreciate new, unfamiliar types of music. One person's noise is another person's music.
Another example of anti-music is Mozart's Musical Joke. Apparently he wrote it as an example of bad composition to be funny. Some of the gaffes are composer's inside jokes, other are more obvious to a general listener.
Answer: This is a great question. Yes I believe this has been attempted. John Cage's Organ2/ASLSP changes notes As Slow As Possible (ASLSP) which is based on the same idea, albeit inverted, as that given in the Harry Potter. Charles Ives' Three Places in New England if I remember contains simultaneous performing of essentially separate pieces of music. This creates a terrible aural conflict which the Harry Potter describes well. Note, this is very different from dissonant music which although is dissonant is still structurally organized. In the Ives case the work is true cacophony.


Finding the Curl of a vector field. (Vector calculus)

Question: Find a vector field $F$ such that
$$\operatorname{curl} F = xi + 2yj + 3zk,$$
or, explain why such a vector field does not exist
What i tried
Since $\operatorname{curl} F$ is given, in order to find the original vector field, can i say that since $div (curl F)$ not equals to 0, the second order partial derivative does not exists and hence its potential function (vector field) does not exists.
Comment: If you compute the curl of what you obtained, do you get the original field?
Comment: Does div(curl F) = 0?
Comment: No it dosent give 0.
Answer: The divergence of the curl of a vector field must be zero. Here, we see that
\begin{equation}
\text{div} \, \text{curl} \, F = \nabla \cdot \left(\begin{array}{c} x \\ 2y \\ 3z \end{array}\right) = \frac{\partial}{\partial x}x + \frac{\partial}{\partial y}2y + \frac{\partial}{\partial z}3z = 1 + 2 + 3 = 6 \neq 0.
\end{equation}
Then what we're calling "$\text{curl} \, F$" isn't really the curl of any vector field and such a vector field does not exist, precisely because the condition $\text{div} \, \text{curl} \, F = 0$ condition is not met.
Comment: That gets at the right idea here. The mixed second partial derivatives of at least one component of $F$ do not agree with each other. For example, if we say $F = P\hat{i} + Q\hat{j} + R\hat{k}$, where $P$, $Q$, and $R$ are all functions of $x$, $y$, and $z$, then $\text{div} \, \text{curl} \, F \neq 0$ means that $R_{xy} \neq R_{yx}$ or that a similar condition is violated by $P$, $Q$, or $R$.
Comment: So can i say that since $div curlF$ not equals to 0, the second order partial derivative does not exists and hence its potential function (vector field) does not exists.


real numbers a vector space over rational numbers?

Question: Let $V$ be set of real numbers and $K$ the field of rational numbers.
Is $V$ a vector space over $K$, with ordinary addition of real numbers
and multiplication by rational numbers?
Comment: Similar question: http://math.stackexchange.com/questions/257504/the-real-numbers-form-a-vector-space-over-the-rationals-i-e-with-q-as-the-scal
Answer: Yes, $V$ is a vector space over $K$, but it is of infinite dimension over $K$.  Choosing a basis for $V$ over $K$ is a non-trivial matter that requires non-constructive foundational material such as the axiom of choice, see http://en.wikipedia.org/wiki/Axiom_of_choice
Comment: Mikhail, would the opposite be the case as well, i.e., can the Rationals be made into a vector space over the Reals? Well, as a field, they are a vector space over themselves. I'm a bit stale on this from long back, but maybe we can use Realification, and,  over the Complexes,  maybe Complexification?
Answer: A vector space over a field $K$ is any set $V$ equipped with functions $V\times V\to V$ and $K\times V\to V$ satisfying the axioms (I sometimes call them "computation rules").
So, since $\mathbb{R}$ with the two functions you mention satisfies the axioms, it is a vector space over the rationals. It is infinite dimensional, by reasons of cardinality: a finite dimensional vector space over an infinite field $K$ has the same cardinality as $K$.
In the same vein, $\mathbb{C}$ is a vector space over $\mathbb{Q}$ as well. This has important applications in the theory of algebraic numbers, because one can use the powerful machinery of vector spaces. Note that $\mathbb{C}$ and $\mathbb{R}$ are vector spaces over any of their subfields. One of the most useful results in this respect is the formula
$$
[M:L][L:K]=[M:K]
$$
where $M$, $L$ and $K$ are subfields of $\mathbb{C}$ (any field would do, actually) with $K\subseteq L\subseteq M$ and with $[L:K]$ we denote the dimension of $L$ as a vector space over $K$.
Answer: Anytime you have a field extension $V/K$ you can consider $V$ as a vector space over $K$.


Dealing with sequential/ordered data in SQL

Question: I apologize if this question has already been asked, attempted a search but could not find a relevant thread.
I have been given a semi-large data source (~15m records) which I need to perform some analysis on to determine user behavior. The data source includes fields for the User ID, date of the transaction, and a flag to indicate if the transaction had a certain characteristic. Obviously I'm simplifying here to get to the core of the question. The number of transactions by user will vary quite a bit (from 1 to 200+), the date distribution will vary, and the distribution of flags will vary.
Consider the following table:
ID          User ID         Date             Flag
1           1               2015-01-03       Y
2           1               2015-03-15       N
3           1               2015-07-20       N
4           1               2015-11-18       N
5           1               2015-11-29       N
6           2               2015-02-16       Y
7           2               2015-03-03       N
8           2               2015-06-10       Y
9           2               2015-08-10       Y

How would one go about querying this data to isolate records based upon the characteristics of other records for the same user before or after?
For example:

How would one identify records with a 'Y' flag which are followed by three other records (ordered by date) for the same User ID with an 'N' flag? [Would return 1 in the above table]
How would one identify User IDs where 50% or more of their transactions with 'Y' flags occur in the first 20% of their transactions? [Would return User ID 1 in the above table]

I hope the question is clear enough.
*Edit: The answer below is correct, however he did not know that I am using MySQL as the database (I added in the tag after he answered). MySQL DOES NOT support these functions, either Oracle or SQL Server would be able to implement these functions.
Comment: Please tag your question with the database you are using.
Answer: This question assumes a reasonable database that supports window/analytic functions.
The first question can be handled using lead():
select t.*
from (select t.*,
             lead(flag, 1) over (partition by userid order by date) as flag_1,
             lead(flag, 2) over (partition by userid order by date) as flag_2,
             lead(flag, 3) over (partition by userid order by date) as flag_3
      from t
     ) t
where flag = 'Y' and flag_1 = 'N' and flag_2 = 'N' and flag_3 = 'N';

The second also uses window functions:
select user_id
from (select t.*,
             row_number() over (partition by user_id order by date) as seqnum,
             count(*) over (partition by user_id) as cnt
      from t
     ) t
group by user_id
having sum(case when flag = 'Y' and seqnum/0.2 <= cnt then 1 else 0 end) >=
           0.5 * sum(case when flag = 'Y' then 1 else 0 end);

So, the answer to your question is basically:  Learn about window (analytic) functions.
Comment: Very interesting, I haven't seen these functions before but reading through the SQL I can kind of see what they must be doing. The database is MySQL and after a quick Google search it seems that I'll have no problem implementing this. Really appreciate the quick and detailed reply.


How can I get django to run a python program upon receiving an http request?

Question: I'm new to python and just finished the django tutorial. I have a django powered site and I'm writing an android application which needs to send and receive data from the same database managed by django. The website and the application provide the same functionality, but I don't want pages rendered for the application, I just want to send/receive commands and serialised objects. Essentially what I need to do is
receive http request (from mobile) in django ---> Run myProgram.py ---> Update database ---> send confirmation to client.
Could I have a few pointers about what/where to edit? Thanks.
Answer: It seems that you are trying to make an API with Django. You can read here more about REST APIs. The basic idea is that your web site will have a set of command links/urls - where each link will either do some action (update db, etc), just return some information (most commonly in JSON - e.g. return an object from db), or will do both.
What you will have to do is make a list of all possible commands the api will have to handle. That will include all the commands of retrieving, inserting, updating, and deleting data.
For this example, lets assume the only job of the application is to manage items in a store. This is a very simplified demo however it should get the point across.
Here is a Django model (within Store django app):
class Item(models.Model):
    name = models.CharField(max_length=255)
    price = models.IntegerField() # assume the price is always int
    quantity = models.IntegerField()

So then lets assume the possible commands for api are:

Get information about specific item
Get information about all items
Update information for specific item
Remove specific item
Add item to store

URL structure for all the commands
urlpatterns = patterns('',
    # will be used for getting, updating, and removing an item
    url(r'^item/(?P<item_id>\d+)/$', "item"),
    # will be used to get info about all items
    url(r'^item/all/$', "item_all"),
    # will be used to create new item
    url(r'^item/new/$', "item_new"),
)

Getting info about all items
For getting information information from django, django serialization functions are very helpful. Here is a django docs for that.
#views.py
from django.core import serializers
import json

def item_all(request):
    items = Item.objects.all()
    data = serializers.serialize("json", items)
    return HttpResponse(data, mimetype="application/json")

What this will do is return a JSON array with all the items like so:
[
  {
    pk: 1,
    model: "store.item",
    fields: {
      name: "some_name",
      price: 20,
      quantity: 1000
    }
  },
  // more items here
]

Adding new item
For this your android app will have to send a JSON object to the django.
JSON object:
{ data:
        {
          name: "some_name",
          price: 40,
          quantity: 2000
        }
}

So now your django app has to parse the info from the request in order to create a new item:
#views.py

def item_new(request):
    # the request type has to be POST
    if request.method != "POST":
         return HttpResponseBadRequest("Request has to be of type POST")
    postdata = request.POST[u"data"]
    postdata = json.loads(postdata)
    item = Item()
    item.name = postdata["name"]
    item.price = postdata["price"]
    item.quantity = postdata["quantity"]
    item.save()
    data = serializers.serialize("json", [item])
    return HttpResponse(data, mimetype="application/json")

Some notes:
Note the use of the POST request type. This is very crucial in REST API's. Basically depending on the request type, different actions will be done. This is going to be much more vivid in the next view.

Getting, updating, and removing
#views.py

def item(request, item_id):
    item = get_object_or_404(Item, pk=item_id)
    if request.method == "GET":
        data = serializers.serialize("json", [item])
        return HttpResponse(data, mimetype="application/json")
    elif request.method == "POST":
        postdata = request.POST[u"data"]
        postdata = json.loads(postdata)
        item.name = postdata["name"]
        item.price = postdata["price"]
        item.quantity = postdata["quantity"]
        item.save()
        data = json.dumps(True)
        return HttpResponse(data, mimetype="application/json")
    elif request.method == "DELETE":
        item.delete()
        data = json.dumps(True)
        return HttpResponse(data, mimetype="application/json")
    else:
         return HttpResponseBadRequest("Invalid request")

So what this method will be is do different actions according to the different request type.

Comments
Note that this is a very, very simple demo. It does not account for any error checking, user authentication, etc. But hopefully it will give you some ideas.


How to install fGarch package

Question: How do I install the fGarch package for R?  When I run install.packages('fGarch'), it returns package 'fGarch' is available as a source package but not as a binary.
Comment: This question appears to be off-topic because it is about how to use software.
Comment: try `install.packages("fGarch", type = "source")` - there are no binaries (for Windows, at least), but if you have a local FORTRAN compiler you're in business.
Answer: If you are using Rstudio, it is farily easy to install packages, just go to Tools on navigation bar, click on Install Packages....
You can do it in two ways:

Download the Cran packages from: http://cran.r-project.org/web/packages/fGarch/index.html, and choose "Install from Package Archive File"
Choose "Install from Repository", and type in fGarch, it will search,download, and install it for you automatically.
Comment: Well I believe Rstudio is one of the most popular interface tools for R scripting?
Comment: Why do you assume the OP uses RStudio?

How to install fGarch package


how to create the same directory name inside every sub-directory with linux bash

Question: let's suppose I have a directory structure and I want to create a directory called new inside each subdirectory recursively.
For instance, If I have
dir1
  |
  -------dir11
  |
  -------dir12
           |
           ------dir121
dir2

I want to create new directories like this:
 dir1
  |
  -------dir11
  |        |
  |        -------new
  |
  -------dir12
  |        |
  |        ------dir121
  |        |        |
  |        |        ---------new
  |        |
  |        ------new
  |
  -------new

dir2
  |
  -------new

Is it possible?
Answer: find . -type d ! -name "*new*" -exec mkdir {}/new \;

find all folders. make a folder in that folder called new. don't make folders in folders that have new in the same (otherwise it'll get dir1/new/new/new/new, etc)
Comment: didn't worked. I tried and created `./dir1/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/new/...`. Has to stop it
Comment: and there were no folders called new


Make sure Flex components are loaded at the beginning

Question: How can I make sure all the components, even those that are not going to be visible at the beginning, load right away when I start my application?
I  have an application with a ViewStack whose visible child is set via a sidebar menu. Say the ViewStack has two children, A and B. A is initially visible, whereas B is not. How can I make sure they both load at the beginning, so that when I change to B I don't have to wait for it to load?
Answer: each of your viewstacks should have
<code>creationPolicy = "all";
</code>
not sure if this can be set at the application level or not to control all children, but I know it works on viewstacks.
Comment: Well, viewStacks are all I need for now. Thanks.
Comment: I think that's valid for all Flex Containers, since ViewStack inherits that property precisely from the Container class.


Is there a way to control the variance of the singular values in SVD?

Question: I have an engineering problem in which I use SVD on matrix $\mathbf{A}$:
\begin{align}
\mathbf{A} &= \textbf{U} \mathbf{\Sigma} \textbf{V}^{*}
\end{align}
However, due to the fact that the singular values in the diagonal of $\mathbf{\Sigma}$ have a fairly large range, in my application some rows are more benefited than the others. Without going deep into the application (I know I`m not explaining it), it suffices to understand a large magnitude of the value in each row of $\mathbf{\Sigma} $ is desirable. Now, what I wanted to have was a form of decomposing $\mathbf{A}$ into a product "UnitaryMatrix x Diagonal x UnitaryMatrix", but such that the magnitudes in the diagonal of the diagonal matrix were more evenly distributed.
Here is a sample of the diagonal matrix in my application:
\begin{align}
\mathbf{\Sigma} = \left[
\begin{array}{ l l l l }
1.3333&0&0&0\\
0&0.84117&0&0\\
0&0&0.54855&0\\
0&0&0&0.4738\\
\end{array}
 \right]
\end{align}
It would be better, for example, to have
\begin{align}
\mathbf{\Sigma} = \left[
\begin{array}{ l l l l }
0.8&0&0&0\\
0&0.8&0&0\\
0&0&0.8&0\\
0&0&0&0.8\\
\end{array}
 \right]
\end{align}
Note, however, I can't simply redefine the diagonal matrix, because $\mathbf{A}$ is determined by physical properties which can`t be modified. Thus, the question is, is there a decomposition that would serve for this purpose (diagonal with more evenly distributed magnitudes)?
Comment: No, it is not possible. The underlying reason is that multiplying a matrix by a unitary matrix does not change its singular values. So, in your notation, $\mathrm{Diagonal} = \mathrm{UnitaryMatrix}^*\mathbf A\mathrm{UnitaryMatrix}^*$ must still have the same singular values as $\mathbf A$.
Comment: I'm not sure what is the question here. So, you seek a factorisation of $A$ in the form, say $A=BDC$ with some "nice" $D$. You can simply take any factorisation in the form $A=BC$ and take $D$ equal to the identity? Of course, if $A$ is "ugly" then necessarily $B$ and/or $C$ will be "ugly" in some sense then.
Comment: Exactly, @PavelJiranek, a seek a factorization A=BDC with a nice "D" and with unitary "B" and "C".
Comment: @igorauad I'm afraid that you can't find such a factorisation unless $A$ is already unitary.
Answer: Given the singular value decomposition
$$
 \mathbf{A} = \mathbf{U} \, \Sigma \, \mathbf{V}^{*}
$$
we note that the singular values are unique. The spectrum of singular values typically spans many orders of magnitude. They represent scale factors between the aligned orthonormal bases for the domain and the codomain. When you change the singular values, you change the scaling between the range spaces. You change the output matrix $\mathbf{A}$.
The following shows an example of singular value decomposition homogenization. Start with a 256 $\times$ 256 matrix, an image of Camille Jordan, scaled such that all values are within $[0,1]$. The image and its spectrum are shown below.

Next, the singular values are all set to unity,
$$
 \Sigma = \mathbf{I}_{256},
$$
and the image is reassembled. The range of data values is $[0.396485,-0.383183]$.


Combining two RegEx in JS

Question: I have two JS RegExes /\?(?!xml)/ig which looks for any ? not followed by string "xml" and another /\?(?!>)/ig which looks for ? not followed by ">".
How do I combine both into a single regular expression?
Comment: What do you mean by "combine"?  A then B, A or B, A and B,...
Comment: A or B. Sorry if it was unclear. I got the solution anyway. Thank you.
Answer: What about:
/\?(?!(xml|>))/gi

Edit: In any case consider parsing your XML properly with a parser instead of RegExp.
Comment: @elclanrs : Bang on! I just came to update the same expression. /\?(?!(xml|>))/ig

Combining two RegEx in JS


Prove that $11^{16} + 16^{11} \equiv 0 \mod {17}$

Question: I was checking the following Fermat's theorem exercise:

Prove that  $11^{16} + 16^{11} \equiv 0 \mod {17}$

Because both $11$ and $16$ are primes with $17$ I applied the theorem individually, so the first one
$$11^{16}\equiv 1 \mod {17}$$
gives me a result directly.
But the after applying the theorem to the second one
$$16^{16} \equiv 1 \mod {17}$$
I don't know the way to go back in the power from $16$ to $11$ which is the number requested. Is that as easy as $16 \equiv -1 \mod {17}$? Any help will be really appreciated.
Comment: Observe that $16\equiv -1\pmod{17}$.
Answer: First of all, the Fermat's theorem states that $a^{p-1} \equiv 1 \mod p$ if $p$ is a prime and $p \nmid a$. There is a condition on the exponent. Certainly $11^{16}$ simplifies to $1$ mod $17$ using this theorem.
For the other term, you cannot apply Fermat's theorem, because the exponent is $11$, which although prime is not $17-1$. However, the fact that $16 \equiv -1 \mod 17$, tells you that $16^{11} \equiv (-1)^{11} \equiv -1$ mod $17$. Now you can combine the two terms and conclude.
Answer: $$2^4\equiv-1\pmod{17}$$
$$16^{2m+1}=(2^4)^{2m+1}\equiv(-1)^{2m+1}\pmod{17}\equiv?$$
Answer: One correct approach:
$11^{16} \equiv 1 \pmod{17}$ by Fermat's Little Theorem. The justification is that $17$ is prime, that $11$ does not divide $17$ and that $16$ is one less than $17$.
$16^{11} \equiv(-1)^{11} \equiv -1 \pmod {17}$. The justification is the rules of modular exponentiation.
Add them up, and you get the required result.


Determine $x\in X=\{1,...,n\}$ by halving $X$ in $k$ ways s.t. each two halvings share $n/4$ elements.

Question: Let $X=\{1,...,n=2^k\}$ and $H_1,...,H_k$ be $\frac{n}{2}$-element subsets of $X$ which satisfy $|H_i\cap H_j|=\frac{n}{4}$ for each $i\neq j$.
My question is: can we determine the $x\in X$ uniquely by knowing whether $x\in H_i$ for each $i$?
Or equivalently, $|H_1\cap H_2\cap ... \cap H_k|=1$ ? (If this holds then $|\overline{H_1}\cap H_2\cap ... \cap H_k|$ etc. is also 1 by symmetry. So for example if we know $x\in H_i$ for all $i\neq1$ we can determine $x$ as the unique element of $\overline{H_1}\cap H_2\cap ... \cap H_k$.)
By definition $|H_1|=\frac{n}{2}$ and $|H_1\cap H_2|=\frac{n}{4}$, so
I think intuitively that adding one more $H_i$ to this intersection halves the number of the elements in the intersection, thus $|H_1\cap H_2\cap ... \cap H_k|=\frac{n}{2^k}=1$.
But the definition say nothing about intersections of 3 or more $H_i$'s...
Answer: Let $k=3, H_1=\{1, 2, 3, 4 \}, H_2=\{1, 2, 5, 6 \}, H_3=\{1, 2, 7, 8\}.$


Droid x2 Android 2.3.4 layout issue

Question: I have been writing apps for my Droid x2 using the new Android update 2.3.4.
The layout with of a simple test app show a margin on the left, right, and buttom side of the screen.
How do I get the full real-estate of the screen?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
>
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Hello World, MainActivity"
/>
</LinearLayout>

Screen shot: http://jasonfoglia.com/img/DROIDX2.png
Answer: I had the same problem and I think i solved it.
Insert this line into the Manifest and it works.
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="8"></uses-sdk>

For more information look at this site: http://realmike.org/blog/2010/12/21/multiple-screen-sizes-with-processing-for-android/

Droid x2 Android 2.3.4 layout issue


How to count number of running process with given name?

Question: How I could check how many instances of an executable is running also checking if each exe has a different PID?
--Edit--
What I already got:
The code display the PID correctly but szProcessName always return:

void DisplayProcessNameAndID(DWORD processID)
{
    TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");

    // Get a handle to the process.
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION |
        PROCESS_VM_READ,
        FALSE, processID);

    // Get the process name.
    if (NULL != hProcess)
    {
        HMODULE hMod;
        DWORD cbNeeded;

        //Given a handle to a process, this returns all the modules running within the process.
        //The first module is the executable running the process,
        //and subsequent handles describe DLLs loaded into the process.
        if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded))
        {
            //This function returns the short name for a module,
            //typically the file name portion of the EXE or DLL
            GetModuleBaseName(hProcess, hMod, szProcessName,
                sizeof(szProcessName) / sizeof(TCHAR));
        }
    }

    // Display the process name and identifier.
    CString str;
    str.Format("Text:%s, PID : %u", szProcessName, processID);
    //AfxMessageBox(str);

    //close the process handle
    CloseHandle(hProcess);
}

void Processes()
{
    // Get the list of process identifiers.
    DWORD aProcesses[1024], cbNeeded, cProcesses;
    unsigned int i;

    //This returns a list of handles to processes running on the system as an array.
    if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded))
        return;

    // Calculate how many process identifiers were returned.
    cProcesses = cbNeeded / sizeof(DWORD);

    // Display the name and process identifier for each process.
    for (i = 0; i < cProcesses; i++)
        if (aProcesses[i] != 0)
            DisplayProcessNameAndID(aProcesses[i]);
}

Comment: https://learn.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-enumprocesses
Comment: @paddy thanks i have found some examples using EnumProcesses, I have updated my post
Comment: Store the names in a `std::set`, `std::map` or similar.
Comment: @paddy this example i post is showing PID correctly but the process name don't, any idea why?
Comment: Maybe it's using UTF-16 characters, as is the WIndows default, and you're trying to output with `std::cout`.  I don't know.  Please don't use the comments section for a tutorial on the Win32 API.  If you have a specific question about a specific thing, post a new question, provide sample code, describe the behavior (with example output if possible) and explain why it differs from what you expect.
Comment: *To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege.* Try to get the return value of `OpenProcess` and call `getlasterror` if it failed, check whether it returns 5(access denied).
Comment: @DrakeWu-MSFT `hProcess` return 0x00000000000000 and `processID` return the PID correctly
Comment: And then does the following `getlasterror` return 5?
Comment: I dont know how to call getlasterror, I also tried debug with visual studio as admin, and got same value on hProcress 0x000
Comment: Try to use this sample:[Enabling and Disabling Privileges in C++](https://learn.microsoft.com/en-us/windows/win32/secauthz/enabling-and-disabling-privileges-in-c--) to enable the `"SeDebugPrivilege"` when run as admin.
Comment: use `EnumProcesses` very bad solution. need use `NtQuerySystemInformation(SystemProcessInformation, ...)`, *checking if each exe has a different PID* - this not need check at all
Comment: @DrakeWu-MSFT does the code works on your machine ? RbMm if my code prints the process name correctly would already help
Comment: Seems that the processes which failed to open are [protected process](https://learn.microsoft.com/en-us/windows/win32/services/protecting-anti-malware-services-), you could only open it with `PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE`. The following sample to list process with name works for me: [Taking a Snapshot and Viewing Processes](https://learn.microsoft.com/en-us/windows/win32/toolhelp/taking-a-snapshot-and-viewing-processes)
Answer: As mentioned in the comment, OpenProcess failed and the GetModuleBaseName function was skipped. The processes you opened are protected process. Even if you have the SeDebugPrivilege privilege, it can only allow PROCESS_QUERY_LIMITED_INFORMATION|SYNCHRONIZE access.
The following sample to list process with name works for me: Taking a Snapshot and Viewing Processes. And I made some simple modifications to meet your needs:
int main(void)
{
    int count = GetProcessCount(TEXT("notepad.exe"));
    _tprintf(TEXT("The Number of process %s has %d instance \n"), TEXT("notepad.exe"), count);
    return 0;
}

BOOL GetProcessCount(const TCHAR* name)
{
    HANDLE hProcessSnap;
    HANDLE hProcess;
    PROCESSENTRY32 pe32;
    DWORD dwPriorityClass;
    int count = 0;
    // Take a snapshot of all processes in the system.
    hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == INVALID_HANDLE_VALUE)
    {
        printError(TEXT("CreateToolhelp32Snapshot (of processes)"));
        return(FALSE);
    }

    // Set the size of the structure before using it.
    pe32.dwSize = sizeof(PROCESSENTRY32);

    // Retrieve information about the first process,
    // and exit if unsuccessful
    if (!Process32First(hProcessSnap, &pe32))
    {
        printError(TEXT("Process32First")); // show cause of failure
        CloseHandle(hProcessSnap);          // clean the snapshot object
        return(FALSE);
    }

    // Now walk the snapshot of processes, and
    // display information about each process in turn
    do
    {
        _tprintf(TEXT("\n\n====================================================="));
        _tprintf(TEXT("\nPROCESS NAME:  %s"), pe32.szExeFile);
        _tprintf(TEXT("\n-------------------------------------------------------"));

        _tprintf(TEXT("\n  Process ID        = 0x%08X"), pe32.th32ProcessID);
        if (_tcscmp(pe32.szExeFile, name) == 0)
            count++;

    } while (Process32Next(hProcessSnap, &pe32));

    CloseHandle(hProcessSnap);
    return count;
}

void printError(const TCHAR* msg)
{
    DWORD eNum;
    TCHAR sysMsg[256];
    TCHAR* p;

    eNum = GetLastError();
    FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL, eNum,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        sysMsg, 256, NULL);

    // Trim the end of the line and terminate it with a null
    p = sysMsg;
    while ((*p > 31) || (*p == 9))
        ++p;
    do { *p-- = 0; } while ((p >= sysMsg) &&
        ((*p == '.') || (*p < 33)));

    // Display the message
    _tprintf(TEXT("\n  WARNING: %s failed with error %d (%s)"), msg, eNum, sysMsg);
}

Comment: thank you I have tested it and its working, may I ask, in what case it could not count a process?