When She Loved Me: Decorative Chords alternatives on (Add2)

Question: This is the middle part of "When She Loved Me," in Toy Story 2 sung by Sarah McLachlan.
P.S. See this for example for the piano.
The chord progression goes twice as:
Em7b5 -> A/C# - > Dm -> F(add2)/C -> Bb(add2).
My questions:
Why does the song writer consider the (add 2) decorations? It sounds a bit messy and not clear. How will it be (or why not) to replace the follows:

replace F(add2)/C (namely CFGA) to F/C (namely CFA)?

replace Bb(add2) (namely BbCDF) to Bb (namely BbDF)?

replace Em7b5 (EGBbD) to Em7 (EGBD)?

For more information on the sheet music:
The first time:

Repeat the second time:
Comment: Both this and the linked question suggest an unfamiliarity with these kinds of harmonies. They're common in jazz, musical theater and movies, and singer/songwriter kinds of popular music.  Before continuing to look to analyze these kinds of chords/chord progressions, I highly recommend spending several months listening to this kind of music so that your ear can get used to it. Once you have a feel for the language, the analysis will be much easier.
Answer: Em7b5 vs. Em7
The song is temporarily in D minor here. Em7b5 is the ii7 chord in D minor; whereas Em7 is the ii7 chord in D major. D minor is the relative minor of F major, so the Bb has already been prominent in our ear throughout the piece.
Fadd2/C vs. F/C
The G in this chord is a carryover from the melody G that comes with "hap-py". I interpret it as hanging onto that memory of happiness in a way that transitions the lyrical subject from "she" to "I". Without that G, there's no melding of the two characters, just a sharp transition from one to the other.
(Note: In an earlier version of this answer, I proposed this chord as Csus4. This was based on changing the F to E (i.e., resolving the suspension) on the "and" of beat 4. However, this is wrong. What I really did was changed the chord to A minor, which sounds quite nice, but isn't what's happening here.)
Bb(add2) vs. Bb
The "add2" is a carryover from the previous chord and adds a gentle dissonance against both the Bb and the D. Were in "just" a Bb chord, that poignancy would be missing.
(Note: in an early version of this answer I claimed the Bbsus2 would be a better label. This is incorrect. Although the C is "suspended" from the previous chord, both the Bb and D — that is, the tones of resolution — are present in the Bb chord. Thus, the apparent suspension is a color tone rather than a dissonance requiring resolution.)
Comment: I'm not your mystery downvoter, this is a one-time thing. I'll explain why I happened to vote that way: my downvote is because I disagree with you on the second and third paragraphs. In the second paragraph, the Csus4 interpretation misses the A note of the Fadd2, and while Dm C Bb is a common progression, I think it is more accurate to examine the V-I F-Bb motion while using the descending bass motion to encompass the points in your paragraphs. The viability of Fadd2 can be established by changing beat 4 to an F7 chord. It also perfectly explains the melody without non-chord-tone analysis.
Comment: I also disagree with the Bbsus2 interpretation of paragraph 3. I see no issue with the Bbadd2 label, and to me the D note is clearly the chord tone. No need to exclude the note D from the chord label, in my opinion - it can all be in the Bbadd2, or honestly a simple Bb major triad is better for non-chord-tone analysis. So as to why I downvoted? It's because I disagree with a large portion of your answer. Nothing personal, I hope. And I'd be open to a discussion on the merits of our different interpretations, if you want to go to chat.
Comment: Good.  Now, what about the F(add2)?  I still challenge you on that!
Comment: @LaurencePayne I stand by that one. I think it's a C major chord in disguise, and I don't think the A is structural (though I could be persuaded to go with C6, perhaps).
Answer: Em7♭5 keeps us in the tonality of F major/D minor. A B♮ would take the music somewhere it doesn't want to go at that point.
The add2 chords are just an artistic decision.  You might consider them cheesy, Newman thinks the add to the emotion.   Fine, you write your music, he writes his.
And the printed chord names are fine.  In Fadd2/C  the A is as structural - the melody of that bar outlines the tonic chord of the piece.  And a chord containing B♭, F, C and D  is an (add2) not a (sus2).


Tips for going between trumpet and sousaphone from tune to tune?

Question: I used to play mostly trombone in trad jazz bands. I got turned onto the cornet, and there was a need for someone in our area to play the cornet, so I got it "up to speed". For a little while (short to be honest) I tried to double on trombone and cornet, but found the switch of mouthpieces and embouchures really uncomfortable, disorienting and well, made me worse on both when I switched from tune to tune.
So I stopped playing much trombone, since the cornet is smaller anyway and easier to travel with! Recently I joined a NOLA style second line band and there were 5 trumpets but no sousaphone players. The leader had a sousaphone laying around and asked if I'd be interested in playing. I gave it a go and it turns out I love it! With the 2nd line band I just play sousaphone now.
So this is the real question: I took the sousaphone AND my cornet to a swing jam the other day, thinking that I'd switch back and forth. I guess I had forgotten the issues with the trombone doubling. I hadn't tried to switch back and forth before this jam, and I found that not only was it disorienting and uncomfortable, it was darn near impossible for me to lock in my cornet embouchure after playing sousaphone for a tune. I just couldn't do it, and it got worse every time I tried. And it was very psychologically disorienting and uncomfortable. It felt like Alice in Wonderland or something. The cornet felt so awful and my lips felt rubbery and uncontrollable.
This is a long-winded way of asking WTF? I love both of these instruments (and trombone too), and I would love to be able to switch around on them, but maybe that's just a pipe dream. I don't see it done very much and maybe this is why, but it seems like at best I'll have to choose one per set, or maybe one per day. The technique and calibration are just too different for the accuracy required.
I do remember when I tried with trombone/cornet, that my embouchure on the trombone started fluttering uncontrollably on lower notes, and it felt that the actual muscle development caused by the cornet embouchure was interfering?
Anyway, does anyone have experience with this, and have tips, suggestions for me? Or confirmations that this is a pipe dream, or maybe just not meant to be, or not meant to be for me?
Thanks!
Comment: Warmup time between switches is best.  Meanwhile, maybe practice switching repeatedly while safely back home (or wherever you practice).
Comment: @CarlWitthoft I'm talking about switching during gigs between tunes. So there's not much "warmup time". In theory I'm already "warm". Maybe practicing at home switching is a good first start. I think I was mostly interested in others' experience of this.
Comment: as a related example,  check out Aubrey Logan, who goes from singing to playing trombone without blinking.
Comment: @CarlWitthoft I'm not sure these are related. I'm specifically referring to embouchure interference. I can go between violin, guitar, clarinet and ONE brass instrument without any issues. It's the issue of how the embouchure orientation, musculature, and fatigue affect accuracy and feel on brass.
Comment: I think your own suggestion in one of your comments above "practicing at home" is a good way to go on this matter.
Answer: I switch from Jazz small bore tenor trombone, large bore tenor trombone, bass trombone, sousaphone, and trumpet all the time. If I do have to switch between instruments quickly, I look for a mouthpiece with a rim and cup similar to that of the mouthpiece I use for the other. For example, I use a 12C for jazz, and that has a very specific rim shape and cup shape. So I got a Bousfield 5o for my large bore tenor, because that has a comparable rim shape. I use a Jupiter 24AW with my sousa, so I grabbed a 1/2 MD shires bass trombone mouthpiece. For the trumpet, I found a Bach 3c megatone works equally well for all of the doubling. Just find the mouthpiece that makes the transition easier, and you'll be set.
Answer: (I meant to ask the same question as I'm in a similar situation. I've been playing Euphonlum, Trombone, Eb-Bass for many years, and now I mean to practice Cornet.)
My friend -  a cornetist - had no problems to switch between Cornet and Bass or Euphonium, but from low to high it seams  to be harder. A tip: start with just buzzing high tones without Instrument. You can practice when and where ever you want. The same fort the Trombone- embouchure: let the lips  flatter 15min before you start playing.
Comment: I'm referring to changing instruments every other tune or something like that in a band performance situation. So there's not really time for buzzing or anything. Well maybe 20 seconds of buzzing.
Answer: Ask James Morrison how he does it!   Some people seem to be able to switch effortlessly between instruments.  But a whole lot more can't :-(
This may be a pipe dream for you.   But don't give in until you've had a hard look at your embouchure to make sure you aren't relying on pressure, and worked hard at developing flexibility on all the instruments.   On cornet, is a lip slur from middle C to the C two octaves higher (and back down) effortless?  Or are you 'screwing it in' for the high C?
Comment: Nothing for me above the middle D is effortless for me. And embarrassingly I have never hit a high C. I have plenty of work to do so this could be complicating matters for sure.


Given a URL to a movie, how can retrieve it's info?

Question: Under iOS, I need to get the codec used to make the move (H.264, MJPEG and so on), the movies' width and height, the file size, and the number of frames in the movie. I tried using AVAsset for the movie duration and such but the duration was always zero. Same for the width/height. I also tried using a movie player controller but that did not work either (see code below). The docs are a bit confusing and with multiple ways of getting to the same place you can't seem to get to the same spot.
Has anyone got the above information working properly? I am sure I am missing a few things but I was hoping for sample code and/or pointers?
Edit: I added a better code example. But, there are questions that remain. How do I get the creation date of the movie, the codec used to compress it and the movie's file size? Anybody figure these out?
Thanks
- (IBAction)getMovieInfo
{
    int         hours = 0, minutes = 0, seconds = 0;

    NSURL* sourceMovieURL = [NSURL URLWithString:@"http://trailers.apple.com/movies/summit/stepuprevolution/stepuprevolution-tlr1_h480p.mov"];
    AVURLAsset* movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];

    NSArray *tracks = [movieAsset tracksWithMediaType:AVMediaTypeVideo];

    if ([tracks count] != 0) {
        AVAssetTrack *videoTrack = [tracks objectAtIndex:0];

        NSTimeInterval      durationSeconds = CMTimeGetSeconds([movieAsset duration]);
        CGSize              videoSize = videoTrack.naturalSize;

        //
        // Let's get the movie's meta data
        //

        // Start with the duration of the movie
        hours = durationSeconds / 3600;
        minutes = durationSeconds / 60;
        seconds = (int)durationSeconds % 60;
        durationLabel.text = [NSString stringWithFormat:@"%d:%d:%d", hours, minutes, seconds];

        // Next is the creation (posting) date of the movie
        //postedLabel.text = AVMetadataQuickTimeUserDataKeyCreationDate;

        //The resolution of the movie
        resolutionLabel.text = [NSString stringWithFormat:@"%g x %g", videoSize.width, videoSize.height];

        // The frame rate of the movie
        rateLabel.text = [NSString stringWithFormat:@"%g fps", [videoTrack nominalFrameRate]];

        // The frame count of the movie
        countLabel.text = [NSString stringWithFormat:@"%g", [videoTrack nominalFrameRate] * durationSeconds];

        // Get the codec used to compress the movie

        // And lastly, let's generate a thumbnail of the movie
        AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:movieAsset];

        if (imageGenerator != NULL) {

            CMTime      thumbPoint = CMTimeMakeWithSeconds(15.0, 600);
            NSError     *error = nil;

            CGImageRef thumbnail = [imageGenerator copyCGImageAtTime:thumbPoint actualTime:nil error:&error];

            if (thumbnail != NULL) {
                // Convert CGImage thumbnail to UIImage and then scale it.
                UIImage *tempImage = [[UIImage alloc] initWithCGImage:thumbnail];

                if (tempImage != NULL) {
                    // Let's scale the image and put the it into the imageview.
                    self.thumbDisplay.image=[self scaleAndRotateImage:tempImage];

                    CGImageRelease(thumbnail);
                }
            }
        }
    }
}

- (UIImage *)scaleAndRotateImage:(UIImage *)image {

    CGImageRef  imgRef = image.CGImage;

    CGFloat     width = 135.0;
    CGFloat     height = 75.0;

    CGAffineTransform transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);

    CGFloat scaleRatio = bounds.size.width / width;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
    CGFloat boundHeight;
    UIImageOrientation orient = image.imageOrientation;

    switch (orient) {

        case UIImageOrientationUp: //EXIF = 1
            transform = CGAffineTransformIdentity;
            break;

        case UIImageOrientationUpMirrored: //EXIF = 2
            transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            break;

        case UIImageOrientationDown: //EXIF = 3
            transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationDownMirrored: //EXIF = 4
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
            transform = CGAffineTransformScale(transform, 1.0, -1.0);
            break;

        case UIImageOrientationLeftMirrored: //EXIF = 5
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
            transform = CGAffineTransformScale(transform, -1.0, 1.0);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationLeft: //EXIF = 6
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
            transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);
            break;

        case UIImageOrientationRightMirrored: //EXIF = 7
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeScale(-1.0, 1.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        case UIImageOrientationRight: //EXIF = 8
            boundHeight = bounds.size.height;
            bounds.size.height = bounds.size.width;
            bounds.size.width = boundHeight;
            transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
            transform = CGAffineTransformRotate(transform, M_PI / 2.0);
            break;

        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];

    }

    UIGraphicsBeginImageContext(bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    if (orient == UIImageOrientationRight || orient == UIImageOrientationLeft) {
        CGContextScaleCTM(context, -scaleRatio, scaleRatio);
        CGContextTranslateCTM(context, -height, 0);
    } else {
        CGContextScaleCTM(context, scaleRatio, -scaleRatio);
        CGContextTranslateCTM(context, 0, -height);
    }

    CGContextConcatCTM(context, transform);

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return imageCopy;
}

Comment: After some teeth bashing I have this block so far. But I still need to figure out how to get the creation date of the movie as well as its file size.
Answer: NSURL's method getResourceValue:forKey:error allows you to get total number of bytes:
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
NSString *size = NULL;
[fileUrl getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
NSLog(@"Bytes : %@",size);

It is good practice to check for any errors returned.
Comment: NSURLFileSizeKey return an NSNumber
Answer: Try:
CMTime lengthTime = [movieAsset duration];
Float64 seconds = CMTimeGetSeconds(lengthTime);
NSLog(@"Asset is %g seconds long", seconds);


Irrationality of ${\pi}$ and $e^{x/y}$

Question: I attempt to prove that ${\pi}$ is an irrational number. For this, I use the beautiful continued fraction given by Brouncker who rewrote Wallis' formula as a continued fraction, which Wallis and later Euler (1775) proved to be equivalent.
The continued fraction given by Brouncker is
$$\frac{4}{\pi} =
1 + \cfrac{1}{3 + \cfrac{4}{5 + \cfrac{9}{7 + \dots}}}$$
Now we know that every infinite continued fraction is irrational. Does it mean that since RHS has an infinite continued fraction the LHS $\frac{4}{\pi}$ must also be irrational? And hence ${\pi}$ must be an irrational number?
EDIT 1: From this post General Continued Fractions and Irrationality If, in the continued fraction
$$\cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \dots}}}$$
the values $a_{i}, b_{i}$ are all positive integers, and if we have $a_i \geq b_i$ for all $i$ greater than some $n$, then the value of the continued fraction is irrational(Is this a necessary and sufficient condition? I am in doubt since the golder relation $\phi$ has $a_i \geq b_i=1$ for all $n\geq1$). As the condition is not satisfied the proof is actually wrong.
EDIT 2:
How to prove the following continued fraction of  $e^{x/y}$
$${\displaystyle e^{x/y}=1+{\cfrac {2x}{2y-x+{\cfrac {x^{2}}{6y+{\cfrac {x^{2}}{10y+{\cfrac {x^{2}}{14y+{\cfrac {x^{2}}{18y+\ddots }}}}}}}}}}}$$
Since $a_i \geq b_i$ for all $i \geq 1$. By the condition of irrationality of generalized continued fraction, proving this directly proves that $e^{x/y}$ will be an irrational number!
Comment: Proving  $\pi$ is irrational number is much harder than it seems...
Comment: That's the idea behind Lambert's proof of the irrationality of $\pi$. See [this](https://en.wikipedia.org/wiki/Proof_that_%CF%80_is_irrational#Lambert's_proof) and [this](https://hal.archives-ouvertes.fr/hal-02984214/document).
Comment: Your right-hand side is not really a continued fraction but a generalised continued fraction, with numerators greater than the first term of the denominators, so it does not quite work
Comment: @Henry Does the generalized infinite continued fraction is not an irrational number?
Comment: https://math.stackexchange.com/questions/895611/lamberts-original-proof-that-pi-is-irrational
Comment: @SourangshuGhosh See [this](https://en.wikipedia.org/wiki/Generalized_continued_fraction#Conditions_for_irrationality) for the irrationality condition in the case of generalized cf.
Comment: What are you allowed to use in your proof. Seems like nearly everything is fair game?
Comment: @Jean-ClaudeArbaut thanks for the link. What does K represent in the formula?
Comment: It's just a shorthand notation for the continued fraction, similar to $\sum$ or $\prod$ for sums and products. See https://mathworld.wolfram.com/GeneralizedContinuedFraction.html
Answer: To see that not every generalized infinite continued fraction is irrational, note that if
$$
x=1 + \frac{2}{1 + \frac{2}{1 + \frac{2}{1 + ...}}}
$$
then $x=1+{\large{\frac{2}{x}}}$, so $x=2$.

Of course that assumes that the continued fraction converges.

To prove $x=2$ more rigorously, we can argue as follows . . .

By definition, $x$ is the limit, if it exists, of the infinite sequence $x_0,x_1,x_2,...$ defined recursively by $x_0=1$ and
$$
x_n=1+\frac{2}{x_{n-1}}
$$
for $n\ge 1$.

Clearly we have $x_n \ge 1$ for all $n$.

For $n\ge 1$ we have
$$
x_n=1+\frac{2}{x_{n-1}}\le 1+\frac{2}{1}=3
$$
hence, since $x_0=1$, we have $x_n\le 3$ for all $n$.

Then for all $n\ge 1$ we get
$$
x_n=1+\frac{2}{x_{n-1}}\ge 1+\frac{2}{3}=\frac{5}{3}
$$
From the recursion we get
$$
x_n-2=\frac{2-x_{n-1}}{x_{n-1}}
$$
for all $n\ge 1$, hence for all $n\ge 2$ we get
$$
\left|x_{n}-2\right|\le\frac{\left|x_{n-1}-2\right|}{\left({\large{\frac{5}{3}}}\right)}
$$
and then an easy induction yields
$$
\left|x_n-2\right|\le\Bigl(\frac{3}{5}\Bigr)^{\large{n-1}}
$$
for all $n\ge 2$.

It follows that
$$
\lim_{n\to\infty}x_n = 2
$$
so $x=2$.

As to the question you raised in your edit, consider the generalized continued fraction
$$
1 + \frac{3}{1 + \frac{3}{1 + \frac{3}{1 + ...}}}
$$
which can be shown to be equal to
$$
\frac{1+\sqrt{13}}{2}
$$
Thus the condition for irrationality that you referenced is a sufficient condition, but not a necessary condition.
Comment: $x=1+\frac{0}{1+\frac{0}{1+\frac{0}{1+\dots}}}$ is rational as well, with arguably more apparent convergence.
Comment: To be extra rigorous, one would also have to prove that it's convergent.
Comment: Agreed. I'll edit in a proof of that.
Answer: Regarding the second part of the question.
I think this might be a solution.
The Continued Fraction Expansion of the hyperbolic tanh function discovered by Gauss is
$$\tanh z = \frac{z}{1 + \frac{z^2}{3 + \frac{z^2}{5 + \frac{z^2}{...}}}} \\$$
We also know that the hyperbolic tanh function is related to the exponential function with the following formula
$$\tanh z=\frac{e^z-e^{-z}}{e^z+e^{-z}}$$
Putting $\frac{x}{y}$ in place of $z$ in the previous equation we get
$$\frac{e^{\frac{x}{y}}-e^{-{\frac{x}{y}}}}{e^{\frac{x}{y}}+e^{-{\frac{x}{y}}}}= \frac{{\frac{x}{y}}}{1 + \frac{{\frac{x}{y}}^2}{3 + \frac{{\frac{x}{y}}^2}{5 + \frac{{\frac{x}{y}}^2}{...}}}} \\$$
This continued fraction can be simplified into
$$\frac{e^{\frac{x}{y}}-e^{-{\frac{x}{y}}}}{e^{\frac{x}{y}}+e^{-{\frac{x}{y}}}}= \frac{x}{y + \frac{x^2}{3y + \frac{x^2}{5y + \frac{x^2}{...}}}} \\$$
This equation can be further be simplified as
$$1+\frac{2}{e^{\frac{2x}{y}}-1}=y + \frac{x^2}{3y + \frac{x^2}{5y + \frac{x^2}{...}}} \\$$
$$\frac{e^{\frac{2x}{y}}-1}{2}=\frac{1}{(\frac{y}{x}-1) + \frac{x}{3y + \frac{x^2}{5y + \frac{x^2}{...}}}}$$
From this equation after some algebraic manipulation, we finally get the continued fraction expansion of $e^{x/y}$ as
$${\displaystyle e^{x/y}=1+{\frac {2x}{2y-x+{\frac {x^{2}}{6y+{\frac {x^{2}}{10y+{\frac {x^{2}}{14y+{\frac {x^{2}}{18y+\ddots }}}}}}}}}}}$$
This is an infinite generalized continued fraction. We will now state the necessary and sufficient condition for the continued fraction proved by Lagrange given in Corollary 3, on page 495, in chapter XXXIV on "General Continued Fractions" of Chrystal's Algebra Vol.II to converge into an irrational number.
\begin{theorem}The necessary and sufficient condition that the continued fraction
$$\frac{b_1}{a_1 + \frac{b_2}{a_2 + \frac{b_3}{a_3 + \dots}}}$$
is irrational is that the values $a_{i}, b_{i}$ are all positive integers, and if we have $|a_i| > |b_i|$ for all $i$ greater than some $n$
\end{theorem}
In the continued fraction of $e^{x/y}-1$ as we have derived $a_{i}, b_{i}$ are equals to $2(2i-1),x^2$ except $i=1$.Therefore we have $|a_i| > |b_i|$ for all $i>\frac{\frac{x^2}{2}+1}{2}$. Hence we have proved that $e^{x/y}-1$ is irrational which in turn means $e^{x/y}$ is irrational.

Irrationality of ${\pi}$ and $e^{x/y}$


How do I have points and polygons in the same Leaflet map?

Question: I have two content types

Location that geocodes an addressfield to place markers on the map
Boundary that uses a geojson field to create complex shapes on the map

I need to use views to show both content types on the same map. It appears that I can only do one or the other.
For an example, think about a map that shows constituency boundaries and voting stations.
Answer: Nigel Waters has it correct. Here are the details. I did this for cities and states. I used points for cities and polygons for states. Here are the steps.
Requirements:

Geofield module
Leaflet module
Leaflet Views module (a submodule of Leaflet)

Steps:

Create the two content types: City and State.
Create a field of type Geofield, call it "Location"
Choose GeoJSON as the field widget
Add the Location field to both content types
Create a city. For location enter GeoJSON Point data
Create a state. For location enter a GeoJSON Polygon data
Create a view with a Page display
Add the Location field to the view
Filter the view by State and City content types
Set the Format of the view to Leaflet Map
Your view should now look like pic 1
Click on View Page
You should see a map like pic 2
Answer: To answer my own question is to use the same field on both content types. I used a geojson (geofield) field which accepts both points and polygons to merge into a single leaflet map in views.
Comment: mmm... it would be very interesting to get a more deep explanation about did you do that... thanks in advance
Comment: I am not going to write out an entire tutorial as I don't have the time. Just add a geofield of type "geojson", then just add your points and polygons using geojson. I found the following site very helpful to draw out what i needed and then I just pasted the json directly into the field of my content type. http://geojson.io/
Comment: No need to write a tutorial. I see your geojson is not dynamic (I need create map based on views) so its not useful for me. Thanks in any case.
Comment: It is dynamic. I use views to place the markers on the map and a proximity search function.
Answer: To show multiple content types in the same View:

Edit your view
Under "Filter Criteria" click "Content: Type"
Select both content types under the "Content types" section
Click Apply
Comment: Could you add 2 screenshots? One that shows configuration needed, and other that shows both points and polygons actually displayed in the same Leaflet map?
Comment: @Molot It doesn't matter. This doesn't answer the question. The question is not how to add two content types to a view. The question is how to add to content types to a leaflet map. THe leaflet map settings in a view only allow for one field from one content type.
Comment: @NigelWaters if module clearly disallows what you are trying to do, it is a feature request and should be posted in module's issue queue rather than here. Unless you are trying to code a fix - in that case, show the code you are using, or the part of code that is relevant to the question.
Comment: The module does not "clearly" disallow what I am trying to do. The Leaflet API definitely allows this and there are also several Drupal examples of combining these features into one map. I was hoping that one with experience could point me in the right direction.


Problema com delay em jquery

Question: O delay dessa função em jquery não esta pegando, queria saber o motivo, ou um outro jeito de fazer um delay no mesmo.
$("header").delay(1000).css("display", "none");
$(".logo_1").delay(2000).css("display", "none");

OBS: Já olhei todo o api do jquery esta correto como eu fiz mas não pega.
Answer: O mais simples parece-me usar o setTimout e o .hide() (o .hide() faz o mesmo que .css('display', 'none')):
setTimeout(function () {
    $("header").hide();
}, 1000);
setTimeout(function () {
    $(".logo_1").hide();
}, 2000);

Exemplo
O jQuery tem um "fila de espera" .queue() para poder encadear funcções. Neste caso o aspeto seria assim:
$("header")
    .delay(1000)
    .queue(function (next) {
    $(this).css('display', 'none');
});
$(".logo_1")
    .delay(2000)
    .queue(function (next) {
    $(this).css('display', 'none');
});

Exemplo
A razão pela qual o seu código não funcionou dá para ler na página da documentação do jQuery:

o método .delay() permite atrasar a execução de funções que estão numa queue. Pode ser usada com uma queue de efeitos ou uma queue customizada.
Answer: O método delay só vale para animações, e esconder um elemento sem fade, somente manipulando a propriedade display, não envolve animação.
Um breve fadeOut deve resolver:
$("header").fadeOut(100);
$(".logo_1").delay(2000).fadeOut(100);

Ou (mesmo efeito):
$("header").hide(100);
$(".logo_1").delay(2000).hide(100);

Você verá o delay entre os dois fades. Se quer um delay no início e não houver nenhuma animação pendente antes dessas, use um setTimeout:
setTimeout(function(){
    $("header").hide(100);
    $(".logo_1").delay(2000).hide(100);
}, 1000);

Comment: estou usando exatamente isso, ultilizo fadeIn() - delay() - fadeOut() (8 segundos) para exibir um alerta pro usuário, mas no próprio alerta, resolvi colocar um botão para o usuário dar dismiss fadeOut() no alerta, antes dos 8 segundos, más não funciona, o fadeOut só executa depois do delay(), tem como forçar a parada do delay() ?
Comment: https://api.jquery.com/clearQueue/ @hugopablo

Problema com delay em jquery


HTTP Error 404: Not Found - Post request not working

Question: Im trying to use postcode.io to get longitude and latitude from a bunch of postcodes by using the "Bulk lookup postcodes" that they have shown on the website https://postcodes.io/.
Im trying to pass a json object to the api point as they've shown in the documentation but keep getting the error shown in the title.
Here is my code;
allpostcodes = [i['postcode'] for i in _sortedstores()] # Getting postcodes from json file

data = {}
data['postcodes'] = allpostcodes # creating a dictionary and keeping `postcodes` and key and the postcode's as the value as shown in the example

_postcodearray = 'https://api.postcodes.io/%s' % json.dumps(data) # creating a json object and passing in the data
#_postcodearray = 'https://api.postcodes.io/%s' % data['postcodes'] #Not working

try:
    with urllib.request.urlopen(_postcodearray) as _postcodearray:
        a = _postcodearray.read()
        a = json.loads(a.decode('utf-8'))
        print(a)
except Exception as e:
    print(e)

How my data varible looks before i use json.dump on it {'postcodes': ['GU34 2QS', 'TN23 7DH', 'HP20 1DH']}
I have also tried to regularly pass an array which resulted in the same error. Any help/suggestion on what i could be doing wrong would be appreciated.
Comment: can you show how your `data` variable looks like before the request?
Comment: @Vishal Sure, i will update my question with it at the bottom.
Comment: can you change the url to `_postcodearray = 'https://api.postcodes.io/postcodes/%s' % json.dumps(data)` and try
Comment: @Vishal I actually did try that before and forgot to mention it, i still get the same error.
Comment: `postcodes` will definitely be there at the end. otherwise it is not a valid url. I tried with Postman app in my desktop and it is working fine.
Comment: what version of python you are using?
Comment: @Vishal i too just tried it and it seems like it is still not working for me, maybe im passing the data in wrong?
Comment: @Vishal Python 3.7.2
Answer: #!/usr/bin/env python3

import json
import urllib.request

allpostcodes = ["OX49 5NU", "M32 0JG", "NE30 1DP"]
#allpostcodes = [i['postcode'] for i in sortedstores] # Getting postcodes from json file

values = {}
# creating a dictionary and keeping `postcodes` and key and
# the postcode's as the value as shown in the example
values['postcodes'] = allpostcodes

api_endpoint = 'https://api.postcodes.io/postcodes/'
data = json.dumps(values).encode('utf8')
req = urllib.request.Request(api_endpoint, data,
        headers={'content-type': 'application/json'})
try:
    with urllib.request.urlopen(req) as response:
        result = json.loads(response.read())
        print(json.dumps(result, indent=2))
except Exception as e:
    print(e)


How to change directly the voice of a note with Musescore?

Question: I have a staff with wrong placement of notes. I can change the selected note's staff with ctrl+shift+up/down, but the voice of the note remains and creates a mess.
How can I change the voice of a not with one operation (or minimal) so it is detached from the voice group of notes ?
In this example, I want to move the notes according to the red arrows. Ideally the change should be associated by a voice change and I should have voice green at the bottom and blue voice at the top.
Comment: Given the godawfulness of what you're trying to deal with - 64th rests, even a 128th rest!?! - if you're editing for readability, I recommend an overhaul such as transcribing this by ear.
Comment: Isn't the green voice already in the bottom and the blue voice already on top in your picture?
Comment: @Dekkadeci Well quantization may help simplify, that would be a smart first step before thinking taking such radical option.
Answer: You'll need to make do with cutting-and-pasting notes from one staff to the other. I would NOT use ctrl+shft+up & down, since all it does is move the note representation to the other staff, but it's still counted for in the original staff.
When ever I encounter a mess like this, I tend to create additional staves, where I can temporarily park stuff. E.g. I'd create a new staff and start constructing the blue notes there, cutting them from the source staves and pasting them in the destination staff and immediately changing the voice and fixing durations etc. when necessary.
Comment: @Soleil - If by "changing the text" you mean cutting and pasting or committing notes to memory when deleting and adding - with the attendant risk of mis-remembering the note transferred - then I'm afraid you have to change the text.
Comment: "with one operation (or minimal) ", furthermore you are changing the text, I want to keep it but change the "label" of few notes.
Comment: @Soleil - One example where you *have* to change the text if all you want is 2 voices is the third note you want to transfer: a dotted 32nd note that's getting placed where the latter part of a 16th note is. I'd have to shorten the 16th note to a 64th note in order to transfer your dotted 32nd note.
Comment: @Soleil - Even if you want to preserve all note starts and note lengths when transferring that dotted 32nd note, you have to resort to hacks such as replacing that 16th note with a 64th note tied to a dotted 32nd note. In short: for situations like that, you *really* have to change the text and you *cannot* win.
Comment: @Soleil it's not possible with one operation, I'm afraid. It's like asking to untangle a ball of christmas lights with "one operation or minimal". Cleaning up midi is unfortunately still a manual and intelligent operation, since you'll need to judge what needs to happen exactly. Maybe some day using A.I. it will be different.
Answer: Naively, you can click on any individual note and change which voice that particular note is in by clicking on the voice label you want (details on how to do that are in https://musescore.org/en/handbook/3/voices#change-voice).
You can even exchange the voices of (two voices' worth of) notes by selecting the range you want to exchange voices of, going to the menu bar, and finding which voices you want to exchange in the resulting dropdown menus (further details in https://musescore.org/en/handbook/3/voices#exchange-voices).
This may hit snags if the note you want to swap in is a different note length than at least one note in the equivalent place in the voice you want to swap that note into, such as swapped-in notes displacing swapped-out notes or the notes refusing to swap in the first place. I'm afraid I'll have to defer to Creynders and his answer (copy and paste notes back and forth, or essentially do that by committing single notes to memory and deleting and adding them yourself) if you encounter those snags.
If you want to preserve note starts and possibly nothing else whenever you hit such a snag, you may need to edit notes in the voice you're swapping notes into to fit in the notes you're swapping out. For example, in order to successfully swap in the third note you want, a dotted 32nd note trying to displace the latter portion of a 16th note, I'll have to turn that 16th note into a 64th note.
Even if you want to preserve all note starts and note lengths when transferring that dotted 32nd note, you have to resort to hacks (with their own readability issues) such as replacing that 16th note with a 64th note tied to a dotted 32nd note, then swapping that dotted 32nd note in.
Comment: The problem I had was the duration discrepancy, which blocks the voice affectation.
Comment: @Soleil - I was afraid your situation matched my third paragraph for a high enough percentage of notes: snag after snag.
Answer:
Select the passage whose voices you want to change
Go to the Tools menu on the top bar, and then go to voices. There you will find options like "Exchange voice 1-2" and so on. Click on what you need. It's as simple as that.
Comment: This is not what I'm trying to achieve.


How should I approach updating a "hot" table?

Question: I have a postgres DB with a "hot" table, meaning it is receiving many updates + deletes every second. I would like to run a query that will UPDATE about 10% of its rows.
I do not have an index on the 10% criteria and the isolation level is set to SERIALIZABLE as a DB flag (affecting all transactions). I would like this query to succeed, even if it temporarily blocks other ongoing updates. This is a one-time data migration and I won't need an index on this criteria once the transaction completes. The query will run for several minutes.
It seems I have a few paths forward, and I'm trying to determine which would be best:

I could take out an explicit table lock, e.g.:

BEGIN;
LOCK TABLE hotness IN SHARE MODE;
SELECT * FROM hotness WHERE ...; -- 10% of rows affected
-- make some maybe-complex business logic decisions
UPDATE hotness SET x = some_result WHERE ...;
COMMIT;

But I wonder if that approach would block more concurrent manipulations than is strictly necessary.

I could create a temporary index in the txn:

BEGIN;
CREATE INDEX foo ON hotness (...);
SELECT * FROM hotness WHERE ...; -- 10% of rows affected
-- make some maybe-complex business logic decisions
UPDATE hotness SET x = some_result WHERE ...;
DROP INDEX foo;
COMMIT;

This seemed appealing at first since the index would allow only certain updates to conflict (thanks to predicate locks), but it seems CREATE INDEX itself takes out a SHARE mode lock, so it seems to be strictly worse (table lock + overhead of btree creation).

I could use explicit row-level locks, e.g.:

BEGIN;
SELECT * FROM hotness WHERE ... FOR NO KEY UPDATE; -- 10% of rows affected
-- make some maybe-complex business logic decisions
UPDATE hotness SET x = some_result WHERE ...;
COMMIT;

but without an index on this criteria, I think the planner would execute a SeqScan, which would effectively row-lock the entire table, which also seems worse than option 1.

I could rely on the SERIALIZABLE isolation level and retry again and again, hoping to catch a window where we happen to be the "winning" txn and don't throw a serialization exception.

In my experiments, this doesn't seem at all feasible, thanks to how many concurrent inserts + updates are happening in this table while my query is running.
Any thoughts on which approach is best?
Comment: "but it seems CREATE INDEX itself takes out a SHARE mode lock"  Couldn't you create the index concurrently?
Comment: It is not asynchronous. The session which issued the CREATE blocks until the build completes, just like regular CREATE INDEX does.
Comment: @jjanes is there a way to poll for completion + validity of the `CREATE INDEX CONCURRENTLY` statement? I guess you'd have to poll `pg_stat_progress_create_index` until it completes?
Answer: As you noticed yourself, options 2. and 3. are not useful. Only 1. and 4. look promising.
If the table is really hot, I think that the only feasible option will be an explicit table lock. SHARE mode would be sufficient to prevent deadlocks, but there could still be serialization errors if concurrent transactions read the rows you want to modify. If you want to be certain that no conflicts can occur, you have to take an ACCESS EXCLUSIVE lock on the table. Both a SHARE and an ACCESS EXCLUSIVE lock on the table are problematic, because they will cancel concurrent autovacuum runs. So only consider this solution if this update of 10% of the table does not occur often.
To see if the less invasive method 4. could work, you'd have to experiment. It may well be that your transaction never succeeds on a hot table.
Comment: The use-case is a one-time data migration for an evolving schema, so won't be happening often. I'm also looking to provide guidance for our team on how to think about + develop these kinds of migrations in the future. Thanks for the insights!
Answer: There are various methods for updating 10% of the rows in "hot" PostgreSQL tables which undergo frequent updates and deletions. Although it can guarantee success, locking the table in SHARE MODE may momentarily block other transactions.
It takes a lot of resources and may result in significant locking to create a temporary index in the transaction. Without an index, table-level locks could result from row-level locks using FOR NO KEY UPDATE.
As serialization errors occur frequently, relying on the SERIALIZABLE isolation level with retries may not be practical.
In my opinion option 1 (a table-level lock) would be feasible given your restrictions, but it might obstruct other transactions. It is vital to fine-tune, taking into consideration the particular requirements and performance effects of your program.
Comment: Yeah the entire table being locked, even when you think you're doing row-level `FOR NO KEY UPDATE` locks, is an unfortunate gotcha from not having proper indexes!


Can this integral be expanded as a power series?

Question: I am looking at this integral:
$$I(x_1^2, x_2^2) = \frac{1}{4}x_1^2 x_2^2 \int\limits_{-\infty}^{\infty} d\tau_3 \int\limits_{-\infty}^{\tau_3} d\tau_4 \int\limits_{-\infty}^{\tau_4} d\tau_5 \int\limits_{-\infty}^{\tau_5} d\tau_6\ (I_{13}I_{25} + I_{15}I_{23})(I_{14}I_{26} + I_{16}I_{24}), \tag{1}$$
with:
$$I_{ij} := \frac{1}{(2\pi)^2} \frac{1}{x_i^2 + \tau_j^2}. \tag{2}$$
I would like to expand $I(1,x_2^2)$ as a power series centered at $x_2 \sim 0^+$, i.e.:
$$I(1,x_2^2) = c_0 + c_1 x_2 + c_2 x_2^2 + ... \tag{3}$$
with $x_2 > 0$. I know from numerical integration that:
$$I(1,0) = \frac{1}{2^{12} \pi^4} = c_0. \tag{4}$$
I would like to find as many coefficients as possible in eq. (3). My naive attempt was to power expand the integrand of eq. (1), which gives:
$$\begin{align}
I(1,x_2^2) = \frac{x_2^2}{4(2\pi)^8} \sum_{k=0}^\infty \sum_{l=0}^\infty (-1)^{k+l} x_2^{2(k+l)} \int\limits_{-\infty}^{\infty} d\tau_3 \int\limits_{-\infty}^{\tau_3} d\tau_4 \int\limits_{-\infty}^{\tau_4} d\tau_5\\ \int\limits_{-\infty}^{\tau_5} d\tau_6\ \left( \frac{\tau_5^{-2(k+1)}}{1+\tau_3^2} + \frac{\tau_3^{-2(k+1)}}{1+\tau_5^2} \right) \left( \frac{\tau_6^{-2(l+1)}}{1+\tau_4^2} + \frac{\tau_4^{-2(l+1)}}{1+\tau_6^2} \right).
\end{align} \tag{5}$$
The idea was to numerically integrate the integrals for given $k$ and $l$. Unfortunately this cannot be right, since there is no $c_0$ term, and the integrals seem to diverge for all $k,l$.
So can such an expansion as a power series be done, and if yes how?
EDIT:
So I have managed to reduce $(1)$ to a one-dimensional integral analytically (recall that I assume $x_1,x_2>0$):
$$\begin{align}
I(x_1^2,x_2^2) = \frac{1}{256\pi^6} \int\limits_{-\infty}^\infty d\tau_3\ \Biggl\lbrace x_1 I_{13} \left(\tan^{-1} \frac{\tau_3}{x_2} \right)^2 \left( 2\tan^{-1} \frac{\tau_3}{x_1} + \pi \right)\\
 + x_2 I_{23} \left(\tan^{-1} \frac{\tau_3}{x_1} \right)^2 \left( 2\tan^{-1} \frac{\tau_3}{x_2} + \pi \right) \Biggr\rbrace. \end{align}\tag{6}$$
From there I should be able to compute the coefficients. For example the coefficient $c_1$ should obey:
$$c_1 = \left. \frac{\partial}{\partial x_2} I(1,x_2^2) \right|_{x_2 = 0}. \tag{7}$$
However when I differentiate $(6)$ and then integrate for decreasing values of $x_2$, the result does not seem to converge. I am moderately confident that this is not a numerical artefact. I observe the same thing for the second derivative.
Any idea why this is happening, or what it could mean?
Answer: For $x_1, x_2 > 0$, we have
$$ I(x_1^2,x_2^2) = \frac{F(x_1/x_2) + F(x_2/x_1)}{2^{10}\pi^7}, $$
where
$$ F(x) := \int_{-\infty}^{\infty} \mathrm{d}t \, \frac{\arctan^2(xt)}{t^2+1}. $$
1. The behavior of $F(x)$ as $x \to 0^+$ is easier to study. Indeed, $F(0) = 0$ is obvious, and
$$ \frac{F(x)}{x} \stackrel{(u=xt)}= \int_{-\infty}^{\infty} \mathrm{d}u \, \frac{\arctan^2(u)}{u^2+x^2} \xrightarrow{x \to 0^+} \int_{-\infty}^{\infty} \mathrm{d}u \, \frac{\arctan^2(u)}{u^2} = 2\pi \log 2 $$
shows that
$$F(x) = (2\pi \log 2)x + o(x) \quad \text{as} \quad x \to 0^+.$$
In fact, it can be shown that $F(x)$ extends to an analytic function on all of $\mathbb{C}\setminus(-\infty, 1]$ that agrees with the integral definition along the positive line $(0, \infty)$.
2. The behavior of $F(1/x)$ as $x \to 0^+$ is much trickier. First, we have $F(+\infty) = \frac{\pi^3}{4}$. Then
\begin{align*}
F(1/x) - F(+\infty)
&= 2 \int_{0}^{\infty} \mathrm{d}t \, \frac{\arctan^2(t/x) - (\pi/2)^2}{t^2+1} \\
&= -4x \int_{0}^{\infty} \mathrm{d}t \, \frac{\arctan(t/x)\arctan(t)}{t^2+x^2} \tag{IbP} \\
&= -4x \int_{0}^{\infty} \mathrm{d}t \, \frac{\arctan(t/x)(\arctan(t) - t \mathbf{1}_{[0,1]}(t))}{t^2+x^2} \\
&\quad - 4x \int_{0}^{1} \mathrm{d}t \, \frac{\arctan(t/x)t}{t^2+x^2} .
\end{align*}
In the last line, the first integral without the prefactor $4x$ converges as $x \to 0^+$ by the Dominated Convergence Theorem. Next,
$$ \int_{0}^{1} \mathrm{d}t \, \frac{\arctan(t/x)t}{t^2+x^2}
= \int_{0}^{1/x} \mathrm{d}u \, \frac{\arctan(u)u}{u^2+1}
\sim \frac{\pi}{2} \log(1/x) $$
as $x \to 0^+$, where the asymptotic equivalence in the last step follows from the L'Hopital's Rule. Combining altogether,
$$ F(1/x) = \frac{\pi^3}{4} + (2\pi + o(1)) x \log x \quad\text{as}\quad x \to 0^+. $$
Conclusion. Using the above estimates, we get
$$ I(1,x_2) = \frac{1}{2^{12}\pi^4} + \frac{1 + o(1)}{2^9\pi^6} x_2 \log x_2 \quad\text{as}\quad x_2 \to 0^+. $$
Comment: @Jxx, Indeed, this shows that your function develops a logarithmic singularity around $x_2=0$, which prevents power series expansion from happening.
Comment: Wow, this is amazing! I tried to reproduce your conclusions numerically, and it is pretty close: computing $(I(1,x_2)-c_0)/x_2 \log x_2$ for $x_2 = 10^{-25}$, I obtain $2.01793 \cdot 10^{-6}$, while $1/2^9\pi^6$ gives $2.03157 \cdot 10^{-6}$. Quite convincing! Would you say that this means the integral *cannot* be expanded as a power series around $0$?


Onde devo colocar os blocos Try/Catch usando MVC?

Question: estou fazendo uma aplicação web em java e tenho algumas duvidas em relação ao bloco try catch, estou usando o padrão MVC e tenho os seguintes códigos:
Controller:
try {
    String pesquisa = "%" + request.getParameter("pesquisa") + "%";
    List<Administrador> adm = serviceAdm.listarAdm(pesquisa);

    request.setAttribute("adm", adm);
    RequestDispatcher disp = request.getRequestDispatcher("administradores.jsp");
    disp.forward(request, response);
} catch (Exception ex) {
    System.out.println("Erro: " + ex);
    request.setAttribute("erro", true);
    RequestDispatcher disp = request.getRequestDispatcher("principal.jsp");
    disp.forward(request, response);
}

Model:
public List<Administrador> listarAdm(String pesquisa) {
    try {
        return (List<Administrador>) admDB.selectAdms(pesquisa);
    } catch (Exception ex) {
        return null;
    }
}

E uso o DAO para fazer a conexão:
public List<Administrador> selectAdms(String pesquisa) {
    List<Administrador> usuarios = manager
            .createQuery("select a from Administrador a where nome LIKE :pesquisa")
            .setParameter("pesquisa", pesquisa).getResultList();

    return usuarios;
}

Gostaria de saber se caso der algum problema no Model, como eu coloquei para ele retornar null, ele não vai entrar no catch do Controller? Eu devo colocar o try/catch em todos os arquivos ou só nos Controllers?
Comment: Tenho duas perguntas para responder sua resposta : http://pt.stackoverflow.com/questions/58536/blocos-try-catch?rq=1 e http://pt.stackoverflow.com/questions/108484/uso-espec%C3%ADfico-do-try-catch?rq=1
Comment: Foi você quem criou o seu proprio MVC? Ou é algum framework especifico?
Answer: A ideia de uso do try catch é justamente capturar exceções que a aplicação possa lançar e executar uma operação alternativa. Então você deve colocar escopos de try catch toda vez que a aplicação puder lançar um erro, ou seja, se um erro pode ocorrer em um arquivo, use try catch.
Pelo seu código, o catch do controller lançará uma exceção por você tentar utilizar uma variável que está como null. Então, sua lógica funcionará corretamente.
Comment: *Downvoters*, poderiam explicar ao Jader (que está respondendo pela primeira vez no site), o motivo do voto negativo?
Answer: Você pode usar throws na assinatura dos métodos do model para ecoar as exceptions direto para o Controller ao invés do try catch ou usar o try catch mesmo e dentro do catch você faz um throw new para especificar o erro gerado no model.


Annoying behaviour when I'm counting checked elements of a checkbox

Question: I have a form with many checkboxes. Somewhere in my client's code I need to check if a given checkbox is really checked returning a boolean value. I've googled around and supposed this solution as optimal:
$("input[@id=checkboxId]:checked").length>0

This works fine if every checkbox in the page is unchecked, while it's completly unusefull otherwise. Why this happens? Why other checkboxes interfear with this behaviour even specifyng the id of interested checkbox?
I prepared a fiddle of this behaviour. In this example you can notice, that, if the second checkbox is checked, console output will be always true, while if I uncheck the second checkbox I have alternate true/false value.
Where I wrong how can I fix this (I have jQuery 1.4 on this client and I can't upgrade)?
Comment: console.log($("#testableCheckbox:checked").length>0)
works fine.. the @ is the problem..
Answer: Remove the @ symbol from your attribute selector.(@attr was removed from jQuery 1.3)
It should be $("input[id=checkboxId]:checked").length > 0
JSFIDDLE DEMO
or simply $("#checkboxId:checked").length > 0
http://api.jquery.com/category/selectors/attribute-selectors/
Note: In jQuery 1.3 [@attr] style selectors were removed (they were previously deprecated in jQuery 1.2). Simply remove the "@" symbol from your selectors in order to make them work again.
Comment: Just a curiosity: where his @ came from? I can't remember any time I did @attr ..  Or any docs mentioning it.
Comment: @enapupe - until jQuery 1.2, @attr is the syntax. `@` was removed from  v1.3
Comment: That was a long time huh? 2008? jQuery 1.2 'New Wave Javascript'
Comment: @enapupe yep it was. Sep '07
Answer: You can use any of this method
console.log($(this).is(':checked'))

or
console.log($('#checkboxId').is(':checked'))


R2 in Brackets with Esttab

Question: I want to export my regression results in TeX format with R2 in brackets using esttab. The code below produces a table with no brackets around R2 and I couldn't find a way to add them.
sysuse auto
eststo: qui reg price mpg

esttab using "reg.tex", ///
compress noconstant replace gaps noobs ///
 b(%8.3f) se(%8.3f) r2(%8.3f) nolines

Comment: I recommend going on Statalist with this one. `esttab` is a great command I never use, so I stop there.
Answer: I am not sure this is possible out-of-the-box with esttab. The second-best is to automate this via sed (if on Mac/Linux):
sysuse auto
eststo: qui reg price mpg

esttab using "reg.tex", ///
compress noconstant replace gaps noobs ///
 b(%8.3f) se(%8.3f) r2(%8.3f) nolines

shell sed -i.bak -e 's#\\(R^{2}\\)#[R^{2}]#' reg.tex

On Windows it's possible to use powershell for this, but I don't have access to a Windows machine to test it. A good starting point for Windows could be this answer.

R2 in Brackets with Esttab


How to get value from recursive call using dataframe query

Question: I am trying to make this lookup between two tables. With recursive call. But it always returns None. What could be the reasons ?
def checkExchangerate(yearEc,monthEc,dayEc,currCode):
currCodes = {
    'gbp' : 'GBP/EUR',
    'usd' : 'USD/EUR'
}
retVal = exch_rate[currCodes[currCode]][exch_rate['DAGS']==dt(yearEc,monthEc,dayEc)]
print(retVal)
if retVal.empty:
    dayEc = dayEc-1
    checkExchangerate(yearEc,monthEc,dayEc,currCode)
else:
    return min(retVal)

checkExchangerate(1999,1,17,'usd')
returns None.
table exch_rate is pd.DataFrame:
DAGS         USD/EUR   GRP/EUR
1999-1-15      0,66    0,4
1999-1-18      0,65    0,4

expected output is 0,66
Comment: Please add example of the two dataframes you are using and expected output.
Comment: if your Dataframe is exch_rate you can passed it as a parameter on your function :

def checkExchangerate(yearEc,monthEc,dayEc,currCode,exch_rate)
Answer: Please add some sample data to your question.
In your code:
    if retVal.empty:
        dayEc = dayEc-1
        checkExchangerate(yearEc,monthEc,dayEc,currCode)
    else:
        return min(retVal)

If retVal is empty, it will recursively call itself. But when it comes out of recursion, it does nothing with return value, so it returns None.
To fix that, you should return the value that is returned from recursion:
    if retVal.empty:
        dayEc = dayEc-1
        return checkExchangerate(yearEc,monthEc,dayEc,currCode)
    else:
        return min(retVal)

Also, you can replace:
        dayEc = dayEc-1
        return checkExchangerate(yearEc,monthEc,dayEc,currCode)

with
        return checkExchangerate(yearEc,monthEc,dayEc-1,currCode)

However, instead of recursion, I recommend using a loop:
def checkExchangerate(yearEc,monthEc,dayEc,currCode):
    currCodes = {...}
    retVal = False
    while not retVal or retVal.empty:
        retVal = exch_rate[currCodes[currCode]][exch_rate['DAGS']==dt(yearEc,monthEc,dayEc)]
        dayEc -= 1
        print(retVal)
    return min(retVal)

This could cause infinite loop (just as your code could cause infinite recursion), so here's a version with for loop:
def checkExchangerate(yearEc,monthEc,dayEc,currCode):
    currCodes = {...}
    retVal = False
    for day in range(dayEc, dayEc-20, -1):
        retVal = exch_rate[currCodes[currCode]][exch_rate['DAGS']==dt(yearEc,monthEc,day)]
        if not retVal.empty:
           break;
        print(retVal)
    if retVal.empty:
        return some_error_code
    else:
        return min(retVal)

You can change 20 to be a different number. Or use range(dayEc, 1, -1) -- as I suspect that day should never be less than 1
Comment: no does not work.
also the date has to try lower value.
here is what is returned:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Comment: Can you please add some sample data to your question?
Comment: Oops, I just noticed I forgot to subtract 1 from dayEc in my loop. Try now.
Comment: Yes, that was the problem return was missing before checkExchangerate.
Thanks you


Compare many pairs of bools

Question: I am unsure of the terminology of the comparison I would like to make:
if(test1 == true && test2 == true || test2 == true && test3 == true || test3 == true && test4 == true...)
{
   //Do stuff
}

Is there an effective method/function to accomplish this? Otherwise I'm going to have a really long if statement. Any help is appreciated.
Comment: Not if you have them all as variables. If you have alot of bools they should probably be in a list. Otherwise, if-statements can be long sometimes, then just linebreak after each || to make the code more readable.
Answer: You don't have to specify the ==true part. It can be written as follows.
if(test1 && test2 || test2 && test3 || test3 && test4...)
{
   //Do stuff
}

If you want to simplify the expression itself, I suggest you look into boolean algebra and the reduction of boolean expressions.
This is an expression of the form AB + BC + CD + .... One reduction you could perform is as follows.
AB + BC = B(A+C) = B && (A || C)

A list can also be used to store all the different boolean values and one iteration over them can be used to compute this. This helps readability, while performance/memory footprint is almost unchanged or only slightly degraded.
Answer: var tests = new[] { test1, test2, test3, test4, ... };

for (int i = 0; i < tests.Length - 1; ++i) {
   if (tests[i] && tests[i + 1]) {
     // Do stuff
     break;
   }
}

Comment: call me loopy, but this seemed to be efficient enough. Like I said, I had a bunch of comparisons to make...
Answer: You may just use if(test1 && test2 || ...)
or you may break it down into multiple steps
Do you have all separate variables or are they in a array/list
In the latter case, you may iterate them over a loop.
bool result = true;

foreach (bool b  in boolArray)
{
   result = result op b;
}

Answer: You can simply eliminate the boolean comparisons
if( (test1 && test2)) is equivalent to if(test1 == true && test2 == true)
Answer: The shortest I can think of would be this:
if((test2 && (test1 || test3)) || (test3 && test4)) {
    //Do Stuff
}

Answer: If you dont mind put your bool's in a list and use it by linq
e.g.
bool test1 = true;
bool test2 = true;
bool test3 = true;
bool test4 = true;

List<bool> booList = new List<bool>{test1, test2, test3, test4};

bool isTrue = booList.All(b => b == true); //This will return true

bool test5 = false;
booList.Add(test5);

bool isFalse = booList.All(b => b == true); //This will return false

PS: I don't know what would be the performance compare to if statement
Answer: char test[x]

... test[x] init ...

i=0
res=0

while( i < x-2 )
{
    res |= test[i] && test[i+1]
}

Answer: When using C#, you can treat boolean values with logic. :)
if bool1, then buy some ice-cream;
if bool1 does not exist, then don't buy some ice-cream;
when comparing a value to 0, you can use the not operator (!).
if(!bool1)MessageBox.Show("No ice-cream mate");
same goes for when comparing against 0, just don't apply the not operator (!).
if(bool1)MessageBox.Show("ice-cream :D");
Sorry if I made it confusing.
So, to add to the other's posts, the following would be fit.
if(bool1 && bool2 || bool1 && bool3)MessageBox.Show("ice-cream!");
Answer: The LINQ way (assuming that the values are in an array):
bool result = (from index in Enumerable.Range(0, tests.Length - 1)
               where tests[index] && tests[index + 1]
               select index).Any();

Answer: Or would translate to LINQ.ANY if you can put the bool in a list
List<bool> booList = new List<bool> { true, true, true, true };
            bool isTrue = booList.Any(b => b);
            Console.WriteLine(isTrue.ToString());
            booList = new List<bool> { true, true, false, false };
            isTrue = booList.Any(b => b);
            Console.WriteLine(isTrue.ToString());
            booList = new List<bool> { false, false, false, false };
            isTrue = booList.Any(b => b);
            Console.WriteLine(isTrue.ToString());

Compare many pairs of bools


a youtube regex that works but needs improving

Question: I currently have this regex that works successfuly on plain text youtube links.
 /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/

So it works on something like this -->
http://www.youtube.com/watch?v=Y34jC4I1m70

Where it fails however is detecting a youtube link inside an  tag
http://www.youtube.com/watch?v=Y34jC4I1m70

Is there a way i can make it catch both?
Comment: As a general note, regex is a bad approach to markup languages. Use a parser instead, and look for links in the right places.
Comment: Can you show us a code example of how you are using this regex?
Comment: **Don't use regular expressions to parse HTML.  Use a proper HTML parsing module.** You cannot reliably parse HTML with regular expressions, and you will face sorrow and frustration down the road. As soon as the HTML changes from your expectations, your code will be broken. See http://htmlparsing.com/php for examples of how to properly parse HTML with PHP modules that have already been written, tested and debugged.
Answer: Try removing the leading ^.
However I am wondering the .* should work in this case. But why you need a . inside the word youtube?
Comment: Somehow, your regex was working fine in my tests for both the input strings.


A driver operation has been interrupted (mongodb exception)

Question: I am using mongo database for my application
for connection spooling in configured the below mongoOption while creating connection
MongoOptions options = new MongoOptions();
   options.autoConnectRetry = true;
   options.connectionsPerHost = 40;
   options.threadsAllowedToBlockForConnectionMultiplier = 25;

while exceuting my application,getting the following exception
com.mongodb.MongoInterruptedException: A driver operation has been interrupted
at com.mongodb.DBPortPool.get(DBPortPool.java:216)
at com.mongodb.DBTCPConnector$MyPort.get(DBTCPConnector.java:440)
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:177)
at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:155)
at com.mongodb.DBApiLayer$MyCollection.update(DBApiLayer.java:349)
at com.mongodb.DBCollection.update(DBCollection.java:177)
at com.mongodb.DBCollection.save(DBCollection.java:817)
at com.mongodb.DBCollection.save(DBCollection.java:785)
at cherrypick.ck.datalayer.mongo.MongoDataAccessLayer.saveObject(MongoDataAccessLayer.java:361)
at cherrypick.ck.emailinterface.CKMailMonitor.processIncomingMessage(CKMailMonitor.java:170)
at cherrypick.ck.emailinterface.CKMailMonitor.monitorNewMessages(CKMailMonitor.java:253)
at cherrypick.ck.emailinterface.CKMailMonitor.run(CKMailMonitor.java:275)
Caused by: java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos(AbstractQueuedSynchronizer.java:1325)
at java.util.concurrent.Semaphore.tryAcquire(Semaphore.java:414)
at com.mongodb.util.SimplePool.permitAcquired(SimplePool.java:148)
at com.mongodb.util.SimplePool.get(SimplePool.java:110)
at com.mongodb.DBPortPool.get(DBPortPool.java:214)

could any one can help me to solve the issue.
Thanks in advance
 Raja Subramani
Answer: I recently faced this exception. This happens if Thread is already interrupted and you are further trying to do some operation on same thread. I handled this exception by clearing the flag by using Thread.interrupted method of java.lang.Thread
Answer: The same error appear when you open multiple mongodb instances. Be sure that are closing the mongo clients before open a new instance. For example:
MongoClient mongo = new MongoClient ("localhost", 27017);

be sure of do:

mongo.close();

I hope it helps
Answer: I met that problem before, it was caused by the mongo database not your code, so you can enlarge the socket-timeout in your config file or call the dba.
Comment: Provide more detail please (not the call the dba part)
Comment: I use a MongoTemplate, and define the object in xml config file. There is an option for mongo connection, which name is socket-timeout... or you just google "MongoTemplate socket-timeout"
Answer: This can occur when using a small connection pool and overloading it with so many requests that normal functionality cannot occur. For example, I had a connection pool with a max of 10 connections, and fired off 50 requests that would each take over 10 seconds, as well as threads that were checking other mongo collections for work.


Restricting a basis of a vector space $V$ in order to form a basis of a subspace of $V$

Question: We know as a trivial result of Linear Algebra, that given a finite-dimensional vector space $V$ with $\dim V=n$ and $W\subset V$ a subspace of $V$ with $\dim W=k$, $k<n$ we can always extend a basis of $W$ in order to form a basis of $V$ (by associating $n-k$ linearly independent elements to the given basis).
Is the inverse true? And if not, then

Under which conditions can we constraint a basis of a finite dimensional vector space $V$ in order to create a basis of a subspace of $V$?

If for example we consider $\Bbb{R^n}$ and a basis $$B_n=[(1,0,0, \cdots)_1,(0,1,0,\cdots)_2, \cdots (0, \cdots,0,1)_n]$$ and let $\Bbb{R^k}$ with $k<n$ be a subspace of $\Bbb{R^n}$ , it is easy to see that we can constraint $[(1,0,0, \cdots)_1,(0,1,0,\cdots)_2, \cdots (0, \cdots,0,1)_n]$ to a basis of $\Bbb{R^k}$ by chosing the appropriate $k$ vectors from $B_n$.
Can we produce a counterexample where such a construction is not possible?
Comment: For example, consider $W=\{ (t,t): t\in \Bbb R\} \subset \Bbb R^2$.
Comment: @Omnomnomnom Thank you! Simple counterexample that gets the job done.
Comment: I don't think I understand your problem correctly. If $B=\{e_1,\dotsc,e_n\}$ is a basis for $V$, and $k_1,\dotsc,k_m$ are distinct integers chosen from $\{1,\dotsc,n\}$ and $m<n$, then $\{e_{k_1},\dotsc,e_{k_m}\}$ *is* a basis for some subspace.(Linearly independent vectors cannot suddenly become linearly dependent when you throw some away.) On the other hand, given a proper vector subspace $W$ of $V$, we have no reason to expect that $B\cap W\neq\emptyset$.
Comment: @SamM They will be linearly independent but that does not mean that they produce the subspace. Check Omnomnomnom's counterexample and consider a basis of $\Bbb{R^2}$, i.e$(1,0),(0,1)$
Comment: You have misunderstood what I have written. If I take some subset $B'$ of a basis $B$ for $V$ and let $W$ be the linear span of $B'$, then $B'$ is a basis for $W$ (trivially). I followed that with the situation given in the example of @Omnomnomnom. The vector space $W$ generated by $(1,1)$ in $\mathbb {R}^2$ does not even contain the vectors $(0,1)$ and $(1,0)$, so they cannot possibly be a basis. My comment was that the question, as written in the question, is a little ambiguous as it is currently written.
Comment: @SamM I beg to difer: the question seems to me pretty clear and, in fact, it is a standard question in many first years quizzes and exams I've seen.
Comment: As it is written, it could be read: under what conditions does restricting a basis for a vector space $V$ give a basis for a subspace of $V$. To which the answer is always. Alternatively it could be read: Given a vector space $V$, a basis $B$ for $V$, and a subspace $W$ of $V$, under what conditions on $W$ does some subset $B'$ of $B$ form a basis for $W$. Which, as we have seen, is only in a few cases.
Comment: @SamM "under what conditions does restricting a basis for a vector space VV give a basis for a subspace of V.." But the answer is vare rarely-described in the accepted answer below..
Answer: In the most general case, almost never. For example, the standard (or canonical) basis of $\;\Bbb R^2_{\Bbb R}\;$ , $\;\{\,(1,0),\,(0,1)\,\}\;$ cannot be restricted to a basis of no (proper) subspace whatsoever except the two obvious one: the lines (one-dimensional) $\;y=0\,,\,x=0\;$.
Your example about $\;\Bbb R^k\;$ is not so accurate, as you are choosing a very, very special, particular embedding of $\;\Bbb R^k\;$ into $\;\Bbb R^m\;$ . Take instead
$$\Bbb R^k\cong\,\text{Span}\,\left\{\,(1,1,0,...0), (0,1,0,...,)\,,\,\ldots, (0,0,..,\overbrace{1}^{k},0,...,0)\,\right\}$$
and then you have no restriction of the standard basis to a basis of the above subspace.
Comment: @MathematicianByMistake Thank you. The exceptions are really "exceptional": just the span of all the subsets of the basis you chose that yield different subspaces, and that's all. This is very restrictive, in my opinion.
Comment: Thank you! This was quite enlightening. Coupled with Omnomnomnom's counterexample I understand why it fails in the general case. PS It would still be of interest I guess to define these exceptions ("almost never") if they are so rare, right?
Comment: I am quite confused by what you claim above. The first $k$ standard basis vectors for $\mathbb R^m$ are certainly contained within the linear span of $(1,1,0,\dotsc,0),(0,1,0,\dotsc,0),\dotsc, (0,\dotsc,1,0,\dotsc,0)$ that you have above. (For instance, take $(1,1,0,\dots)-(0,1,0,\dots)$.) So the first $k$ vectors from the standard basis for $\mathbb R^m$ do form a basis for the subspace you list.
Comment: @SamM Thank you. **Any** vector is contained in the span of *any* basis in a vector space. That follows trivially from the very definition. In this case, it seems to me the asker wanted that some subset of some basis, in this case the standard one, could be chosen that'd span a given subspace. In my example, there is **no** subset of the standard basis that is a basis of the given subspace isomorphic with $\;\Bbb R^k$
Comment: @Joanpemo The first $k$ vectors from the standard basis *do* span the subspace you defined, hence my confusion. What is true is that if you extend the basis that you specify $\{e_1+e_2,e_2,\dotsc,e_k\}$ above by adding the vectors $e_{k+1},\dotsc,e_n$, then you don't recover the standard basis. But that is not to say that the vectors $e_1,\dotsc,e_k$ do not span the subspace.
Comment: @SamM I think I understand now better what's the problem. Thank you, I agree that some confusion can pop up here.
Comment: Here is a genuine counterexample. Let $e_k$ denote the vector with $1$ in the $k$-th position and $0$ elsewhere (in $\mathbb{R}^n$). Fix $k<n$. Take $f_1=e_1+e_2$, $f_j=e_{j+1}$ for $j=1,\dotsc,k-1$. Then the linear span $W$ of $f_1,\dotsc,f_{k-1}$ is linearly isomorphic to $\mathbb{R}^{k-1}$, does not contain $e_1$ or $e_2$ but does contain an element in the span of $e_1$ and $e_2$. Thus no subset of $\{e_1,\dotsc,e_n\}$ can be a basis for $W$.
Answer: The problem is that given a basis $\{v_1, \ldots, v_n \}$ for $V$ and a subspace $W$ with basis $\{w_1, \ldots, w_k \}$, the basis $\{w_1, \ldots, w_k\}$ can be extended to a basis for $V$, but not necessarily to the same basis $\{v_1, \ldots, v_n\}$ that we had before.


Esconder Botões

Question: Queria uma ajuda com angular, eu uso um ngFor para gerar os botões "-" e "+" que são os botões que dão escolha ao usuário. Dai na hora de escolher as opções tais como o sabor da pizza queria que quando ele clicasse em algum sabor esse botão "+" sumisse.. entende ?
<ion-list *ngIf="varia.eMax > 1">
<ng-container *ngFor="let item of itensVaria">
    <ion-item class="compact" *ngIf="item.idPV == varia.idPV">
      <ion-row no-padding>
        <ion-col col-7 style="text-align: left;">

Descrião do item

        </ion-col>

        <ion-col col-5>
          <button ion-button icon-only clear color="danger" (click)="changeQty(item, varia, -1)">
            <ion-icon name="remove-circle"></ion-icon>
          </button>

          <button ion-button icon-only clear color="danger" (click)="changeQty(item, varia, 1)">
            <ion-icon name="add-circle"></ion-icon>
          </button>
        </ion-col>
      </ion-row>

    </ion-item>
</ng-container>

Mas como são vários sabores e o usuário pode escolher apenas no máximo 3 e no mínimo 2 por exemplo eu queria que ao clicar em x sabor o botão referente a este sabor ficasse indisponível indicando que ele ja clicou neste sabor!
Answer: Seria possível você ter uma variável com os sabores adicionados.:
saboresAdicionados = [];

E colocar no botão um disabled chamnando um método saborJaAdicionado(item)
<button ion-button [disabled]="saborJaAdicionado(item)" icon-only clear color="danger" (click)="changeQty(item, varia, 1)">
 <ion-icon name="add-circle"></ion-icon>
</button>

O método poderia ser da seguinte forma:
saborJaAdicionado(item){
    let achouItem = false;
    this.saboresAdicionados.foreach(e => {
       if (e === item) achouItem = true;
    }
    return achouItem;
}

Dessa forma para cada item ele vai testar se o sabor já está adicionado e fará a liberação/bloqueio do sabor.
Comment: Editei a pergunta dessa forma ai sei fazer, mas some com todos quero que faça conforme o item!
Comment: @SIGAutomação atualizei a resposta
Comment: Não deu certo. da um erro
`Typescript Error
Property 'includes' does not exist on type 'any[]'.`
Comment: @SIGAutomação passei o código errado, sorry. O includes é só pra string
Comment: @SIGAutomação postei o certo ç.ç
Comment: Obrigado ficou muito bom.... agora como faço para mostrar a quantidade referida entre um botão e outro ?
Comment: @SIGAutomação desculpa, não entendi o que você quis dizer com a quantidade referida.
Comment: Exemplo: quando eu clico no botão ele adiciona o item né? Daí queria que ele mostrasse a quantidade de cada item entre um botão e outro. no meu código acima tem uma parte comentada entre os dois botões!
Comment: Vai poder adicionar + que uma vez o mesmo item?
Comment: sim............
Comment: @SIGAutomação se tiver como abre uma outra questão postando o código da tua  função changeQty que fica mais fácil
Comment: ai esta o link da pergunta https://pt.stackoverflow.com/questions/318728/mostar-quantidades-escolhidas

Esconder Botões


R: Error - 'by' must specify a uniquely valid column

Question: I can understand, this may have been answered earlier in some form, but I didn't have any luck with the solutions. Would be great if you could help me with this.
I have two txt files and I want to merge them. The format of the file is as below:
ID|C1|C2|C3

ID1|a|b|c

ID2|d|e|f

Basically, the respective columns in both txt files are separated by "|"
When I am merging the two files using merge, the error message displayed is
'by' must specify a uniquely valid column.
Also please see below the code.
mydata_1 <- read.delim("file_1.txt", skipNul = TRUE, sep = "|", header = FALSE, row.names = NULL)
mydata_2 <- read.delim("file_2.txt", skipNul = TRUE, sep = "|", header = FALSE, row.names = NULL)
merge(x=mydata_1, y=mydata_2, by = "ID", all = TRUE)

Edit - sharing a few lines of actual data for easy reference.
File 1
MS|T1|T2|T3|T4|T5|T6|T7|T8|T9|T10|T11|T12|T13|T14|T15|T16|T17|T18|T19|T20|T21
1|646.25|129.966666666666666666666666666666666667|67.1|19.3|0|281.5|0|227.25|126|0|0|7.5|0|0|10.5|3|0|6|600|NO|2G
2|573.24|91.2666666666666666666666666666666666667|23.0833333333333333333333333333333333333|3.3|3.703466796875|205|0|84.75|36|37.49|210|0|0|0|0|0|0|14|640|YES|3G
3|955.63|1163.93333333333333333333333333333333333|2.11666666666666666666666666666666666667|5.58333333333333333333333333333333333333|0|248|600|8.25|91.88|0|0|7.5|0|0|0|3|0|21|1050|NO|2G
4|906|306.666666666666666666666666666666666667|24.75|7.35|0|663.5|0|123|63|0|0|2.5|0|0|0|1|0|21|1050|NO|2G
5|147.6|29.4833333333333333333333333333333333333|21.45|0|0|75.6|0|63|0|0|0|9|0|0|0|3.6|0|3|150|NO|2G

File 2
MS|T1|T2|T3|T4|T5|T6|T7|T8|T9|T10|T11|T12|T13|T14|T15|T16|T17|T18|T19|T20|T21
1|100346.25|129.966666666666666666666666666666666667|167.1|19.3|0|281.5|0|227.25|126|0|0|7.5|0|0|10.5|3|0|6|600|NO|2G
2|73.24|91.2666666666666666666666666666666666667|203.0833333333333333333333333333333333333|3.3|3.703466796875|205|0|84.75|36|37.49|210|0|0|0|0|0|0|14|640|YES|3G
3|955.63|1163.93333333333333333333333333333333333|2.11666666666666666666666666666666666667|5.58333333333333333333333333333333333333|0|248|600|8.25|91.88|0|0|7.5|0|0|0|3|0|21|1050|NO|2G
4|906|306.666666666666666666666666666666666667|24.75|7.35|0|663.5|0|123|63|0|0|2.5|0|0|0|1|0|21|1050|NO|2G

Comment: Do you want to merge the files on `MS`? What is your expected output?
Answer: You have specified that the file does not contain the names of the variables as its first line by providing FALSE to the argument header in read.delim(). As a result, there is no column ID:
text <- "ID|C1|C2|C3
ID1|a|b|c
ID2|d|e|f"

with header = FALSE there is no column ID:
read.delim(text = text, sep = "|", header = FALSE)

   V1 V2 V3 V4
1  ID C1 C2 C3
2 ID1  a  b  c
3 ID2  d  e  f

with header = TRUE you have the correct headers that are in the first row of your files:
read.delim(text = text, sep = "|", header = TRUE)
   ID C1 C2 C3
1 ID1  a  b  c
2 ID2  d  e  f

Comment: It works with the example data you have provided. you might want to check out this: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Comment: I did try using header = TRUE, but it doesn't work with that.
Comment: I would like to share 5 rows of data of each file so that it's more representative, but the character limit doesn't allow me to - is there a work around?
Comment: I have pasted a few lines of data into the original question - please check
Comment: that's rather easy: both files don't have an `ID` column you might want to change that to `MS` in merge. reading works just fine with `header = TRUE`.
Comment: MS vs ID wasn't the issue here - I pasted just these 5 lines of data into a fresh txt file, and it works - seems to be some issue with the base txt file.


Como centralizar logo brand no Bootstrap 4 e deixar os itens de menu abaixo?

Question: estou realizando um projeto e estou com dificuldade em centralizar o logo e deixar os itens de menu abaixo, de forma que tudo faça parte da navbar e que quando ocorra a quebra para celular tablet, o toggle icon fique na mesma linha do logo, e não abaixo.
Código:

        <button class="navbar-toggler" data-toggle="collapse" data-target="#nav-principal">

        </button>

                 Início

                 A Clínica

                 Tratamentos

                 Promoções

                 Contato

Como eu gostaria que ficasse:
Answer: Você pode criar uma regra de media query quando a tela tiver de 768px pra cima, aplicando flex-direction: column; na div .container. Desta forma, a logo e o menu ficarão alinhados em forma de coluna, um abaixo do outro. Quando a tela for menor que 768px, o menu hambúrguer ficará na mesma linha da logo, pois a div .container não será mais em forma de coluna. Veja:

Não é necessário o
 após o <button>.

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">

           <button class="navbar-toggler" data-toggle="collapse" data-target="#nav-principal">

           </button>

                    Início

                    A Clínica

                    Tratamentos

                    Promoções

                    Contato

Comment: Obrigado, a solução foi muito eficiente e fez o efeito que eu queria com a media!
Answer: Uma opção é na div que vc coloco a classe container, não use essa classe, substitua container por mx-auto e adicione tb a classe text-center. Com isso vc terá o resultado como abaixo. Não precisa de CSS estra ou de @medias para essa opção. Mas seria interessante vc dar mais detalhes de como imagina a responsividade

Segue o código da imagem acima:

<!DOCTYPE html>

<meta charset="utf-8" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />

                <button class="navbar-toggler" data-toggle="collapse" data-target="#nav-principal">

                </button>

                             Início

                             A Clínica

                             Tratamentos

                             Promoções

                             Contato

Comment: Obrigado pelo código, deu certo! Na questão da responsividade quando chegasse nos breakpoints sm e md eu gostaria de tentar alinhar a logo para esquerda e o toggle icon para a direita, ai precisaria utilizar os @medias?
Comment: A solução do rapaz acima atendeu isso que eu queria, mas muito obrigado pela atenção e pela ajuda!
Comment: @IgorPereira talvez seja possível sim, mas vc via ter que dar uma pesquisada nas classes flex da documentação do bootstrap https://getbootstrap.com/docs/4.3/utilities/flex/


Comparing convex functions near infinity

Question: Assume that $f:(0,\infty)\to (0,\infty)$ is a strictly convex and incresing function. Let $p>1$ be a real number and assume that $$\lim_{t\to\infty} \frac{f(t)}{t^p}=0\tag{1}$$
Can I conclude that there is a positive $1\le q<p$ such that if $t$ is big enough then $$f(t)\le t^q \tag{2}$$
I was trying to prove $(2)$ by contradiction. If my calculations are right, I managed to prove that if $(2)$ is not true, then
$$t^p\ge f(t)\ge t^{q_n},\ \forall \ t\ge t_n,\ t_n\to\infty,\ q_n\to p \tag{3},$$
however, I can't see any contradiction with $(3)$. Maybe a counter example?
Comment: The answer is well-known to people working in calculus of variations: the precise growth condition (2) is not equivalent to the limit (1).
Comment: I was expecting this type of comment. Thank you @Siminore
Answer: Consider
$$
f(t)=\frac{t^p}{\ln t}.
$$
Then
$$
f'(t)=\frac{t^{p-1}(p\ln t-1)}{(\ln t)^2},\quad
f''(t)=\frac{t^{p-2}(2+(1-2\,p)\ln t+p\,(p-1)\,(\ln t)^2)}{(\ln t)^3}.
$$
For $t$ large enough $f'>0$ and $f''>0$, so that $f$ is strictly increasing and strictly convex on an interval $[\,T_p,\infty)$. Also
$$
\lim_{t\to\infty}\frac{f(t)}{t^p}=0,
$$
but if $q<p$ then
$$
\lim_{t\to\infty}\frac{f(t)}{t^q}=\infty.
$$


Find a Orthogonal Matrix Q

Question: Assume we are in the real case instead of complex. Suppose $A$ and $B$ have $AA^T = BB^T=C$ where $C$ is non-singular.Show that there is an orthogonal matrix $Q$ such that $A=BQ$.
My attempt is: $AA^T=C$ is symmetric, so by Spectral theorem, there exists orthogonal $Q$ such that $AA^T = QDQ^{-1}$ where $D$ is diagonal. Then since I have got a $Q$ here, I can define $B=AQ^T$ so that $A = BQ$. And it's easy to verify $AA^T = BB^T=C$ with this set-up. However, the matrix $B$ was actually given in the first place. So what I did is probably incorrect. But without assuming $A$ or $B$ is invertible, I really don't see any ways we can come up with such a $Q$.
Thanks so much in advance for any help.
Answer: Hint. $C$ is positive definite. Put $X=C^{-1/2}A$ and $Y=C^{-1/2}B$, we get $XX^T=YY^T=I_n$, meaning that each of $X$ and $Y$ has orthonormal rows. If you can show that $X=YQ$ for some real orthogonal matrix $Q$, then $A=BQ$.
Answer: Write SVDs, $A=U_1\Sigma_1 V_1^T$, $B=U_2\Sigma_2V_2^T$ where the $U$s are $n\times n$, $\Sigma$s are $n\times m$, and $V$s are $m\times m$. Note that $m\geq n$ is a necessary condition for $C$ to be full rank.
Then,
$$
U_1 \Sigma_1\Sigma_1^T U_1^T
= (U_1\Sigma_1V_1^T)(V_1\Sigma_1^TU_1^T)
= AA^T = BB^T
= (U_2\Sigma_2V_2^T)(V_2\Sigma_2^TU_2^T)
= U_2 \Sigma_2\Sigma_2^T U_2^T
$$
What kind of decomposition is on the left and right of the above inequality. What can you say about the uniqueness of this decompostiion, and therefore about the relationship between $U_1$ and $U_2$ and $\Sigma_1$ and $\Sigma_2$?
Now can you relate $A$ and $B$?

Find a Orthogonal Matrix Q


A group, but with the binary operation undefined for some elements. What is this called?

Question: I have in mind a structure similar to a group, but different in that the binary operation is undefined for some pairs of elements. For lack of a better term, call $G$ a restricted group if there is a binary operation $\star:S\subset G \times G \to G$ such that
(1) There is an identity element $e$ such that for all $g \in G$, we have $e \star g = g \star e = g$.
(2) For each $g \in G$ there exists an element $g^{-1} \in G$ such that $g \star g^{-1} = g^{-1} \star g = e$.
(3) For all $f,g,h \in G$ such that $f \star g$, $(f \star g) \star h$, $g \star h$ and $f\star(g \star h)$ are all defined according to the binary operator, then
$$(f \star g) \star h = f\star(g \star h).$$
I imagine this structure must have been studied before and given some name. For instance, I could imagine in robotics there are some physically restricted domains. My particular motivation for asking about this comes from bandaged rubik's cube puzzles, where pieces are glued together.
Comment: How about "incomplete group"?
Comment: https://en.wikipedia.org/wiki/Groupoid#Algebraic
Comment: In your (3), the most common definitions use " if $fg$ and $(fg)h$ are defined, then so are $gh$ and $f(gh)$ and we have $(fg)h=f(gh)$"; at least that's what happens for groupoids
Answer: This is called a groupoid. A naturally occurring example is the fundamental groupoid which has a binary operation when concatenation is possible.


The expectation of the inverse of a negative binomial random variable?

Question: Suppose $X \sim NB(n,p)$ and $\mathbb{P}(X=x) = \binom{x-1}{n-1}p^n(1-p)^{x-n}$.
Then what is $\mathbb{E}(\frac{1}{X}) = \sum_{x=n}^\infty \frac{1}{x}\binom{x-1}{n-1}p^n(1-p)^{x-n}$?
Answer: These negative moments of random variables are in general difficult to obtain closed-form expressions for. You already have $\text{E}[X^{-1}]$ in the form of an infinite series, but what you ultimately want is a representation as a finite sum or product. As I learned from my mentor, sometimes it is possible to get this using the generating function of $X$ as follows.
Let $G(z)=\text{E}[z^X]$ be the probability generating function of $X$. In this case, $X$ is negative binomial which yields
$$
G(z) = \text{E}[z^X] = \Big(\frac{pz}{1-\bar{p}z}\Big)^n
$$
with the short notation $\bar{p}=1-p$. Now observe that
$$
\int_0^1 \frac{G(z)}{z}\text{d}z = \int_0^1 \text{E}[z^{X-1}]\text{d}z = \text{E}\Big[\int_0^1 z^{X-1}\text{d}z\Big]= \text{E}\Big[\frac{1}{X}\Big]
$$
where switching the expectation operator and integral requires some regularity conditions to be fulfilled. I am quite sure in this case they are.
So
$$
\text{E}\Big[\frac{1}{X}\Big] = \int_0^1 \Big(\frac{pz}{1-\bar{p}z}\Big)^n \frac{\text{d}z}{z}
$$
For any finite value of $n$, the integrand is a rational function, so at least in principle it should be possible to integrate this analytically, giving a closed-form result.
Comment: According to [Wolfram Alpha](https://www.wolframalpha.com/input?i=integrate+%28%28%28p*+z%29+%2F+%281%E2%88%92%281-p%29+*+z%29%29+%5E+n%29+%2F+z+dz+from+0+to+1) it contains both gamma and hypergeometric functions: $p\Gamma(n){_2}\tilde{F}{_1}(1, 1;n + 1;1 - p)$ for $\Re(n)>0 \land \Re(p)>0$
Answer: In this paper (equation (3), derived in Appendix A) you can find a closed-form expression for that:
$$
\mathbb E \left[\frac 1 x \right] = \sum_{i=1}^{n-1} \frac{(-1)^{i+1}}{n-i} \left(\frac{p}{1-p}\right)^i +(-1)^n \left(\frac{p}{1-p}\right)^n \ln p
$$
As noted in the paper  (see Appendix A), for $p$ close to $1$ numerical evaluation is easier if the logarithm is replaced by a certain series expansion.
Interestingly, the expression is much simpler (and is obtained more directly; see for example here) if $1/x$ is replaced by $1/(x-1)$:
$$
\mathbb E \left[\frac 1 {x-1} \right] = \frac{p}{n-1}.
$$


How to enable varnish daemon in Cygwin?

Question: I've installed the varnish packages (3.0.2-1 or 2.1.5-1) in cygwin (for local testing of VCL on Win7 64bit) and want to start varnish listening on port 80 but the varnishd isn't available:
<code>$ varnishd -f /etc/varnish/default.vcl -s malloc,1G -T 127.0.0.1:2000 -a 0.0.0.0:80
-bash: varnishd: Command not found.
</code>
so i've installed initscripts and sysvinit packages and reinstalled varnish but still varnishd isn't available!
What additonal packages are necessary to get this running?
Comment: Can you try to use full path? "/usr/sbin/varnishd"?
Answer: My suggestion in comment to use full path to the binary "/usr/sbin/varnishd" helped OP with the issue.
Comment: I've also added PATH="/usr/sbin:${PATH}" to $HOME/.bash_profile - now it's directly accesible.
Comment: Yep, That'd do it. Good Job.

How to enable varnish daemon in Cygwin?


Problemas com colunas no Python XLRD

Question: Sou um iniciante em Python e estou tentando fazer um script para somar todos os valores de uma coluna do excel e escrever o valor da soma na planilha. Estou usando os pacotes Python xlrd e xlwt. O código funciona bem pra primeira coluna, mas a partir da segunda não funciona mais, ele informa sempre valor 0. Espero que alguém mais experiente possa me ajudar.
Obrigado!
import xlwt
import xlrd

workbook_page = xlrd.open_workbook('page_level.xlsx')
worksheet_page = workbook_page.sheet_by_name('Daily External Referrers')
num_rows = worksheet_page.nrows - 1
curr_row = 0
num_cols = worksheet_page.ncols - 1
curr_col = 1
soma = 0

while curr_col < num_cols:
    curr_col = curr_col + 1
    while curr_row < num_rows:
        curr_row = curr_row + 1
        row = (worksheet_page.cell_value(curr_row, curr_col))
        if isinstance (row, float):
            soma = soma + row
        else:
            pass
    worksheet_page.write(num_rows+1, curr_col, soma)
worksheet_page.save('page_level.xlsx')

Answer: Seu problema parece estar na forma de progressão dos loops:
while curr_col < num_cols:
    curr_col = curr_col + 1
    while curr_row < num_rows:
        curr_row = curr_row + 1

Na primeira iteração do loop externo, curr_col passa a valer 1, e então curr_row vai de 0 a num_row através do loop interno. Na segunda iteração, curr_row já é num_rows, de modo que ele nem sequer entra no loop interno!
Pra solucionar você precisa resetar curr_row para 0 antes de começar o loop interno:
while curr_col < num_cols:
    curr_col = curr_col + 1
    curr_row = 0
    while curr_row < num_rows:
        curr_row = curr_row + 1

P.S. Você tem certeza que o que você quer é incrementar o valor da variável primeiro e usá-la depois? Veja bem que o cell_value é baseado em zero, não em um... Por isso, creio que o correto seria:
while curr_col < num_cols:
    curr_row = 0
    while curr_row < num_rows:
        # Seu código...
        curr_row = curr_row + 1 # No __final__ do loop
    # Mais código...
    curr_col = curr_col + 1 # No __final__ do loop

Ou, de forma mais "pitônica":
for curr_col in range(num_cols):
    for curr_row in range(num_rows):
        ...

Answer: Obrigado mgibsonbr!
Eu resolvi da seguinte forma:
while curr_col < num_cols:
    soma = 0
    curr_col = curr_col +1
    curr_row = 0
    while curr_row < num_rows:
        curr_row = curr_row + 1
        row = (worksheet_page.cell_value(curr_row, curr_col))
        if isinstance (row, float):
            soma = soma + row
            sheet.write(0, curr_col-2, worksheet_page.cell_value(0, curr_col))
            sheet.write(1, curr_col-2, soma)
            wb.save('kpis.xlsx')

        else:
            pass

Problemas com colunas no Python XLRD


default routing of custom module

Question: I'm trying to write my first module and am using the hook_menu to route the pages. The module consists of a multi-step form and two static content pages.
/**
 * Implements hook_menu().
 */
function order_menu() {
  $items = array();

  $items['order/form'] = array(
    'title' => 'Order Form',
    'description' => 'Order multistep form.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('order_form'),
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'tpe' => MENU_CALLBACK,
  );

  $items['order/cancel'] = array(
    'title' => 'Order Cancelled',
    'description' => 'Order cancelled.',
    'page callback' => 'order_cancel',
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'type' => MENU_CALLBACK,
  );

  $items['order/success'] = array(
    'title' => 'Order Success',
    'description' => 'Order Successful.',
    'page callback' => 'order_success',
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'type' => MENU_CALLBACK,
  );

  return $items;
}

What I want to do is be able to access 'example.com/order/form' from 'example.com/order' but when I change the menu hook from $items['order/form'] to $items['order'] it displays as page not found.
Any suggestions as to how to how to get the module to display the content I want from example.com/order?
Comment: on /order you want it to display the *same*  form as /order/form or do you want to replace /order/form with simply /order?
Comment: I would like /order to display the same form as /order/form.  I tried to accomplish that by changing /order/form to /order, but I get page not found.
Answer: Did you force Drupal to rebuild the menu, after you changed the code? If you don't do that, Drupal will use the previously defined menus.
To force Drupal to rebuild the menus, you just need to visit the modules page (the administration page showing the list of all installed modules), disable a module, and re-enable it. The last two operations are not strictly necessary; you would probably get the same effect if you click on the "Save" button present on that page without to enable or disable any module at all.
Drupal will call any implementation of hook_menu() and hook_menu_alter(), and it will grab the last menu callbacks defined from your module.
Alternatively, you can call menu_rebuild() from code, or install Devel, which has a block containing a link that allows to force Drupal to rebuild the menu list it caches.
Comment: Install the Devel module, makes working with hook_menu() almost pleasurable :)
Comment: disabling the module and re-enabling it did the trick.  I was clearing all caches, but I guess that doesn't rebuild the menus. Thanks!
Comment: I really suggest installing Devel (or drush, drush cc all *does* rebuild the menu too). Also you don't need to re-enable the module, it is enough if you just submit the module selection form without any changes.
Answer: The problem is that order is not defined as a menu item. An easy way of fixing this would be to include it in the hook menu definition:
/**
 * Implements hook_menu().
 */
function order_menu() {
  $items = array();

  $items['order'] = $items['order/form'] = array(
    'title' => 'Order Form',
    'description' => 'Order multistep form.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('order_form'),
    'access callback' => TRUE,
    'file' => 'order_form.inc',
    'type' => MENU_CALLBACK,
  );

  ...

}

You could use use the MENU_DEFAULT_LOCAL_TASK for the order/form menu item, but I believe it will produce a tab by default, which might not be what you want.
Remember to clear the cache after making these changes.
Comment: double declaration - NEAT! I was going to recommend duplicating the menu item but this is cleverer ;)

default routing of custom module


Limitar o resultado de um valor (SQL SERVER)

Question: No meu SQL tenho a seguinte condição:
CASE
    WHEN MF.Tipo_veiculo = 'M' THEN ((PBI.Peso_bruto - PBF.Peso_bruto) / 9540) * 100
END AS TAXA

Porém, o resultado dessa conta as vezes passa de 100 e eu gostaria de travar em 100 caso ultrapasse, isso é possível?
Answer: Uma maneira de resolver o problema, é utilizando a função least, segue um exemplo:
SELECT CASE
    WHEN MF.Tipo_veiculo = 'M' THEN LEAST(((PBI.Peso_bruto - PBF.Peso_bruto) / 9540) * 100, 100)
END AS TAXA

Repare que ao utilizar a função LEAST, estou passando explicitamente o valor 100, para que no caso de haver valores maiores que 100, então o valor 100 será exibido como um valor padrão.
Comment: Obrigado por responder! Me deparei com esse erro: 'LEAST' is not a recognized built-in function name.
Comment: eu escrevi a query específica para sql-server. que é a tag que está presente na sua pergunta.  @MatheusPrado, junto com a resposta em coloquei um link para a documentação do comando do próprio manual do sgbd.


Manipulação de arquivos C (pular linhas)

Question: Olá, Estou com um problema para pular linhas em um arquivo, eu utilizo o fgets(), mas ele sempre imprime a primeira linha do meu arquivo.

Eu também fiz alguns testes, e por algum motivo, ocorre apenas uma iteração e o x entra no if com o valor do random.

Obs: cada linha do arquivo é sempre < 30 caracteres.
void randInventario() {
    srand(time(NULL));
    int random = rand() % 10;
    nome = new char;
    desc = new char;

    strcpy(parm,"armas.txt");

    FILE* arquivo = fopen(parm,"rt");
    if (arquivo == NULL) {
        cout << "Não foi possível abrir o arquivo." << "\n" << endl;
    }

    int x = 0;
    char text[30];
    while(!feof(arquivo))
    {
      if(x = random)
      {
       fscanf(arquivo, "%s %d %s\n", nome, &dano, desc);
       break;
      }
      fgets(text,30,arquivo);
      ++x;
    }

    fclose(arquivo);
  }

Comment: Já que está usando C++, não use `fgets`, `fscanf`, `fopen`, etc. Usando *streams* já pode ser um grande passo para facilitar o trabalho.
Answer: int random = rand() % 10;

random vai ser 0, ou 1, ou ... 9
  if(x = random)
  {
   fscanf(arquivo, "%s %d %s\n", nome, &dano, desc);
   break;
  }

Este if executa sempre que random seja  diferente de 0. Alem disso atribui o valor de random a x.
Sugestao: liga os warnings do teu compilador e toma atencao ao que eles dizem.
substitui a condicao do if por uma comparacao (em vez duma atribuicao)
if (x == random) ...

Comment: Nossa, pura desatenção. Acabei desligando os warnings por outros motivos e acabei com um problema maior ainda. Obrigado!