Tempo conservation with Time Signature Change, How to notate this for Classical Musicians?

Question: So, I am writing a Scherzo in the key of Eb major for a string quartet. And I was just thinking about what to do for the B section of my Scherzo, both in key and time signature. I was thinking that for the time signature, I should maybe do a change from 2/4 to 6/8. Now I could just do that, keeping the quarter note speed at 160 quarter notes per minute and thus changing the tempo of the 6/8 section to 107 BPM. But, that is going to slow down the 6/8, possibly to the point where it feels like 6 beats rather than 2. I want to keep the tempo the same in the 6/8 section as in the 2/4 section, 160 BPM, so as to keep the feel of Allegro vivace going.
To do this, the speed of the quarter notes has to change to a faster speed. There are 3 ways I could convey this to the string quartet players. I'm not sure though which way to do it. Here are the 3 different ways I could convey this tempo conservation:
Option 1: Have the Time Signature imply the change in quarter note speed
This would be the simplest route. I wouldn't have to write down anything but the time signature change. But, what are the chances that the string quartet ensemble is going to conserve the 160 BPM tempo in a time signature change from 2/4 to 6/8? Pretty minimal right? Most likely thing to happen here would be that the 6/8 would be slowed down(just like how, when I see a time signature change from 4/4 to 2/2, the 2/2 generally speaking feels faster than the 4/4, even if only the time signature change is indicated).
Option 2: Metric Modulation relative to the quarter note
Metric Modulation is just what it sounds like. The tempo is conserved but the note value getting the beat changes, thus giving the feel that the music is going faster or slower. In this case, having it relative to the quarter note, I should probably have a switch back to 2/4 towards the end of the B section, towards the Scherzo Da Capo. So I would put in this marking at the time signature switch to 6/8 and back to 2/4(6/8 on the left, 2/4 on the right):

Option 3: Metric Modulation relative to the eighth note
Same idea as with Option 2, but with the eighth note being the note value that everything is relative to. I do use a lot of eighth notes and dotted rhythms in the 2/4 section, so it might make sense to use the eighth note as the basis for the Metric Modulation which would mean this:

and vice versa for the switch back to 2/4. Unfortunately, there is no easy way to do the eighth note metric modulation as indicated in my Musescore software. The only real way to get that would be to make everything but the 2 eighth notes and triplets invisible, put in an equal sign via text, do an image capture, and then add that image to the Musescore palatte. And then I would have to do the same thing for the reverse. It is a lot more work.
Out of these 3 options, which one would be the best for getting across what I want(tempo being conserved while time signature changes) to a string quartet? Just letting the time signature imply the change, Metric Modulation relative to the quarter note, or Metric Modulation relative to the eighth note?
Comment: Did you consider notating the "Ebm" section in D#m instead? That might be easier on string players. Regardless, since the issue with the key signature is irrelevant to your question, I recommend editing it out of the OP.
Comment: Did you consider merely notating the 2/4 section as 6/8 and dotted crotchets? The quavers you might have in 2/4 bars then become 6/8 duplets.
Comment: @AndrewLeach No, I haven't considered that. I don't often see duplets in 6/8(though maybe that's because I don't see nearly as much in 6/8 as I do in 2/4 and most of what I do see in 6/8 sort of amounts to a waltz rhythm in 2/4), I normally see 3 note groupings that, if in 2/4 would be triplets.
Comment: I find #2 so standard in notation that I was surprised that MuseScore didn't have it as an automatic glyph. That said, in classical, I've also seen simply using triplets in the duple meter. See, for example, the 1st Movement of Beethoven's Moonlight Sonata. It's rarely if ever notated in 12/8.
Comment: Musescore does have #2 as a "Metric modulation" glyph, and it can usually act on that sort of thing with its own playback. Musescore 3.3.4 appears not to do that: quavers simply carry on at the same speed.
Comment: @trlkly If you open the Tempo palate and scroll past the Italian words, you will see Metric Modulation markings, including quarter = dotted quarter and dotted quarter = quarter
Comment: @Caters Neat. That wasn't there when I was looking for it before--I even looked up how to do it on the MuseScore website, and they said you had to make it manually. I'm glad they added it.
Answer: I'd use your second option: metric modulation relative to the quarter note.
With no notation at all, the unwritten convention I've witnessed is actually to assume a quarter note (or an eighth note, etc.) has the same tempo value throughout, so 2/4 to 6/8 does indeed have the duple meter feel slow down. On the other hand, at least there aren't many complaints about how to handle a series of changes from 4/4 to 3/4 to 5/4 to 7/8! Therefore, I do not recommend letting the time signature imply the change--it often doesn't.
The only time I've seen multiple notes on the same side of the equals sign is in swing notation, so I don't recommend your use of metric modulation relative to the eighth note.
Answer: I agree with @Dekkadeci that this option is a good option:

That kind of change is common and easy to understand.
@Caters Now regarding the key signatures. E♭ minor is fine on piano because it can fit the hands very well. But as you indicated it is not so nice on the strings. Why not make the whole thing a half step lower by changing the keys to D major and D minor. That will be very good on the strings. Another option is a half step higher, E major and E minor, but the D major/minor option is especially good I would say.
Comment: And yet another option is to not use the parallel minor at all but rather the relative minor. Most Scherzi and other pieces in Scherzo form that I hear such as the Beethoven's Ninth Scherzo, Bagatelle in C minor, etc. use the parallel minor and major for their minor-major shifts. But some, such as the Scherzo from Beethoven's Piano Sonata no. 3 use the relative minor instead. Using the relative minor of C minor for the 6/8 section would keep the minor-major shift, keep the tonic of Eb major, and make it easy on the string instruments.
Comment: @Caters Yes you can certainly do that.
Answer: Option 2 for the tempo indication. It's the beat that matters. You're saying 'quqrter beat becomes dotted-quarter beat'.  Probably what the players would assume, but good to spell it out.
No, I wouldn't inflict 6 flats on a string quartet! In this age of free-ranging and even atonal music they are quite accustomed to playing any notes in any order at all. But if, as I suspect, you're writing in a tonal style, there seems little reason for E♭ minor.
If your ear hears a 'parallel minor' move, MUST you start in Eb major?  Why not D major or E major?  But there are plenty of other places to go.    You can go to the parallel minor for the Trio if you like. It's not required. (Is it even THAT common?) If there is a 'rule' for a Scherzo and Trio it's that, as a descendent of the classical Minuet and Trio, it's in a fast 3 time.  You're breaking that rule! (And that's just fine.)
(If you DID want the two-8ths = three-8ths metric modulation, MuseScore will do it with a bit of editing and the Special Characters menu. The triplet number is trickier - not saying MuseScore can't manage it, but I haven't worked out how yet!  You wouldn't need it anyway. 8th groups in 6/8 aren't triplets. Otherwise music in 6/8 would be knee-deep in triplet numbers.)
Comment: Most of the Scherzi I have heard went to the parallel minor/major for the trio. Not just Beethoven Scherzi either. Scherzi going to the parallel key for the Trio: Beethoven's Ninth Movement 2, Bagatelle in C minor WoO 52, Beethoven's Fifth Movement 3, Chopin Scherzo no. 1 in B minor, etc. Scherzi going to the relative key for the Trio: Beethoven Piano Sonata no. 3 Movement 3, probably a few others. So yeah, the parallel key is pretty common for the Trio, more so than the relative key. But that doesn't mean mine can't be in Cm for the Trio instead of Ebm since Cm is easier on strings.
Answer: As a former string quartet professional, I'd also go with option two. Yes, it's the beat that matters, and this most clearly and simply conveys that. Regarding key, it depends on the sonority you want from the strings. Keys with lots of accidentals tend to somewhat mute the sound of the string instruments. This has to do with the sympathetic vibrations of the open strings and their overtones. This is why Mozart wrote the viola part for his Symphonia Concertante in scordatura D Major, to get a brighter sound from the viola than the Eb key would allow. Also, the higher tuning puts more tension on the strings, which also brightens the sound.


Forecasting monthly time series with known periodicity and a known driver

Question: For 2004-2014, I have monthly measurements of my outcome of interest - some kind of physical exposure - for a collective of many thousand persons. The main determinant for the average exposure level is the intensity of the physical source (correlation ~ 0.7). This intensity was measured 1993-2014 in monthly intervals - it is periodic with a known cycle length.
The collective has three groups (A, B, C) which differ in their behavior such that their average time within proximity of the physical source differs - and thus their average exposure level. Yet, the correlation between their average monthly exposure is very high (~ 0.95). The smoothed monthly group averages look like this:

For group A, I have individual exposure measurements also for 1993-2004, but for B and C, no measurements exist for this period. I would like to retrospectively forecast the missing exposure given a) the intensity of the toxic source and b) the measured exposure for A. How can I do that?
I am only interested in prediction, not in testing. However, I also need a quantification of the forecast error variance. Pointers to relevant R functions / packages would be highly appreciated as well.
Comment: Interesting question. Do you also have the data for the driver in 1993-2004? Could you post the data? An extremely simple approach would of course be regressing B and C on A and then predicting them, using the known values of A, and then you could use simple cross-validation/bagging to estimate the error variance. How certain are you that the correlation of 0.95 you measured in one 10 year period also holds in a different 10 year period?
Comment: @StephanKolassa With "driver", do you mean the intensity of the physical source? Yes, that data is available for 1993-2004. Unfortunately, the data is confidential. Yes, I expect a high correlation also in 1993-2004: When members of B/C are exposed, their exposure is the same as for members of A. It's just that they can differ with respect to how much time per month they are exposed (this "time under exposure" is unkown). I have no background in time series, so I have no idea how simple a possible solution might be. I just don't want to make typical beginner's mistakes.
Comment: Thanks for the clarification. I +1'ed [Gaurav's answer](http://stats.stackexchange.com/a/161756/1352). A simple regression should be quite fine for your use case. Good luck!
Answer: I can't comment so I am answering it directly.
For the part b - I agree with Stephan - Use regression. From the graph, it seems a linear regression should work fine without any transformation.
For the part a - Since you have intensity of toxic source from 1993 to 2014, and you have exposure for both B and C, you could directly regress Exposure on intensity for B and C individually. You will need to analyze the graph of intensity/exposure for the best transformation that you might need before doing a linear regression.
Since you will be regressing only on one variable, this link should help you with R functions.
http://courses.statistics.com/software/R/R_Ch02.htm.
Comment: I am concerned about the OLS parameter estimates given correlated errors from the repeated measures. I somewhere read that they loose efficiency. Are there better estimators?
Comment: yes, correlated errors cause problems is regression. One easy way to find out is to plot the residuals and check if they look correlated. There are some tests like Durbin Watson test but using this test correctly requires knowledge of time series. I would suggest that "correlation in errors" is a different question, and this question might have been answered already.


the max of four random variables that are greater than 4.5?

Question: I am currently studying for a final I have really two questions.
If I have four independent random variables A,B,C,D, while A continuous exponential(mean=4), B is discrete uniform(1,6), C is continuous normal(3.5, 1), and D is discrete binomial(n=5, p=.90 or 90%). What is the probability that their max is >= 4.5? basically compute Pr(max(A,B,C,D >= 4.5)
My first question is how do I construct the joint density function for these random variables. I know how to do it when the r.v.'s are all continuous, but here I have 2 continuous and 2 discrete r.v. I don't know how to construct a joint density of all four of these variables. Also my second question is I am supposed to find the probability without knowing (memorizing the formula) the P.D.F of the normal.
Comment: $P(\max>4.5)=1-P(all\le 4.5)=1-\prod_{i=1}^4 P(X_i\le 4.5)$. As for your second question, remember 68-95-99.7 rule - which are probabilities for the normal to be within 1-2-3 deviations from the mean. Hence $P(N(3.5,1)\le 4.5)\approx 0.68+0.32/2\approx 0.84$.
Comment: Memorising the pdf of a normal distribution will not help much.  Instead you need to be able to lookup $\Phi(1)$ from the CDF of a normal distribution.
Comment: Ok thank you I know how to look up the z-score. I was just thinking that I had to have four density functions. Now I know that is not the case.
Answer: You don't need to construct the joint density. All you need to do is note that $P(max(A, B, C, D) < 4.5) = P((A < 4.5) \wedge (B < 4.5) \wedge (C < 4.5) \wedge (D < 4.5))$, i.e. the space in which the maximum of all four is less than a certain value is the space in which all four of the variables are less than that value.
Answer: You don't construct the joint density, because doesn't exist(exist if the random variable is absolute continuous).
Note that, because are independent, $P(A=a,B=b,C=c,D=d)=P(A=a).P(B=b).P(C=c).P(D=d)$ and you can calculate this four probabilities


Quero usar DISPLAY:FLEX no CSS mas não estou conseguindo?

Question:

.OrganizarPosicao{
display:flex;
Justify-content: center;
}

Comment: Vc quer centralizar?
Comment: Sua pergunta está muito vaga, o que vc precisa exatamente?
Answer: Entendo que você quer alinhar o iframe, no meio de sua página.
Dessa maneira, você não deve aplicar a propriedade display no iframe, mas, sim, no elemento pai.
Nesse sentido, a mesma coisa ocorre com o a propriedade justify: ela deve ser aplicada no elemento pai do .OrganizarPosicao.

Dado isso, poderias fazer algo como esse código:

body {
  background: cyan;
}

.pai {
  width: 100%;

  display: flex;
  justify-content: center;
}

.linkedin {
  width: 50%;
  height: 50%;
}

Ps: Note que usei uma imagem para substituir seu iframe, assim como a classe .linkedin foi trocada por .OrganizarPosicao.


How to check whether a directory exists or not in delphi XE2?

Question: I want to create a directory say TestDir but only when that directory does not exist. I don't find the way the check the existence of that directory.
I am using following function to create the directory.
CreateDir('TestDir')

How should I make sure that I use this CreateDir function only when TestDir does not exist?
Comment: Don't bother checking before creating. It introduces a race condition. Just call [`ForceDirectories`](http://docwiki.embarcadero.com/Libraries/XE2/en/System.SysUtils.ForceDirectories) to check and create at the same time.
Comment: Rob is quite right. Just create the directory and handle any failure appropriately.
Answer: In Delphi XE2, you can use the IOUtils unit TDirectory record, like this:
uses IOUtils;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if not TDirectory.Exists('test') then
    TDirectory.CreateDirectory('test');

In Delphi7, you can use the DirectoryExists function from the SysUtils unit:
uses SysUtils, Windows;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if not DirectoryExists('test') then
    CreateDir('test');

Answer: There's a routine in SysUtils called DirectoryExists that should do exactly what you need...
Answer: CreateDir can only create directories that are one level "higher" then an existing directory. E.g., CreateDir('C:\Folder1\Folder2') only works if C:\Folder1 already exists, and likewise CreateDir('C:\F1\F2\F3') only works if C:\F1\F2 exists. For creating the "in-between" folders in one step, you use Delphi's ForceDirectories.
procedure TForm1.Button2Click(Sender: TObject);
begin
  if DirectoryExists(Edit1.Text) then
    ShowMessage(Edit1.Text + ' exists already')
  else begin
    ForceDirectories(Edit1.Text);
    if DirectoryExists(Edit1.Text) then
      ShowMessage('Folder created: ' + Edit1.Text)
    else
      ShowMessage('Could not create ' + Edit1.Text);
  end;
end;


How to prove this series problem: $\sum_{r=1}^\infty \frac{(r+1)^2}{r!}=5e-1$?

Question: Can I have help with this problem?
$$\sum_{r=1}^\infty \frac{(r+1)^2}{r!}=5e-1.$$
Comment: Hint: $$(r+1)^2=r(r-1)+3r+1$$
Comment: The upper limit was to $\infty$ right? I couldn't quite tell from the picture.
Comment: This might help you with your question: [What's the value of $\sum\limits_{k=1}^{\infty}\frac{k^2}{k!}$?](http://math.stackexchange.com/q/44113) And you might also have a look at other posts [linked there](http://math.stackexchange.com/questions/linked/44113).
Answer: $$\sum_{r=1}^{\infty}\frac{(r+1)^2}{r!}=\sum_{r=1}^{\infty}\frac{r^2}{r!}+2\sum_{r=1}^{\infty}\frac{r}{r!}+\sum_{r=1}^{\infty}\frac{1}{r!}=\sum_{r=1}^{\infty}\frac{r}{(r-1)!}+2\underbrace{\sum_{r=1}^{\infty}\frac{1}{(r-1)!}}_{e}+\underbrace{\sum_{r=1}^{\infty}\frac{1}{r!}}_{e-1}$$
thus
$$\sum_{r=1}^{\infty}\frac{(r+1)^2}{r!}=\sum_{r=1}^{\infty}\frac{r-1+1}{(r-1)!}+3e-1=\underbrace{\sum_{r=2}^{\infty}\frac{1}{(r-2)!}}_{e}+\underbrace{\sum_{r=1}^{\infty}\frac{1}{(r-1)!}}_{e}+3e-1=5e-1$$


What is the history of the Augmented Second in World Music

Question: In his book Gypsy Music, Bálint Sárosi states that the Augmented Second --- as found between the second and third, third and fourth, sixth and seventh in a lot of Gypsy as well as Indian and Middle Eastern music --- came into the music of Eastern Europe (specifically Hungary) through the influence of the Ottoman Empire (who I also understand created cymbals and brass instruments.)
I also find the augmented second in Indian, as well as Middle Eastern music and am hoping someone can shed some light on where it might have come to Turkey from and potentially its earliest examples in folk music.
Comment: I think the difference between finding it as an augmented second and as a minor third would be one, that there's not a scale tone between the two if it's a second and also that the augmented second would probably be between the second and third, third and fourth or sixth and seventh scale tones and not between the primary chord tones (tonic, third, fifth, seventh).
Comment: @Tim Actually, "Phrygian with a major third" is one of the most common modes of the harmonic minor. Especially common in metal and industrial music.
Comment: I'm guessing a lot of that kind of music wasn't written down. Why is it called an augmented 2nd, when it likely could be a minor 3rd? In anything apart from 12ET it IS a different note, by 40 cents, but would that have been picked up at that time?
Comment: I wonder if this question is too broad.
Comment: Dude, the Ottoman Empire was founded in 1299AD.  Simple trumpets, made of metal, even, go back at least two thousand years before that.  The Ottoman Empire may have made great contributions to the brass instruments, I don't know.  But they assuredly didn't get there first.  P.S. [cymbals](https://en.wikipedia.org/wiki/Cymbal#History)
Comment: As in harmonic minor, notes 6 and 7?
Comment: The augmented second between the sixth and seventh tone degrees is the reason why the harmonic minor has its distinct middle eastern feel
Comment: updated question.
Comment: @Tim I think in the case of the particular piece of music that was being discussed in the book, it was a phrygian scale with a major third,  so between the second and third scale tones. But yes, if harmonic minor (i'm forgetting) has a minor 6th and a major 7th that would be an good example of the augmented second in Western music.
Comment: Phrygian with a major 3 ? Not seen that one! Usually tones and semis, so an interval of a tone and a half is quite a rare beast in scales (or modes), but there's going to be one in every mode of harmonic minor. They're there in dimished scales/ arps., but as m3s.
Comment: @Codeswitcher it's not unlikely that my concept that the Turks had developed brass instruments is not accurate, but you are also not mentioned another culture that did invent them.
Comment: @MikeiLL  Feel free to google for yourself.  Or just go to wikipedia.  This isn't a mystery.
Answer: I briefly studied Gypsy history, and there is one theory that the Gypsies originated in India and migrated north into Eastern Europe and Hungary, passing through Turkey.
One of the musical forms they would have brought with them is the Indian Raga. In the Carnatic Raga there is a scale form that includes a raised second note, playing up what we would call and Augmented second.
There are other migrations north from India as well, predating the Ottoman Empire, so it is likely that musics in the region using the form with the raised 2nd degree were influenced from the Indian music.
The music is an aural tradition so early transcriptions are difficult to find. There was an interest in Gypsy history in the 1800's in England, but much of the information collected is suspect, as the Gypsies were known to be reluctant to share their actual traditions with outsiders.
Comment: yes. i want to research _when_ those ragas were developed.


sigma fields measures

Question: I am studying basics measure theory, and am stuck with the following problem:

Let Ω = {(i, j) : i, j ∈ {1, . . . , 6}}, F = P(Ω) and define the
random variables $X_1$(i, j) = i and $X_2$(i, j) = j.
Is X1 + X2 measurable with respect to either σ($X_1$) or σ($X_2$)?

The given answer to this is no because :

For example, take B = {12}. Then
{ω ∈ Ω : $X_1$(ω) + $X_2$(ω) ∈ B} = {(i, j) ∈ Ω : $X_2$(i, j) + $X_2$(i, j) = 12}
= {(i, j) ∈ Ω : i + j = 12} = {(6, 6)},
which is in neither of the two sigma fields σ($X_1$), σ($X_2$).

The part that troubles me is that from what I understood, the σ($X_1$) is the list of all unions of the atoms [{(i,1),(i,2)...(i,6)} for i in range (1-6 included)] which does include (6,6) in one of it's atoms.
Where is my confusion ?
Thank you for reading!
Answer: $X_1(i,j)=k$ is same $i=k$ and $j$ arbitrary. This means $\sigma (X_1)$ consists of sets of the form $A \times \{1,2,3,4,5,6\}$ with $A \subseteq \{1,2,3,4,5,6\}$. So $\{(6,6)\}$ is not in $\sigma (X_1)$

sigma fields measures


how can I log an entry in the database after a failed connection (the entity manager is closed)

Question: In my symfony 2/doctrine2 application, I am using an entity listener to catch exceptions and send myself an email if the error is not yet logged in the database.
It works fine except when the error is a failed entry in the database. In that case, the entity manager is closed and I cannot use it anymore in my exception listener.
I cannot reset the entity manager because it would repersist any entity and throw new errors (new entity was found through...)
I'd prefer not to use a different entity manager because it is a pain to remap every entity.
Any idea of how I could solve this ?
Thansk a lot !
Comment: Or make an entity manager specifically for logging.  That way you don't need to change your other entities.  You could also make your logger dependent on the database connection (instead of the entity manager).  The connection will stay open even if the entity manager throws an exception.
Comment: I believe things like this are already logged the log folder, are they not? Maybe it would be efficient, it you wrote a reader for this log file and search for doctrine logs (doctrine channel).
Comment: well, that could be a substitute but logs can be reseted any time, so that's not really what I want here...
Comment: The only solution I see is to use the doctrine channel for logging as tomazahlin suggested.
Answer: We had the same problem in our project, because we use the DB to spool our mails, and we have a mail error reporter. So, in the event of an exception that closes the EM, we have a "patch".
We partially solved the problem creating a new instance of the EM when needed. It's not a perfect solution, but it works. Anyhow, it's a failover, not a normal operation.
We placed this code in our email spooler:
<code>    if(!$this->em->isOpen()) {
        $connection = $this->em->getConnection();

        while($connection->getTransactionNestingLevel() > 0) {
            // clean-up of any open transaction
            $connection->rollBack();
        }

        // new EM
        $this->em = $this->em->create($connection, $this->em->getConfiguration());

        // this is needed if you use the Blameable extension,
        // because at this point of the code, we no longer have a logged user to "blame"
        $user = $this->em->getRepository('FacileCbrCoreBundle:User\User')->loadUserByUsername('facile_cbr');
        $emailEntity->setCreatedBy($user);
    }
</code>
Comment: I went for creating a new entity manager but the blameable tip was useful!


Newbie-question: how to use hooks

Question: Ok, this is a newbie-question i'm afraid to ask for some time .. how to use Drupal Hooks?
Yes, i know where to look for the code, but then? Put it in the template-folder, a block, a custom module?
When i google for a tutorial, the most results are for Drupal 6 / before 2010.
Comment: Yes google can answer a lot of questions, but if **really** want to know how something works **always** look for documentation. https://api.drupal.org/api/drupal is **not** a waste of web storage, please give some credit who woks to maintain this doc.
Answer: Drupal Hooks are a call back mechanism, you name your function modulename_Hook like mymodule_form_alter(). Based on the name of the function, it is called in the proper phase of the Drupal execution. This is an entry point from Drupal into your module.
Using Drupal Hooks doesn't change that much from version to version, the hooks that are available do change from version to version. The old tutorials are still good. The best way to learn how to use hooks is to examine existing contributed modules, or that's what worked for me. Hooks you really need to learn, or that you should start with are the FORM API hooks hook_form_alter, hook_form, hook_form_validate (https://api.drupal.org/api/drupal/includes!form.inc/function/drupal_form_submit/7), ..., hook_menu is generally needed if you're adding a page to the website.
If you can get a copy of "Pro Drupal Development" or "Pro Drupal 7 Development" (http://www.drupalbook.com/ or http://www.amazon.com/Drupal-Development-Experts-Voice-Source/dp/1430228385) it might help as well. Go with the pdf downloads. There are also 2 or 3 day classes you can take, or you can get training at your local Drupal Camp or Drupal convention.
Comment: Since chx answered the original question, I suggest that you use that answer. chx is quite a respected member of the Drupal community.

Newbie-question: how to use hooks


prevent duplicate while merging redux array of objects with setState array

Question: First of all one general question that how to concat setState array with redux array? In my implementation, there is a configured list which is based on setState array of objects. Now, i have a location list which is based on redux array of objects. Now i am adding one item from location list to configured list using concat and saving the data. It is successfully saved but in merged list it is displaying 3 items (that redux array item 2 times).
But, i checked in console although it is showing correct result(2 items) but why it is displaying 3 items(redux item 2 times).
Component code:(getLocationData method where i did the concatenation part and calling that method in other component using callback ref and working fine)
export class NewLocationPanel extends React.Component{
    constructor(props){
        super(props);
        this.state={
               open:false,
               configuredList:[],
               retrievedList:[]
        };
       this.configLocation = this.configLocation.bind(this);
        this.togglePanel = this.togglePanel.bind(this);
        this.handleClick = this.handleClick.bind(this);
        this.allLocations = this.allLocations.bind(this);
        this.clearall = this.clearall.bind(this);
        this.getLocationData = this.getLocationData.bind(this);
        this.handleRemove = this.handleRemove.bind(this);
        this.removeConfigLocation = this.removeConfigLocation.bind(this);
        this.mergedLocation = this.mergedLocation.bind(this);
    }

    togglePanel (e){
        this.setState({open : !this.state.open});
    }
    handleRemove(mruCode){
        this.props.removeLocation(mruCode)
     }
    handleClick (mruCode){
      this.props.addLocation(mruCode)
     }
     allLocations (){
       this.props.addAllLocation()
    }
    clearall (){
        this.props.removeAllLocation()
    }

    componentDidMount() {
        this.props.loadData();
        if(this.props.locationData !=null && this.props.locationData!= undefined){
            this.configLocation(this.props.locationData);
        }
      }

    componentDidUpdate(prevProps,prevState){
        if ((prevProps.jobId != this.props.jobId || prevProps.locationData != this.props.locationData) && this.props.locationData != null && this.props.locationData != undefined) {
            this.configLocation(this.props.locationData);
            this.mergedLocation();
        }
    }

    configLocation(locationData){
        let configuredList =[];
        if(locationData.locations.locationDetails != null && locationData.locations.locationDetails !=undefined ){
            locationData.locations.locationDetails.map(item=>{
                 let listitem ={...item};
                 configuredList.push(listitem);
            });
        }
        this.setState({configuredList},()=>{
            console.log(this.state.configuredList);
        });
    }

    removeConfigLocation(index){
        this.setState({
            configuredList:this.props.locationData.locations.locationDetails.filter((_,i)=>i!==index)
        },()=>{
            console.log(this.state.configuredList);
        });

    }

    mergedLocation(){
         if(this.props.conLocations != null && this.state.configuredList !=null){
             const{configuredList} = this.state;
             let retrievedList = configuredList;
             this.props.conLocations.forEach(loct => {
                 const locationAdded = retrievedList.find(_loct=>loct.mruCode=== loct.mruCode)
             });
          this.setState({
              retrievedList},()=>{
            console.log(this.state.retrievedList);
          });
         }
    }

    getLocationData(){
        let saveableLocationlist = [];
        if(this.state.retrievedList != null){
            saveableLocationlist = retrievedList;
        }
        const locationData = {
            locationDetails : saveableLocationlist
        }
      return locationData;
    }

    render(){
        //const{configuredList} = this.state;
        const _labels = store.getLabels();
        let collapsedToggle = this.props.open ? 'collapsed' : ''
        return(

this.togglePanel(e)}>

                     {this.props.title}

                        {this.state.configuredList.map((loc,index)=>{loc.mruCode} - {_labels[loc.division]} - {loc.country})}
                           this.togglePanel(e)} className={this.state.open ? "collapse-chevronn" : "collapse-chevron"} aria-hidden="true">

              {this.state.open?(

Locations List
<button style={{ display: this.props.location.length === this.props.conLocations.length ? "none" : "block" }} className="allLargeBtn" onClick={()=>{this.allLocations()}}>Add all locations</button>

                             {this.props.location.map((item,index)=>(

{item.mruCode} - {_labels[item.division]} - {item.country}{!this.props.conLocations.find(item2 => item.mruCode === item2.mruCode)&&(
<button style={{ display: this.state.configuredList.find(item3=> item.mruCode===item3.mruCode) ? "none" : "block" }} className="call-to-action" onClick={()=>{this.handleClick(item.mruCode)}}>Add Location</button>
)}

))}

Configured Location
<button className="allLargeBtn" onClick={()=>this.clearall()}>Remove all location</button>

{this.state.retrievedList.map((locc,index)=>
{locc.mruCode} - {_labels[locc.division]} - {locc.country}	{this.removeConfigLocation(index)}} className="deleteIconStyle" src="img/delete_large_active.png" />
)}

):null}

        );
    }
}

const mapStateToProps = state =>{
    return{
        location:state.locationRed.location,
        conLocations:state.locationRed.conLocations
    };
};

const mapDispatchToProps = (dispatch) => {
    return{
        loadData:()=>{dispatch(loadData())},
        addLocation:(mruCode)=>{dispatch(addLocation(mruCode))},
        addAllLocation:() =>{dispatch(addAllLocation())},
        removeLocation: (mruCode)=>{dispatch(removeLocation(mruCode))},
        removeAllLocation: () =>{dispatch(removeAllLocation())}
    }
}

export default connect(mapStateToProps,mapDispatchToProps,null,{withRef:true})(NewLocationPanel);

Jobs Component(where i am calling getLocationData to save updated value of jobs...It is saving the details properly)
import React from 'react';
import ReactDOM from 'react-dom';
import LocationPanel from '../panels/NewLocationPanel';

class JobsPanelComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            jobDetailJson: this.props.jobDetailJson

        };
this.setLocationPanelRef = cRef =>{this.locationPanel = cRef;};

}
componentWillUnmount() {
        this.clearStates();
        this.clearRefs();
        this.clearBindings();
    }
          clearStates() {

        this.state.jobDetailJson = null;
        }
        clearRefs(){
               this.locationPanel = null;
                   }
        clearBindings(){
               this.setLocationPanelRef = null;
                       }
        componentWillMount() {
        this.state.jobDetailJson = this.props.jobDetailJson;
    }

    componentWillReceiveProps(nextProps) {
        this.state.jobDetailJson = nextProps.jobDetailJson;
    }
     saveJobData(jobData){
      var locationData = null;
       if(some conditions){
        locationData = this.locationPanel.getWrappedInstance().getLocationData();
      }
    //more other lines not related to my mine
     }
      render(){
         var locationDataJson= null;
             if(this.state.jobDetailJson != null){
                     locationDataJson =this.state.jobDetailJson;
                   }
         return(

               <LocationPanel ref={this.setLocationPanelRef} locationData ={locationDataJson} jobDetailJson={this.state.jobDetailJson} versionId={versionId} jobName={jobName} jobId={jobId} isForViewOnly={this.props.isForViewOnly} parentJobId={this.props.parentJobId} title="Location"/>
     //More coded lines for other things not related to my part
              );
         }

}

I am adding current output which is showing 3 results but it should show 2 results. How to prevent that.Please help me on this.
Comment: Put console.log in getLocationData for configured list and conLocations. If it helps let me know so I can write an answer.
Comment: Yes for configuredList it is coming the first data values like pics. and for conLocations after adding single item it is showing 2nd data values. Yes i was rendering two array differently.
Answer: UPDATE #1:
mergeLocationData(){
  let mergedList = [];
  // you either have to setup initial state for conLocations in your reducer to `undefined` or to `null`.
  if(this.props.conLocations !== undefined && this.state.configuredList !== null){
    const { configuredList } = this.state;
    const { conLocations } = this.props;
    mergedList = configuredList;

    this.props.conLocations.forEach(location => {
      const locationAdded = mergedList.find(_location => _location.mruCode === location.mruCode);
      if(!locationAdded){
        mergedList.push(location)
      }
    });
  }
    // instead of setting state, return the mergedList
    return mergedList; //[ always an array of elements ]
}

And then, at the render method: instead of getting the list from the state, we just invoke the function.

  {
    this.mergeLocationData().map((locc,index)=> (

          {locc.mruCode} - {_labels[locc.division]} - {locc.country}

          {this.removeConfigLocation(index)}}
            className="deleteIconStyle"
            src="img/delete_large_active.png" />

    )
  }

There is nothing wrong with the code, I suppose it's correctly working, but, it's the logic that is not right, you are rendering both of the arrays in your render, you are not using the function getLocationData anyware in your component, eventhough, concat won't solve the problem.
You can do the following steps to fix the logic.
- Fix the logic of getLocationData:
mergeLocationData(){
  // you either have to setup initial state for conLocations in your reducer to `undefined` or to `null`.
  if(this.props.conLocations !== undefined && this.state.configuredList !== null){
    const { configuredList } = this.state;
    const { conLocations } = this.props;
    let mergedList = configuredList;

    this.props.conLocations.forEach(location => {
      const locationAdded = mergedList.find(_location => _location.mruCode === location.mruCode);
    });

    this.setState({
        mergedList
    });
  }
}

Use the function as a callback to your fetch request, supposibly in  componentDidMount after loading the data correctly.
Render the new Array of mergedList which should be in your state by now, and don't forget to add mergedList: [] to your state.
Basically you need to replace the two maps that render location elements in your render with that.

      {
        this.state.mergedList.map((locc,index)=> (

              {locc.mruCode} - {_labels[locc.division]} - {locc.country}

              {this.removeConfigLocation(index)}}
                className="deleteIconStyle"
                src="img/delete_large_active.png" />

        )
      }

Comment: Thank you very much for your response. Yes that is the way i was searching. But, one question while adding location into that . locationAdded?? how to use that ? I am just confused on this part
Comment: if you mean while merging it, this is the bit where we check for the existance of an object and depending on it we push, or not `mergedList.find(_location => _location.mruCode === location.mruCode);`
Comment: I have edited my question in where i am using that getLocationData. I am saving the  data into locationData and calling that method into that Jobs Component. It is saving properly. Now how to do that in your mergedLocationData () part. Will you please add this part too in your code? so i can edit and test that
Comment: Thanks a lot. It is the way i understood after so many trials. Just show me how to configure the save locationData part in mergedLocationData() as per your answer
Comment: If you save the data in the store, then invoke the merge function again, things should be ok.
Comment: what if i will  create one method like yours and send mergedList to getLocationData and calling it to job component like i did previously. I think it will work. Because problem was two different list rendering. What will you say? It will work
Comment: I will work, and I will update the answer to match with the following, If you are handling the data save in another component and it's hard to invoke the function after the save event, the updated answer will still do the job, as when you update the store, the component will re-render, and then we evaluate the new mergedList in the `render()` method without the usage of `setState()`, and that is the cheapest solution, another solution is to make mergedList in your redux store with the same functionality..
Comment: I have updated my code as you replied. Now, mergedlist is showing nothing.
Comment: I have updated the code, but, I can't find a scenario that it will not render elements unless this: `this.props.conLocations !== undefined && this.state.configuredList !== null` returns false.


Circle touching 2 sides of a triangle

Question: The centre of a circle inside a triangle is at a distance of 625 units from each of the vertices of the triangle. If the diameter of the circle is 350 units and the circle is touching only two sides of the triangle, find the area of the triangle.
I am not able to solve this question. Help.
Comment: You should find that the triangle is isosceles, and that you can find the two equal sides. The circle also makes it easy to calculate the trigonometric ratios for the angle between the sides - and you can calculate the area from the two sides and the ratios for the angle between them.
Comment: Where are you getting stuck?
Comment: @daOnlyBG I just know that the circumradius is 625 units. I have been able to find the length of the tangent from the common vertex of the two sides touching the circle. That's about it.
Comment: @MarkBennet Yupp. Got it. Thanks!
Answer:
Here is how you could construct this situation: You could start by drawing the circle, with radius $\frac{350}2=175$ around any point. Then draw a larger circle with radius $625$ around that same center. All three corners must lie on the larger circles, and two edges must be tangents to the smaller one. So pick an arbitrary point $A$ on the larger circle, draw tangents to the smaller circle, and the points where these tangents intersect the larger circle are the points $B$ and $C$.
But I take it that you want to know the number exactly, not measure some construction. So think about the image you obtained. For reasons of symmetry, $AE=EC$. Since you know $AF$ and you know $FE$ and since $\angle AEF=90°$, you can compute $AE$ and therefore $AC$.
$$AC=2\sqrt{625^2-175^2}$$
Furthermore, if you define $\alpha=\angle FAE$ then you know $\sin\alpha=\frac{175}{625}=\frac7{25}$. From that you can deduce the vector from $A$ to $C$:
$$\overrightarrow{AC}=AC\begin{pmatrix}\cos\alpha\\\sin\alpha\end{pmatrix}
=\begin{pmatrix}AG\\GC\end{pmatrix}$$
From that you get the area of the triangle as
$$ 2\cdot\frac12\cdot AG\cdot GC = AC^2\sin\alpha\cos\alpha
= 4\left(625^2-175^2\right)\frac{175}{625}\sqrt{1-\left(\frac{175}{625}\right)^2}
= 387072 $$
Comment: The *diameter* is $350$, not the radius.

Circle touching 2 sides of a triangle


Difference between multi-factor ANOVA and Cox proportional hazard model?

Question: I am wondering what is the difference between multi-factor ANOVA and Cox proportional hazard model? As I understood both of them test the significance of some independent factors on a dependent factor...
Comment: I think you pointed out the only common thing between the two methods. Thus said (sorry for being sarcastic), it is like asking "what is the difference between an elephant and a cat. As I understood, they are both animals."
Answer: At a high level: ANOVA is a regression model that tests if the mean value of a variable varies by categorical factors. A Cox PH model is a type of survival analysis model for the hazard function, which you can think of as the probability of having a predefined event within a small window of a given time.
Both of these are often used in medical settings and 2 relevant applications would be testing the effect of a drug on blood pressure via ANOVA and modeling the time until a patient has a heart attack via Cox PH.


Censoring in a discrete-time hazard model of time-to-drop-out of a clinical trial

Question: I am conducting a discrete-time hazard model where the outcome being analysed is time to drop out of treatment during a 12-week clinical trial examining the effect of an agonist drug on days of illicit drug use. I am examining the influence of nine factors on whether and when participants drop out of treatment. The outcome is a discrete numeric variable, weeks in the trial (min = 1, max = 12).
Based on chapter 12 of Applied Longitudinal Data Analysis: Modeling Change and Event Occurrence by Singer and Willett I am conducting a discrete-time hazard model with complementary Log-Log link function. It is essentially a logistic regression model with a cLogLog link function instead of the usual logit; chosen because the outcome is discrete for measurement reasons not actually discrete (time participants actually dropped out could be any day between week markers, but we only have info for the week they dropped out).
Based on what I read in the book I created a person-period dataset that looks like this (have left out all the columns of predictors save 1 as they wouldn't fit on the display)

You can see participant 5 dropped out three weeks into the trial, and hence has three rows, with the event occurring on the third, whereas participant 6 stayed the entire 12 weeks and hence has twelve rows with no event.
I ran the model in R with syntax that looks like this. For non-R users (along with my apologies for parochialism) the model has reference-level coding and includes all 12 columns for each discrete time period as well as the nine predictors (the -1 is R syntax for 'remove the intercept`)
modLogLog <- glm(formula = event ~ D1 + D2 + D3 + D4 + D5 + D6 + D7 + D8 + D9 + D10 + D11 + D12 + gender + group + isi_tot + sf_pain + cpq_tot + qcq_tot + dass_tot + grams_per_day + durationRegUse_dec - 1,
                 family=binomial(link = "cloglog"),
                 data = treatDF_PP)

The output of the model looks like this

That was a lot of preamble I know. But my question relates to the coefficient for D12. For one it is tiny (1.82e-08 after reversing the complementary Log-Log transformation via 1-exp(-exp(foo))) and conspicuously non-significant (p=0.98), especially noticeable juxtaposed against the significant coefficients for the other time periods.
At first I was concerned that I had make some drastic mistake creating the person period dataset, but I checked and everything looked correct. But this morning at about 4am it came to me: the coefficient might be caused by all participants who stayed in treatment to week 12 being right-censored at week 12, which would effectively mean that, during the week 12 "window", the hazard of dropout is effectively zero (i.e. the dropout 'event' cannot occur at this time period, which means no 1's in the event column for anyone who has a 1 in the D12 column).
Which brings me to my two-part question
Was my 4am epiphany right? Is the out-of-place coefficient due to no events occurring during that time period?
and, more importantly
Should I remove the D12 column as a predictor from my model because no events can occur in that week?
Insights much appreciated
Answer: Your "epiphany" seems to be correct.
A large coefficient with an enormous standard error suggests that you are (close to) perfect separation, with combinations of predictors that (almost) perfectly define the outcomes. If your data are structured in a way that there can be no events during the last time period, then predictions for that last time period are trivial: no "events" as you define them. There is no reason to include that last time period in this situation.
The distinction here from usual discrete-time survival models is that the events you are modeling would be considered right censoring (loss to follow up) in other survival models. In those other models, unlike yours, there can be events during the last time period.
Comment: Thanks for confirming EdM. I struggle with the concept of right censoring in a clinical trial when the 'event' is dropping out of treatment. Because in one sense *everyone* drops out of treatment at the end of the trial (if, as in our case, the treatment ends when the trial finishes) but in another sense *no one* drops out of treatment at the end of the trial because they did not intentionally drop out of treatment in the same way that people who dropped out during the trial did; the trial simply ends and they can't get treatment any more even if they still want to.
Comment: The latter interpretation makes more sense to me - treating all the people still in the trial at the end (week 12) as right-censored rather than dropped out - and that is how I created the dataset, with the `D12` column containing zero events. But treating all people at study end as right-censored *still* causes the issue I ran into which is that *all* people remaining in the risk set are right-censored at that point (i.e. 0% hazard of dropout in that time window) which leads to those crazy coefficients.


Retain relative mouse position while resizing a JPanel in a JScrollPane

Question: I'm resizing a JPanel inside of a JScrollPane, and I want to make sure that the point on the JPanel where my mouse is currently located retains its position with respect to the JScrollPane after the resize (like Google maps does when you zoom in/out).
I find the mouse position on the JPanel, which lets me deal with the viewport being at various positions.  I multiply it by the zoom factor so I know where the point will be after scaling.  I then subtract the position of the mouse on the ScrollPane so that I know where the point was with respect to the viewable area.  I'm doing something wrong however, and I just can't see what.
Example Code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class Test
{
    public static void main(String[] in)
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Test();
            }
        });
    }

    public Test()
    {
        final JFrame frame = new JFrame();
        final ScalablePanel child = new ScalablePanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.add(child, BorderLayout.CENTER);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class ScalablePanel
extends JScrollPane
implements MouseWheelListener
{
    final double ZOOM_IN_FACTOR = 1.1;
    final double ZOOM_OUT_FACTOR = 0.9;
    final JPanel zoomPanel = new JPanel();

    public ScalablePanel()
    {
        final javax.swing.JLabel marker = new javax.swing.JLabel("Testing the mouse position on zoom");
        marker.setHorizontalAlignment(javax.swing.JLabel.CENTER);

        zoomPanel.setLayout(new BorderLayout());
        zoomPanel.add(marker,BorderLayout.CENTER);

        getViewport().setView(zoomPanel);
        setPreferredSize(new Dimension(300,300));
        addMouseWheelListener(this);
    }

    public void mouseWheelMoved(final MouseWheelEvent e)
    {
        if (e.isControlDown())
        {
            if (e.getWheelRotation() < 0)
                zoomIn(e);
            else
                zoomOut(e);
            e.consume();
        }
    }

    public void zoomIn(final MouseWheelEvent e)
    {
        // Get the mouse position with respect to the zoomPanel
        final Point pointOnZoomPanel = SwingUtilities.convertPoint(
                e.getComponent(), e.getPoint(), zoomPanel);

        // Resize panel
        final Dimension currSize = zoomPanel.getSize();
        zoomPanel.setPreferredSize(
                new Dimension(
                        (int)(currSize.width * ZOOM_IN_FACTOR),
                        (int)(currSize.height * ZOOM_IN_FACTOR) ));

        // Find out where our point on the zoom panel is now that we've resized it
        final Point newViewPos = new Point();
        newViewPos.x = (int)(ZOOM_IN_FACTOR * pointOnZoomPanel.x - e.getPoint().x);
        newViewPos.y = (int)(ZOOM_IN_FACTOR * pointOnZoomPanel.y - e.getPoint().y);
        // Move the viewport to the new position to keep the area our mouse was in the same spot
        getViewport().setViewPosition(newViewPos);

        zoomPanel.revalidate();
    }

    public void zoomOut(final MouseWheelEvent e)
    {
        // Get the mouse position with respect to the zoomPanel
        final Point pointOnZoomPanel = SwingUtilities.convertPoint(
                e.getComponent(), e.getPoint(), zoomPanel);

        // Resize panel
        final Dimension currSize = zoomPanel.getSize();
        zoomPanel.setPreferredSize(
                new Dimension(
                        (int)(currSize.width * ZOOM_OUT_FACTOR),
                        (int)(currSize.height * ZOOM_OUT_FACTOR) ));

        // Find out where our point on the zoom panel is now that we've resized it
        final Point newViewPos = new Point();
        newViewPos.x = (int)(ZOOM_OUT_FACTOR * pointOnZoomPanel.x - e.getPoint().x);
        newViewPos.y = (int)(ZOOM_OUT_FACTOR * pointOnZoomPanel.y - e.getPoint().y);
        // Move the viewport to the new position to keep the area our mouse was in the same spot
        getViewport().setViewPosition(newViewPos);

        zoomPanel.revalidate();
    }
}

Answer: Try instead finding the position of the mouse as a percentage of the current size, then applying that to the new size:
newViewPos.x = (int)((ZOOM_IN_FACTOR * currSize.width) * (e.getPoint().x/(double)currSize.width));

as an example. In this way, you are looking at the mouse position relative to the scroll pane, and preserving that relationship on the zoomPanel.


Delete row from 2D array python (IndexError)

Question: I got one 2-D array
data = [[1,2,3...], [4,5,6...], [7,8,9...], ...]
and another 1-D array which contains the MINIMUM value of each sub-array from above:
minima= [1, 4, 7, ....]. So consequently len(minima) = len(data).
Now i want to set a threshold value, say threshold = 7 and want to delete each sub-array of data with a minimum below this threshold. So I tried the following:
threshold = 7
for i in range(len(minima)):
    if minima[i] < threshold:
        data = np.delete(data, i, 1)

but this gives me an IndexError:
IndexError: index 225 is out of bounds for axis 1 with size 225
I guess it has sth to do with the axis and a loop is not the best approach but my expertise is very limited. Appreciate your help!
Comment: An (overly?) detailed explanation as to why 'delete` (even in a list) is dangerous in a loop: https://stackoverflow.com/questions/61013951/how-to-use-delete-to-delete-specific-array-in-numpy-when-iterate-it/61015621#61015621
Answer: The reason this will fail is because if you delete a row, then the number of rows declreases, but i will keep incrementing until the "old" number of rows.
But anyway, using a loop to each time delete one row is not very efficient. Numpy can boost efficiency by doing operations in bulk. By iterating, your algorithm will likely not be much faster than a simply Python program without using numpy.
You can just filter the array, with:
data2 = data[minima >= threshold]
Note that you do not need to calculate the row-wise minimum yourself, you can calculate this with:
data2 = data[data.min(axis=1) >= threshold]


Merge multiple google map polygons into one polygon, javascript


Khan Academy Towers of Hanoi recursion Step 3

Question: I need help on step three of solve Hanoi recursively and it says that all of my assertions do not pass and I have looked at other peoples answer and it is the same as mine. My code is Program.assertEqual(hanoi.isSolved("B"),true); that is what they say is wrong
Answer: Step 1:
var solveHanoi = function(numDisks, fromPeg, toPeg) {
if (numDisks===0){
return;
}
// recursive case:

};

You are meant to a case of 0 discs by writing the if statement in the function.
Step 2:
var solveHanoi = function(numDisks, fromPeg, toPeg) {
if (numDisks===0){
return;
}
// recursive case:
var sparePeg = hanoi.getSparePeg(fromPeg, toPeg);
solveHanoi(numDisks-1, fromPeg, sparePeg);
};

Now create a variable called 'sparePeg' then write in the function 'solveHanoi' 3 parameters like the code above.
Step 3:
var solveHanoi = function(numDisks, fromPeg, toPeg) {
if (numDisks===0){
return;
}
// recursive case:
var sparePeg = hanoi.getSparePeg(fromPeg, toPeg);
hanoi.moveDisk(fromPeg, toPeg);
solveHanoi(numDisks-1, fromPeg, sparePeg);
};

Now add the 'hanoi.moveDisk()' function with the parameters fromPeg and sparePeg.
Step 4 & 5:
var solveHanoi = function(numDisks, fromPeg, toPeg) {
if (numDisks===0){
return;
}
// recursive case:

else{
var sparePeg = hanoi.getSparePeg(fromPeg, toPeg);
solveHanoi(numDisks-1, fromPeg, sparePeg);
hanoi.moveDisk(fromPeg, toPeg);
solveHanoi(numDisks-1, sparePeg, toPeg);
}
};
solveHanoi(5, "A", "B");
Program.assertEqual(hanoi.isSolved("B"),true);

This is the easiest one. All you have to do is uncomment the last 2 lines of code.
Then you're finished!


Media Query width-based CSS not rendered after AJAX rewrites some content

Question: This page  http://www.erica2013.dreamhosters.com/ (built with Zurb Foundation Framework) at widths over 425 px has a row of books on a div with a bookshelf background image.
In phone or browser when width is under 425px the background is not used and inner divs become  rows.
CSS
#homeBookshelfRow {
    margin-top:50px;
    background:url(../img/homepage/hmpg-mini-shelf/hmpg-shelf.png) bottom center no-repeat;
    height:160px;
    padding:19px 0 0 11px;
    text-align:center;
}

#homeBookshelfHeadline {
    display:none;
}

.phoneBookGroup {
    margin:0;
    padding:0;
    display:inline;
}

#homeBookshelfRow .phoneBookGroup .homebook {
    padding-right:10px;
    cursor:pointer;
}

Width Based CSS
@media only screen and (max-width: 425px) {
    #homeBookshelfRow {
        background:none;
        height:auto;
        margin:0 0 20px 0;
    }

    #homeBookshelfHeadline {
        display:block;
        font-family: 'Open Sans Condensed', sans-serif;
        font-size:2.25em;
        color:#b11717;
        padding:0;
        margin:0;
    }

    .phoneBookGroup {
        display:block;
        margin-bottom:10px;
    }

}

HTML

    Bookshelf

It renders fine initially but the following AJAX calls change the big book image and the sidebar content.  When that happens in all tested browsers the width-based CSS is no longer rendered and the regular CSS is rendered.
Why is that happening?  How do I fix it?
$('.homebook').click(function() {
  var id = $(this).attr('rel');
  var urlname = $(this).attr('data-urlname');
  //console.log("Book id " + id);
  $('#bigHomeBook').attr( 'src' , '/bookshelf/hmpg-mini-shelf/large/'+id+'.jpg'  );
  $('#bigHomeBookLink').attr( 'href' , '/bookshelf/' + urlname );

  $.ajax({
      url: 'inc/home_book_ajax.php?bID=' + id,
      success: function(data) {
        if (data == 'bad') {

        } else {
            $('#rightSidebar').html( '' );
            $('#rightSidebar').addClass( 'reviewRed' );
            $('#rightSidebar').html( data );
        }
      }
    });
});

Answer: You would want max-device-width as the browser is changing the current width to match the content (leading to scrolling or scaling and no longer matching your media rule.)
Take a look at:
What is the difference between max-device-width and max-width for mobile web?
EDIT:
Here is a much better link on more options and iphone specific oddities:
http://www.quirksmode.org/blog/archives/2010/09/combining_meta.html
I also made a little detector to get at the actual numbers:
http://jsfiddle.net/JztA4/2/

sanity:

width:

device-width:

But my use of data uri's etc also will upset older browsers, so you would need to copy the style into a real css sheet or maybe style element(s).
I have no pressing need to create a fully dynamic site, so I wont be mapping out results, but if anyone does please consider updating the jsfiddle and/or this question.
Comment: Hmm using `@media only screen and (max-device-width: 816px) {` had effect on all devices of width-based CSS not ever rendering at all.
Comment: From the link you referenced "max-device-width refers to the viewport size of the device regardless of orientation, current scale or resizing. This will not change on a device so cannot be used to switch style sheets or CSS directives as the screen is rotated or resized."
Comment: I think if you follow up that quote it goes to iphones specifically, while android and ipads present the width based on current orientation. Looking from the javascript debugger I think you can examine screen for the device width/height and window.innerWidth for the width value. My sense is that the device values will remain constant while the non-device will fluctuate with contents, leading to your problem. But I think you would have to test on specific mobile browsers to see how they adapt to the larger content.
Comment: OK, I'm trying to get my head around it.  I tried checking `$('#homeBookshelfRow').width()` and also `$('body').width()` before and after the script runs and the widths are constant.
Comment: as lame as this may be I am using this script to get the css at the start and reapply at the end of the run... http://stackoverflow.com/questions/754607/can-jquery-get-all-css-styles-associated-with-an-element  and it's working great.
Comment: Interesting solution! That still implies to me that the width is changing based on the content. If you have chrome on a desktop, you can manually set the device width in the debugger overrrides, then watch the window.innerwidth, window.screen and document.width (I get 454px on your site with a 400 device-width..) Personally, I would probably figure out which value I like to indicate minimal devices, and then use it to set a class on the body during the initial load.
Answer: I had this problem as well - none of my @media CSS styles were being applied after any Ajax update.
For me, I'm using ASP.NET and Telerik controls, and the solution I found was to disable page head updates on Ajax requests:
www.telerik.com/help/sitefinity/developer-manual/radajax.net2-telerik.webcontrols.radajaxutils.radajaxcontrol-enablepageheadupdate.html
I hope this helps you or others find an appropriate solution for your technology.


How do the means of $X^2$ and $X$ compare?

Question: If $X$ has an exponential distribution with mean $\theta$, does $X^2$ have mean $\theta^2$?
If not, how would I find the variance of $X^2$?
I tried this:
$$V(X^2) = E[X^4] - E[X^2]^2$$
But I'm not sure how to factor the $\theta$ into the equation. The only way I can think is if $X^2$ has expected value of $\theta^2$.
I also tried:
$$V(X^2) = 4\theta^2V(X)$$
Any help is welcome, thanks.
Comment: Welcome! Math typesetting is implemented with Mathjax. http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Is this an exercise/study for some class?
Comment: The mean of $X^2$, namely $E[X^2]$, equals the square of the mean of $X$, namely $\left(E[X]\right)^2$ if and only if $X$ has variance $0$, meaning that for all practical purposes, $X$ is a constant and does not  vary at all.
Answer: You can directly calculate the mean of $X^2$,suppose your exponential distribution is $f(x;\lambda)=\lambda e^{-\lambda x}$.
$E(X^2)=\int_{0}^{\infty}x^2\lambda e^{-\lambda x}dx$ by integral by parts you can get $E(X^2)=\frac{2}{\lambda^2}=2\theta^2$.
By the same method you can calculate $E(X^4)$.
You also can calculate $E(X^2)$ and $E(X^4)$ by using moment generating function if you remember:
$E(X^m)=M^{(m)}(0)$, $M$ is the mgf and $(m)$ is the order of derivative.
The mgf of the exponential distribution is $\frac{\lambda}{\lambda-t}$
The first derivative (m=1) of the mgf in term of $t$ is $\frac{\lambda}{(\lambda-t)^2}$, set $t=0$, $E(X)=\frac{1}{\lambda}=\theta$
The second derivative (m=2) of the mgf in term of $t$ is $\frac{2\lambda}{(\lambda-t)^3}$, set $t=0$, $E(X^2)=\frac{2}{\lambda^2}=2\theta^2$.
You can continue to calculate others...
Answer: Re your title -- the mean of $X^2$ and the mean of $X$ aren't even in the same units. Presumably you mean to ask something more like how the mean of $X^2$ compared to the square of the mean of $X$.

If $X$
  has an exponential distribution with mean $θ$, does $X^2$ have mean $θ^2$?

(This question would be consistent with the above suggestion about a correction to the title)
The answer to this is obvious from the fact that the variance isn't zero: Given $E(X)=\theta$, if $E(X^2)=\theta^2$ then $\text{Var}(X) = E(X^2)-E(X)^2 = ...$
More generally, when $f$ is a convex function, then $E(f(X))\geq f(E(X))$ (see Jensen's inequality); equality only occurs when $f$ is linear or $\text{Var}(X)=0$.
For an exponential you can compute $E(X^k)$ quite easily, for example from the definition of expectation for a continuous pmf (the integral can readily be computed for integer $k$ - e.g. by integration by parts), though there are other approaches.


Continuous spectrum $\sigma_c(R)$ of the right-shift operator $R$ on $\ell^\infty$.

Question: Let $R$ be the right-shift operator on $\ell^\infty$, i.e.,
\begin{equation}
R(x_1,x_2,...)= (0,x_1,x_2,...).
\end{equation}
I know the following results from Functional
Analysis Proposition 14.11 on p. 316:
Proposition. Let $X$ be a Banach space, $T\in \mathcal{L}(X)$, and $T^\star$ is the adjoint of $T$. Then
(1) $\sigma(T^\star) =\sigma(T)$;
(2) $\sigma_r(T)\subset \sigma_p(T^\star) \subset \sigma_r(T)\cup \sigma_p(T)$;
(3) $\sigma_c(T^\star) \subset \sigma_c(T)$.
Clearly, $\sigma_p(R)=\varnothing$, and $R= A^\star$, where $A$ is the left-shift operator on $\ell^1$.
Since the spectral radius of $A$ is $r(A)=1$, $\sigma(A)\subset \{\lambda\in \mathbb{C}:|\lambda|\leq 1\}$. Note that if $|\lambda|<1$, then $\lambda\in \sigma_p(A)$ (an eigenvector is $(1,\lambda,\lambda^2,\lambda^3,...)\in \ell^1$). Moreover, if $|\lambda|=1$, then $\lambda\notin\sigma_p(A)$ (otherwise any eigenvector must form a geometric sequence with a common ratio of $\lambda$, which is not in $\ell^1$). Hence $\sigma_p(A)= \{\lambda\in \mathbb{C}:|\lambda|<1\}$. Since $\sigma(A)$ is closed, we have $\sigma(A)= \{\lambda\in \mathbb{C}:|\lambda|\leq 1\}$. Using the above
results, we obtain
\begin{equation}
\sigma(R)= \sigma(A)=\{\lambda\in \mathbb{C}:|\lambda|\leq 1\},
\end{equation}
and
\begin{equation}
\sigma_r(A) \subset \sigma_p(R)=\varnothing.
\end{equation}
Therefore, $\sigma_c(A)= \{\lambda\in \mathbb{C}: |\lambda|=1\}$. Also, using (3), we deduce
\begin{equation}
\sigma_c(R) \subset \sigma_c(A) =\{\lambda\in \mathbb{C}: |\lambda|=1\}.
\end{equation}
But I have no idea how to determine $\sigma_c(R)$ explicitly. Any ideas would be greatly appreciated.
Comment: I have found a solution below.
Answer: Today, I have found a solution from Spectral Theory step f) on p. 15--p.16:
In fact $\sigma_r(R) = \overline{B(0, 1)}$: because of the previous observations it suffices to show that
any $\lambda\in \mathbb{C}$ s.t. $|\lambda| = 1$ is also in $\sigma_r(R)$.
Let $\lambda$ be such a value. We start by computing
a formal inverse of $\lambda I− R$ : if $a \in \ell^\infty$ and if $b$ is another sequence with values in $\mathbb{C}$, the
equation $(\lambda I− R)(b) = a$ reads
\begin{equation}
\begin{cases}
  a_1=\lambda b_1,\\
  a_2= \lambda b_2- b_1,\\
  \ \ \ \ \cdots\\
  a_n= \lambda b_n -b_{n-1},\\
  \ \ \ \ \cdots
\end{cases} \quad \Longleftrightarrow  \quad
\begin{cases}
  b_1=\overline{\lambda} a_1,\\
  b_2= \overline{\lambda}(a_2 +b_1)  ,\\
  \ \ \ \ \cdots\\
  b_n= \overline{\lambda} (a_n+ b_{n-1})  ,\\
  \ \ \ \ \cdots
\end{cases}
\end{equation}
Hence this equation has the solution $b_n = \overline{\lambda} a_n + \overline{\lambda}^2 a_{n−1} + \cdots + \overline{\lambda}^n a_1$.
We can already
see that $\lambda I− R$ is not onto because, for
$a = a_{[\overline{\lambda}]} := \left(1, \overline{\lambda} , \overline{\lambda}^2,...\right) \in \ell^\infty$, the solution is
$b_n = n \overline{\lambda}^n$
and this sequence cannot be in $\ell^\infty$: thus $a_{[\overline{\lambda}]}\notin \text{Im} \left(\lambda I− R\right)$.
But we   need a stronger result, i.e. that $\text{Im} \left(\lambda I− R\right)$ is not dense in $\ell^\infty$. For
that purpose we show that $B\left(a_{[\overline{\lambda}]}, 1/2\right) \cap  \text{Im} \left(\lambda I− R\right) =\varnothing$
in $\ell^\infty$. Let $a \in B\left(a_{[\overline{\lambda}]}, 1/2\right)$, we
can write $a = a_{[\overline{\lambda}]} + \beta$, where $\|\beta\|_\infty < 1/2$. The solution in the space of complex valued
series of the equation
\begin{equation}
(\lambda I− R)b = a = a_{[\overline{\lambda}]} + \beta
\end{equation}
is $b = (b_1, b_2, b_3, ... )$, with:
\begin{equation}
 b_n = n\overline{\lambda}^n  +\sum_{j=1}^{n} \overline{\lambda}^{n+1-j} \beta_j,
\end{equation}
which implies that:
\begin{equation}
\left| b_n  - n \overline{\lambda}^n\right| = \left| \sum_{j=1}^{n}\overline{\lambda}^{n+1-j} \beta_j \right|\leq \sum_{j=1}^{n} |\beta_j|<\frac{n}2.
\end{equation}
Using the triangle inequality $n = \left|n\overline{\lambda}^n\right| \leq \left|b_n − n\overline{\lambda}^n\right| + |b_n|$, we deduce that
\begin{equation}
|b_n| \geq n − \left|b_n − n\overline{\lambda}^n \right| > n −\frac{n}2 = \frac{n}2. \end{equation}
Thus $b$ is not in $\ell^\infty$.
Answer: You can show that $\sigma_c(R)=\sigma(R)\backslash(\sigma_p(R)\cup \Gamma(R))$ where $\Gamma(R)=\{\lambda\in \mathbb{C}:(R-\lambda)$ doesn't have dense range$\}$. Furthermore, you have one more relation such that $\sigma_p(T^*)=\Gamma(T)^*:=\{\overline{z}:z\in \Gamma(T)\}$ for any $T:X\rightarrow Y$, hence, $\Gamma(R)^*=\sigma_p(A)=\{z\in\mathbb{C}:|z|< 1\}$. This clearly gives you that $\Gamma(R)=\{z\in\mathbb{C}:|z|< 1\}$.
Again, you already know that $\sigma_p(R)=\emptyset$. Hence $\sigma_c(R)=\{z\in\mathbb{C}:|z|= 1\}$.
Remark:

The first identity I have used can be derived from the proposition "$T-\lambda$ is invertible $\Leftrightarrow$ $T-\lambda$ is bounded below and has dense range".


Obter valores através dos parâmetros do método get

Question: Tenho uma action que manda por parâmetros o codCliente:
//master/CadastrarEndereco?codigoCliente=1011

Como faço para obter esse esse valor codigoClienteem minha controller para que eu possa persistir o valor no BD?
Answer: No seu método CadastrarEndereco você pode declarar o parâmetro codigoCliente da seguinte forma e usá-lo.
public ActionResult CadastrarEndereco(int codigoCliente){
    // codigoCliente preenchido aqui dentro
}

Você também pode acessar o objeto Request para obter os parâmetros enviados:
var codigoCliente = Request.QueryString["codigoCliente"];


Call a WCF service protected by ACS, which uses ADFS as IDP

Question: Following this post I have created a WCF client which:

Uses ADFS to authenticate users against AD.
Provides a SAML2 ticket to the caller.
Uses the supplied SAML2 ticket to call the WCF Service.

This is working great, however the next part of my problem is to extend this to use Azure ACS.
I added the RP to ACS, and changed the STS reference to point to ACS using Add STS Reference in Visual studio.
I have extended the Token.GetToken method, supplying the token into the following method:
public static SecurityToken GetToken(SecurityToken adfsToken, string appliesTo, string idpEndpointAddress, out RequestSecurityTokenResponse rsts)
{
    WS2007HttpBinding binding = new WS2007HttpBinding();
    binding.Security.Message.EstablishSecurityContext = false;
    binding.Security.Mode = SecurityMode.TransportWithMessageCredential;

    WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(binding, new EndpointAddress(idpEndpointAddress));
    trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
    trustChannelFactory.ConfigureChannelFactory();

    // Create issuance issuance and get security token
    RequestSecurityToken requestToken = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue);
    requestToken.AppliesTo = new EndpointAddress(appliesTo);
    WSTrustChannel tokenClient = (WSTrustChannel)trustChannelFactory.CreateChannelWithIssuedToken(adfsToken);
    SecurityToken token = tokenClient.Issue(requestToken, out rsts);
    return token;
}

To the following endpoint:
https://test.accesscontrol.windows.net/v2/wstrust/13/issuedtoken-symmetric

But I get the following exception:

Secure channel cannot be opened because security negotiation with the
  remote endpoint has failed. This may be due to absent or incorrectly
  specified EndpointIdentity in the EndpointAddress used to create the
  channel. Please verify the EndpointIdentity specified or implied by
  the EndpointAddress correctly identifies the remote endpoint.

With an inner exception of:

ACS10001: An error occurred while processing the SOAP header.

What do I need to configure in ACS to get this working with the token supplied by ADFS?
Do I need to use the token supplied by ACS, or can I use the one supplied by ADFS in the service? (It appears to be working..)
Answer: Take a look at the linked ACS sample, which seems to be doing exactly what you're asking.
Comment: Thanks Oren - I will have a look at that example.


Listar diretórios e subdiretórios

Question: Eu tenho um componente TreeView, e uma estrutura no banco que ja tem na tabela diretórios os subdiretórios.
tem um campo chamado diretorio_parent_guid, se ele for nulo é porque é raiz, se não, é algum Id de outro diretorio.
Então eu tenho a seguinte estrutura:
Método que retorna diretorios: esperando um parametro que vai listar somente os diretorios com parent guid igual a string passada:
internal List<Diretorio> GetSubDiretorio(String termo)
{
    using (var ctx = new TESTEntities())
    {
        var diretorios = (
            from dir in ctx.DIRETORIO
            where dir.DIRETORIO_PARENT_GUID == termo
            select new Diretorio()
            {
                DIRETORIO_GUID = dir.DIRETORIO_GUID,
                XDIRETORIO = dir.XDIRETORIO,
                REFERENCIA = dir.REFERENCIA
            }
        ).ToList();
        return diretorios;
    }
}

Preenchimento do treeview que eu tentei:
public void CriarTreeView()
{
    var raiz = DiretorioController.GetInstance().GetSubDiretorio("");
    foreach (var diretorio in raiz )
    {
        node = new TreeNode(diretorio.XDIRETORIO);
        node.ImageUrl = "~/asstes/img/directory.png";
        TreeView1.Nodes.Add(node);

        foreach (var subDiretorio in DiretorioController.GetInstance().GetSubDiretorio())
        {
              TreeNode nodeSub = new TreeNode(subDiretorio.XDIRETORIO);
              nodeSub.ImageUrl = "~/asstes/img/directory.png";
              node.ChildNodes.Add(nodeSub);
        }
    }
}

Dessa forma esta funcionando diretorios e subdiretorios, porem fica manual, se eu crio um diretorio dentro de um subdiretorio ele não lista, não consegui aplicar a lógica correta ainda.
Como ficaria para listagem dos subdiretorios corretamente?
Answer: Para percorrer a arvore até as folhas, você precisa utilizar de recursão:
public void CriarTreeView()
{
    var diretorios = DiretorioController.GetInstance().GetSubDiretorio("");
    foreach (var diretorio in diretorios)
    {
        node = new TreeNode(diretorio.XDIRETORIO);
        node.ImageUrl = "~/asstes/img/directory.png";
        TreeView1.Nodes.Add(node);
        this.CriarTreeView(diretorio, node)
    }
}

public void CriarTreeView(Diretorio diretorio, TreeNode node)
{
    var subDiretorios = DiretorioController.GetInstance().GetSubDiretorio(diretorio.DIRETORIO_GUID);
    foreach (var subDiretorio in subDiretorios)
    {
        TreeNode subNode = new TreeNode(subDiretorio.XDIRETORIO);
        subNode.ImageUrl = "~/asstes/img/directory.png";
        node.ChildNodes.Add(subNode);
        this.CriarTreeView(subDiretorio, subNode)
    }
}

Comment: Dessa forma esta criando o terceiro diretorio, porem se eu seleciono o primeiro novamente, ele cria abaixo do segundo sempre.
Comment: Então agora os eu problema é outro, considere fazer uma nova pergunta.
Comment: Deu certo, valeu

Listar diretórios e subdiretórios


Interpreting regression coefficients when dependent variable is percentage

Question: There is a similar question posted but this is not what I am looking for: Interpreting coefficients when dependent variable is a fraction/proportion?
I was reading a paper that ran a difference-in-differences regression and the coefficient value was -0.036. The dependent variable is vote shares and none of the variables were logged. In this case, is the coefficient just a percentage? So the impact of X on Y is a decrease of 3.6% of vote shares?
In addition, for simple OLS regressions, are coefficients usually percentages? Sometimes people say percentages and sometimes percentage points.. and this has been giving me a headache.. Can anyone help me clarify please?
Answer: Talking about percents always causes confusion. For instance, if the starting value of $10\%$ undergoes an increase of $10\%$, there are legitimate claims of saying that the ending value (after the increase) is $11\%$ and $20\%$. For the latter, I would prefer to describe it as an increase of "10 percentage points," but this is far from a universal practice.
A related question here on Cross Validated
With that out of the way, if the model is linear, the it is just a matter of taking partial derivatives and interpreting them as usual in calculus. If the derivative is $-0.0036$, this means that you expect a value $0.0036$ lower than it would have been for a predictor value one unit lower (the usual interpretation of a linear regression coefficient). In other words, this would be a decrease of 3.6 percentage points, to use my terminology (not to claim that I invented the terminology, but I do use it).
Don't overthink it. The regression coefficients are telling you exactly what they always tell you.
(A drawback of this kind of model, however, is that it can result in predicted probabilities outside of $[0,1]$, but it is on the author to defend the decision to allow for this. Your interpretation of the coefficients does not depend on this.)
Comment: Thank you for your comment! One other question I have is, if you look at this post (https://stats.stackexchange.com/questions/549830/interpreting-coefficients-when-dependent-variable-is-a-fraction-proportion) the answer says that if a dependent variable is logged transform,  then b is the % change in y when x changes by 1 unit. However, isn't that incorrect? I thought that we have to exponentiate the coefficient and subtract 1 and multiply by 100 to get the percentage..
Comment: its approximately correct (for small coefficients). if we define $z$ as your log transformed value, then your proportion change is  $\exp(z + b)/\exp(z) -1=\exp(b) -1\sim b$ by Taylor expansion of exponential.
Comment: @seanv507 Thanks for your comment! But I meant the raw b value. So if the beta value is 0.36, then you're saying that as long as the coefficient is small enough, I can interpret it as if x changes by 1 unit y changes by 0.36%?
Comment: @seanv507 Also, by looking at exp(+)/exp()−1=exp()−1∼. it seems like you are talking about if the z value is small enough rather than b? which is the coefficient. (My math is rusty.. so sorry if I'm making dumb questions.. but really appreciate any help!)
Comment: y changes by 36% (not 0.36%)
Comment: no the approximation is the claim that exp(b) is approximately 1+b, which depends on b being small


Program adds two large integers using arrays in C++. It works for most numbers but fails in a certain case and I cannot pinpoint why

Question: The program uses an array to add large numbers. It works for the most part but fails if 56789101112 and 12345678910 are input. For some reason if this is input the carry doesn't get added to the next array element it just is output by itself with the sum next. For all other intents and purposes the carry works. For this example I have to use arrays to calculate the large numbers nothing else. Here is the code.
#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <iterator>
#include <stdlib.h>

using namespace std;

const int DIGITS = 20;

void readNum(int list[], int& length, string input1);
void reverseArray(int arr[], int start, int end);
void sumNum(int list1[], int numOfElementsList1,
    int list2[], int numOfElementsList2);

int main()
{
    // Write your main here
    string input1;
    string input2;
    int list[DIGITS];
    int list2[DIGITS];
    int input1Length;
    int input2Length;
    cout << "Please enter your 1st number: " << endl;
    cin >> input1;
    cout << "Please enter your 2nd number: " << endl;
    cin >> input2;
    input1Length = input1.length();
    input2Length = input2.length();
    readNum(list, input1Length, input1);
    readNum(list2, input2Length, input2);
    reverseArray(list, 0, input1Length);
    reverseArray(list2, 0, input2Length);
    sumNum(list, input1Length, list2, input2Length);

}

void readNum(int list[], int& length, string input1)
{

    int array[DIGITS];
    for (int i = 0; i < length; i++)
    {
        array[i] = input1[i] - '0';
        list[i] = array[i];
        for (int i = length; i <= DIGITS - 1; i++)
        {
            list[i] = 0;
        }
    }

}
void reverseArray(int arr[], int start, int length)
{
    int end;
    end = length - 1;
    while (start < end)
    {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}
void sumNum(int list1[], int numOfElementsList1,
    int list2[], int numOfElementsList2)
{

    int array2[20];
    int sum = 0;
    int carry = 0;

    for (int i = 0; i <= DIGITS - 1; i++)
    {

        sum = (list1[i] + list2[i]);

        if (sum >= 10)
        {

            array2[i] = (sum  + carry) % 10;
            carry = 1;
        }
        else
        {
            array2[i] = sum + carry;
            carry = 0;
        }

    }
    reverseArray(array2, 0, DIGITS);
    int flag = 1;
    for (int i = 0; i < DIGITS; i++)
    {
        if (flag == 1 && array2[i] != 0)
            flag = 0;
        if (flag != 1)
        {
            cout << array2[i];
        }
    }
}

Comment: Figuring out why is what a debugger is for. (However, what if `sum==9` and `carry` is `1`?)
Comment: Ok yeah i stepped through I see what is happening. If it is 9 and has a carry of 1 it overflows like you were saying. Now I just need to figure out how to fix that.
Comment: `sum + carry` can this overflow?
Comment: The program is working it just it not outputting the correct answer for those two inputs. I cannot figure out why.
Comment: Side note: Using a raw array of `int` plus a size variable is a very C style. Some `std::vector` could make the code simpler. (Remember to pass by reference to functions which want to modify a vector.)
Comment: Sum + carry can't overflow.
Comment: I have to use an array.
Comment: You should use `std::array` in C++.
Comment: You can reduce your example to inputs `11` and `789`. The correct result is `800` but the actual result is `7100`.
Comment: Ok. I got it fixed thanks for the help.
Answer: The if condition
if (sum >= 10)

only depends on sum. You have to check sum + carry. You don't even need the if condition. You can replace the block
sum = (list1[i] + list2[i]);

if (sum >= 10)
{
    array2[i] = (sum  + carry) % 10;
    carry = 1;
}
else
{
    array2[i] = sum + carry;
    carry = 0;
}

with
sum = list1[i] + list2[i] + carry;

array2[i] = sum % 10;
carry = sum / 10;


How to convert wiki markup to RTF?

Question: I'd like to create some formatted text in a .net RichTextBox control. It seems like a lot of hassle to use the existing mechanism for formatting, e.g. selection etc.
Some kind of markup would be much easier. I.e. just like markup works in this site. E.g.
<code>Some **bold** text.
</code>
gives you "Some bold text".
Does anyone:

know if anything like this exists,
know of any C# code that can be modified to do this,
or have any other suggestions?
Answer: If read this article http://www.codeproject.com/KB/HTML/XHTML2RTF.aspx it should be quite easy to create your own Wiki2RTF converter class, or find a Wiki2Html and combine those two :-) !

How to convert wiki markup to RTF?


How to style the menu button in BotFramework?

Question: I'm trying to add menu buttons exactly as shown in this page,

(source: botframework.com)
I tried using HeroCard as below
<code> var msg = new builder.Message(session)
            .textFormat(builder.TextFormat.xml)
            .attachments([
                new builder.HeroCard(session)
                    .title("Main Menu")
                    .subtitle("How can we assist you today?")
                    .text("Please click on a button.")
                    .buttons([
                                builder.CardAction.dialogAction(session,"flight",'','Book a Flight'),
                                builder.CardAction.dialogAction(session,"hotel",'','Book a Hotel'),
                                builder.CardAction.dialogAction(session,"car",'','Book a Car')
                            ])
            ]);
</code>
I know above is not enough, trying to figure what needs to be done to get the buttons displayed nicely as in the BOT Framework overview page.
Here's how the above code would display.

Any assistance would be very much appreciated! :)
Answer: How the buttons are being rendered will depend on the channel where you are using your bot. You cannot change the buttons style with the exception of the WebChat channel, that is open source and you might be able to tweak the stylesheets.
In your image, you are using the emulator, and that's the way button looks like there.
Check the Channel Inspector to get an idea about how each of channels will render each of the supported features.
Comment: Thanks Ezequiel for all the responses. Channel Inspector will be very useful.
Comment: Forgot to mention, I'm planning to use the BOT in Teams channel. So an alternate approach I'm considering is to get the buttons displayed in a single row. Is that possible? What other attachment should I use other than HeroCard to get the buttons displayed in a row? In my sample above, 'Book a Car' button jumped to the second row.
Comment: I believe that in Teams buttons will be displayed in separate rows. Take a look to the [Channel Inspector](https://docs.botframework.com/en-us/channel-inspector/channels/Teams?f=HeroCard&e=example1) to understand more about how each channels render the different features
Comment: Glad to hear it helped. Please mark the question as answered
Comment: For Teams | Buttons, it's displaying the buttons nicely in the Inspector. Will the rendering in Teams desktop App be any different? (I still need to try that part ..)
Comment: I'm not sure; I leave that part to you :)
Comment: I just tried it from Teams desktop App and it's displaying the buttons nicely in a single row. :) I had to simplify the button labels to squeeze in few more buttons in a row. I've the screenshot ready to share it here, but I don't see an option to upload it from within the comments.


How to modify Presicion and recall of GLM (Logit) in R?

Question: I fit a logistic regression model with an unbalanced population in R.
The problem that I am getting is I have 0.4 for precision and 0.0018 for recall, so I want to modify the threshold in order to get close both indicators (precision and recall)
Do you have any function in R to modify the cutoff? I have seen some work arounds in Python, but the code that I need is in R.
Comment: Questions that are only about software (e.g. error messages, code or packages, etc.)
are generally off topic here. If you have a substantive machine learning or
statistical question, please edit to clarify.
Comment: Yes, my question is that   "How do I round a value in [0,1] according to a given cut-off value x∈[0,1] so that anything less than x returns 0 and anything greater than x returns 1"?  I really need that!, THanks
Comment: The [docs](https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/predict.glm) suggest that predictions give probabilities.  As such, this question actually has nothing to do with `glm`.  I think you may want to ask a question "How do I round a value in [0,1] according to a given cut-off value $x \in [0,1]$ so that anything less than $x$ returns 0 and anything greater than $x$ returns 1?"  If you need to do that in `R`, it probably belongs on StackOverflow.
Answer: Don't use thresholds at all.
Don't use precision and recall. Every criticism that applies to accuracy applies equally to precision and recall.
Unbalanced datasets are not a problem if you use appropriate quality measures (i.e., not accuracy, precision or recall).
If you still feel you need to work with thresholds, simply use predicted probabilities with predict(..., type="response") (see ?predict.glm) and compare them with your threshold.
Comment: "if you use appropriate quality measures" Would you suggest anything in particular?  Although analysis via a single cut off point may be quite narrow, the set of confusion matrices at every cut off contains a lot of information about the performance of a classifier.  For binary classification problems, accuracy, precision and recall are essentially the confusion matrix.
Comment: @Scott: proper scoring rules are the tool of choice, see the first two links. Per both links, I do not believe confusion matrices are useful. They are improper and misleading, and their very simplicity makes them doubly dangerous.
Comment: Neither of those links seem to suggest anything.  They merely repeat your claim that confusion matrices are not useful.
Comment: Indeed, the answer to this question "What are the consequences of deciding to treat a new observation as class 1 vs. 0? Do I then send out a cheap marketing mail to all 1s? Or do I apply an invasive cancer treatment with big side effects?" goes hand-in-hand with the contents of the confusion matrix since it tells you how many people without cancer are getting your invasive cancer treatment.
Comment: Do you have some example code of:

"If you still feel you need to work with thresholds, simply use predicted probabilities with predict(..., type="response") (see ?predict.glm) and compare them to your threshold"

Thanks a lot in advance
Comment: @Scott: have you looked at [my answer](https://stats.stackexchange.com/a/312787/1352) at the second thread I linked? There are multiple paragraphs on scoring rules as alternatives to accuracy, and as I write, the exact same criticisms that apply to accuracy apply equally to precision and recall, and therefore also to the confusion matrix. Also, [the first link](https://stats.stackexchange.com/a/312124/1352) explicitly addresses that very often we will not have *two* possible actions (treating a case as "positive" vs. "negative"), but more (collect more data if we are unsure).
Comment: @josecorti: `predict.glm(..., type="response")` will give you probabilistic predictions, i.e., numbers between zero and one. You can compare them to a `threshold` value using straightforward comparison operators like `<` and work with index vectors in R. If you have questions about this, then it might be best to ask a separate question [at StackOverflow in the R tag](https://stackoverflow.com/questions/tagged/r), since that is not about statistics any more. Feel free to link to that new question here, then I'll try to take a look.
Comment: @Scott: on the shortcomings of the confusion matrix, [here is another example](https://stats.stackexchange.com/a/405049/1352). Yes, I do write about this often, I'll admit it's a bugbear of mine.
Comment: Many of your criticisms are fair.  However, I think that it is often necessary to use the confusion matrix precisely because of the reasons that your answers say not to.  Very frequently, we make a decision based on the outcome of a classifier, and the intermediate probability calculation is irrelevant to how the model ends up being used.  Arguably, people should take the pseudo-probabilistic output into account somehow, but ML systems being what they are these days, that rarely happens: the machine makes a decision totally independently of any human input.
Comment: It's also worth noting that many of the criticisms of accuracy are of using accuracy *only*.  The same apply to using recall and precision *only*, but go away when one considers the entire confusion matrix.  Not all criticisms, but one can never address every possible criticism of anything, I suppose.


How the sequence $S_n=\frac{1}{2}({S_{n-1}+S_{n-2}}), \forall n>2,$ converge?

Question:
If $S_n=\frac{1}{2}({S_{n-1}+S_{n-2}}), \forall n>2,$ then show that ${S_n}$ converges.

I have proved that sequence converges and I understood all the steps except the last one. First, I assumed that the $S_1<S_2$ which leads to a sequence such that it has two subsequences. One of even order and another of odd order. The odd ordered subsequence is increasing and bounded above by $S_2$ and hence it is convergent and similarly the even ordered subsequence also converges. Also, both subsequence converge to the same limit. We can check this by simple substitution of two different expression in the above sequence and then both expression will turn out to be same.
I understood all the steps of the book but then the following expression,I couldn't understand:
$S_{k}+ \frac {1}{2}S_{k-1}=\frac{1}{2}(S_1+2S_2).$
I couldn't not understand,how the book came to the above mentioned step. Any help or hint would be great. Thanks in advance
Comment: $$S_n = \frac{1}{2}(S_{n - 1} + S_{n - 2}) \Rightarrow S_n + \frac{1}{2}S_{n - 1} = S_{n - 1} + \frac{1}{2}S_{n - 2},$$so $\{S_n + \frac{1}{2}S_{n - 1}\}$ is a constant sequence.
Comment: The formula for $S_n$ can be readily derived since there's a linear recurrence relation, and the convergence of $\{S_n\}$ follows.
Comment: Thanks Alex, I am not able to understand how the  relationship in the last expression has been established. Would be great, if you can Help.
Comment: I understood that now. Thank you so much Alex.
Comment: $S_n = S_1+ \frac{2 }3(S_2-S_1)\left(1-\frac{(-1)^{n-1}}{2^{n-1}}\right) \to \color{red}{S_1+ \frac{2 }3(S_2-S_1)}$
Comment: Another way is to directly use the recursive relation, and induction on $n\geq 1,$ to prove that  $|S_n-S_{n-1}|=2^{1-n}|S_1-S_0|$ for all $n\geq 1.$  Then  for $0\leq m <n$ we have $|S_m-S_n|=|\sum_{j=1}^{n-m}S_{m+j-1}-S_{m+i}|$ $\leq \sum_{j=1}^{n-m}|S_{m+j-1}-S_{m+j}|=$ $=\sum_{j=1}^{n-m}(2^{1-m-j})<2^{1-m},$ implying that the equence $(S_n)_n$ satisfies the Cauchy Criterion.
Comment: The last 2 expressions in my comment above should have been multiplied by $|S_1-S_0|$.
Answer: From the recurrence equation,
$$S_k+\frac12 S_{k-1}=\frac12(S_{k-1}+S_{k-2})+\frac12 S_{k-1}=S_{k-1}+\frac12S_{k-2},$$ and by induction,
$$S_k+\frac12 S_{k-1}=S_2+\frac12S_1.$$
Answer:
Answer: $$S_n = S_1+ \frac{2 }3(S_2-S_1)\left(1-\frac{(-1)^{n-1}}{2^{n-1}}\right) \to \color{red}{S_1+ \frac{2 }3(S_2-S_1)}$$
see below

Enforcing $X_n=S_n-S_{n-1}$ then, $$S_n=\frac{1}{2}({S_{n-1}+S_{n-2}}), \forall n>2\Longleftrightarrow S_n -S_{n-1}=-\frac{1}{2}({S_{n-1}-S_{n-2}}), \forall n>2,$$
that is
$$X_n=-\frac{1}{2}X_{n-1}, \forall n>2,$$
which is geometric sequence with ratio $-\frac12$. Hence
$$X_n =\frac{(-1)^{n-2}}{2^{n-2}}X_{2}~~~or ~~~S_n-S_{n-1}= \frac{(-1)^{n-2}}{2^{n-2}}X_{2}$$
Finally by telescopic sequence like here we get
$$S_n -S_1= \sum_{k=2}^{n}(S_k -S_{k-1}) = X_{2}\sum_{k=2}^{n} \frac{(-1)^{k-2}}{2^{k-2}} =\frac{2X_{2}}3\left(1-\frac{(-1)^{n-1}}{2^{n-1}}\right)$$