While statement not working C

Question: I'm learning C, and I'm trying to make a basic calculator, but having some trouble with the while statements. I've tried doing it multiple ways but it never repeats itself, just finishes the script.
Any ideas?
<code>//
//  main.c
//  Calculator
//
//  Created by Austen Patterson on 2013-06-27.
//  Copyright (c) 2013 Austen Patterson. All rights reserved.
//

#include <stdio.h>
#include <stdbool.h>

int main()
{
    int number[100];
    int operator = '0';
    int doAgainAnswer = '0';
    bool doAgain;
    do{
    printf("Please enter your first number:");
    scanf("%d", &number[1]);
    printf("\nYou entered %d as your first number. Please enter your second: ", number[1]);
    scanf("%d", &number[2]);
    printf("\nYou entered %d as your second number.", number[2]);
    printf("\nYour numbers are now %d and %d", number[1], number[2]);
    printf("\nNow enter your operator.\n1 for addition\n2 for subraction\n3 for multiplication\n4 for division.\n");
    scanf("%d", &operator);

    if(operator == 1){
        int finished = number[1] + number[2];
        printf("\n\n%d \+ %d is: %d", number[1], number[2], finished);

    }
    if(operator == 2){
        int finished = number[1] - number[2];
        printf("\n\n%d \- %d is: %d", number[1], number[2], finished);

    }
    if(operator == 3){
        int finished = number[1] * number[2];
        printf("\n\n%d \* %d is: %d", number[1], number[2], finished);

    }
    if(operator == 4){
        int finished = number[1] / number[2];
        printf("\n\n%d \/ %d is: %d", number[1], number[2], finished);
    }

        printf("\nWant to continue?\n 1 for Yes\n 2 for No\nAnswer: ");
        scanf("%d", &doAgainAnswer);
        if(doAgainAnswer == 1) {
          doAgain = '1';
        } else {
          doAgain = '0';

        }
    }while(doAgain == '1');
}
</code>
Comment: You should strongly consider using a switch case, rather than repeated if statements. http://msdn.microsoft.com/en-us/library/66k51h7a.aspx
Answer: Edited code
<code>#include <stdio.h>
#include <stdbool.h>

int main()
{
    int number[100];
    int operator = '0';
    int doAgainAnswer = 0;//edited
    int doAgain=0;//edited
    do{
    printf("Please enter your first number:");
    scanf("%d", &number[1]);
    printf("\nYou entered %d as your first number. Please enter your second: ", number[1]);
    scanf("%d", &number[2]);
    printf("\nYou entered %d as your second number.", number[2]);
    printf("\nYour numbers are now %d and %d", number[1], number[2]);
    printf("\nNow enter your operator.\n1 for addition\n2 for subraction\n3 for multiplication\n4 for division.\n");
    scanf("%d", &operator);

    if(operator == 1){
        int finished = number[1] + number[2];
        printf("\n\n%d \+ %d is: %d", number[1], number[2], finished);

    }
    if(operator == 2){
        int finished = number[1] - number[2];
        printf("\n\n%d \- %d is: %d", number[1], number[2], finished);

    }
    if(operator == 3){
        int finished = number[1] * number[2];
        printf("\n\n%d \* %d is: %d", number[1], number[2], finished);

    }
    if(operator == 4){
        int finished = number[1] / number[2];
        printf("\n\n%d \/ %d is: %d", number[1], number[2], finished);
    }

        printf("\nWant to continue?\n 1 for Yes\n 2 for No\nAnswer: ");
        scanf("%d", &doAgainAnswer);
        if(doAgainAnswer == 1) {
          doAgain = 1;//edited
        } else {
          doAgain = 0;//edited

        }
    }while(doAgain == 1);//edited
return 0;//edited
}
</code>
Comment: Did that but still not working. It continues the code now and doesn't finish it :P
Comment: Add statement return 0.I have tried it and it is running fine.
Comment: I have added the following code to my continue question and it returns 1 every time. `printf("\nWant to continue?\n 1 for Yes\n 2 for No\nAnswer: ");
        scanf("%d", &doAgainAnswer);
        if(doAgainAnswer == 1) {
          doAgain = '1';
            printf("doAgain saved as %d", doAgain);
        } else {
          doAgain = '0';
            printf ("doAgain saved as %d", doAgain);
        }
`
Comment: There is another oversite in the code.  the line: int operator = '0'; is setting operator = 0x30 hex, not 0x00 hex.  Similar considerations can be given for the instances of '1' and '0' when looking for the exit condition.
Answer: Change the while Condition to
<code>while(doAgain==1)
</code>
And in all the doAgain assingments, use 0 or 1.
Other way would be to use While(1) and break when user enters 0 at prompt in doAgainAnswer.

While statement not working C


Why can I use If Else syntax and not a ternary operator?

Question: Why can I do this?
if (integerList.Direction == "ascending") {
    integerList.Integers.OrderBy(i => i.IntegerValue);
} else{
    integerList.Integers.OrderByDescending(i => i.IntegerValue);
}

But not this?
integerList.Direction == "ascending" ? integerList.Integers.OrderBy(i => i.IntegerValue)
                                     : integerList.Integers.OrderByDescending(i => i.IntegerValue);

It returns the error:
only assignment, call, increment, decrement, await and new object expressions can be used as a statement.

Comment: Because that is not how C# works.  The ternary operator must make an assignment.
Comment: @musical_coder Actually in C# the `==` operator *on `string`* performs a value rather than a reference comparison.
Comment: @rae1n: I remember reading that somewhere once, so I deleted my comment. However, this Microsoft guide discourages that and instead uses `Equals`: http://msdn.microsoft.com/en-us/library/vstudio/cc165449.aspx.
Comment: Actually @musical_coder, the behavior of the `==` operator is the same as the `Equals` method, since [`==` calls `Equals` as it is implementation for the `string` class](https://github.com/mono/mono/blob/master/mcs/class/corlib/System/String.cs). Any discouragement would be based on personal appeal or readability, which can quite subjective (or in your case to avoid confusion as to its behavior). But I'll have to admit I'm getting quite fond of using `Equals`, at least in some cases...
Answer: Because this code makes a call to a given operation (regardless of the branch) which is in itself a statement, thus allowed,
if (integerList.Direction == "ascending") {
    integerList.Integers.OrderBy(i => i.IntegerValue);
} else{
    integerList.Integers.OrderByDescending(i => i.IntegerValue);
}

Using the ternary operator, however, you end up with an expression, which by itself it is not allowed, as it is considered a no-op, except of course, like the error says, it is a new object expression,
integerList.Direction == "ascending"
    ? integerList.Integers.OrderBy(i => i.IntegerValue)
    : integerList.Integers.OrderByDescending(i => i.IntegerValue);

The result of the operation it is not actually consumed, so the entire OrderBy is wasted.
Try this instead,
var intergersOrdered =
    integerList.Direction == "ascending"
        ? integerList.Integers.OrderBy(i => i.IntegerValue)
        : integerList.Integers.OrderByDescending(i => i.IntegerValue);

which turns the ternary operator into an assignment statement.
Answer: The ternary operator in C# is an operator not a statement.  You need to use it in a statement with something to receive the return value.
Read this answer by Jon Skeet.
Answer: Because by definition a ternary operator is an assignment operator, or more accurately a conditional assignment operator. It assigns different values according according to the supplied condition. It doesn't execute statements. While you can definitely unfold any ternary construct into an if-then-else construct, the reverse is not true.
Answer: While the fact remains that the ternary operator is a conditional assignment operator, you could probably still do this
var values = integerList.Direction == "ascending" ? integerList.Integers.OrderBy(i => i.IntegerValue)
                                     : integerList.Integers.OrderByDescending(i => i.IntegerValue);

Answer: An easy way to think about the difference between if-else and the ternary operator:

If-else allows you to decide which block of code will be executed.
The ternary operator helps you decide between two objects or values (of the same type) to use inside a  single statement.

The reason you are getting a compiler error for your ternary operator is because the rules of the language: the Ternary operator returns a value.  But values are used in statements; they are not themselves statements.  Consider:
int x = 1;

// Both these lines are invalid because a string literal is not a complete statement:
"x is an integer";
x < 0 ? "x is Negative" : "x is not Negative";

//Valid:
string intDescription = "x is an integer";
string describeNegative = x < 0 ? "x is Negative" : "x is not Negative";

// Invalid because the ternary operator chooses between values, and Console.WriteLine
// is void:
x < 0 ? Console.WriteLine("x is Negative") : Console.WriteLine("x is not Negative");

// Valid:
Console.WriteLine(x < 0 ? "x is Negative" : "x is not Negative");
// or:
string describeNegative = x < 0 ? "x is Negative" : "x is not Negative";
Console.WriteLine(describeNegative);

Now hopefully you understand the Ternary operator a bit better.  Unfortunately, there's another problem with your code.  Even though this compiles, it doesn't actually do anything:
if (integerList.Direction == "ascending") {
    integerList.Integers.OrderBy(i => i.IntegerValue);
} else{
    integerList.Integers.OrderByDescending(i => i.IntegerValue);
}

OrderBy creates a new object that is an IOrderedEnumerable<YourIntegerClass> and contains the same contents that Integers did, but sorted.  OrderBy returns this new object and leaves your original container unchanged.  This is a relatively common pattern with the Linq extension methods, although most return IEnumerable objects instead of IOrderedEnumerable.
Instead of only making a copy that you don't do anything with, I'm guessing you want to sort the contents of Integers; to do that, you need to assign that result of the OrderBy back to the Integers object:
if (integerList.Direction == "ascending") {
    //I'm guessing that Integers is a List, so I've added .ToList() as well here:
    integerList.Integers = integerList.Integers.OrderBy(i => i.IntegerValue).ToList();
} else{
    integerList.Integers = integerList.Integers.OrderByDescending(i => i.IntegerValue).ToList();
}

Because you are choosing between two values (in this case, for assignment to Integers) you can use the ternary operator:
integerList.Integers = integerList.Direction == "ascending"
    ? integerList.Integers.OrderBy(i => i.IntegerValue).ToList()
    : integerList.Integers.OrderByDescending(i => i.IntegerValue).ToList();


iptables - drop all HTTP(S) traffic but from CloudFlare

Question: I would like to allow only HTTP(S) traffic coming from CloudFlare. In that way attackers cannot attack the server directly.
I know CloudFlare is not mainly a DDoS mitigator, but I would like to try it either way.
I'm currently only having access to iptables (ipv4 only), but will try to install ip6tables soon. I just need to have this fixed soon. (we're getting (D)DoSed atm.)
I was thinking about something like this:
iptables -I INPUT -s <CloudFlare IP> --dport 80 -j ACCEPT
iptables -I INPUT -s <CloudFlare IP> --dport 443 -j ACCEPT
iptables -I INPUT -p tcp --dport 80 -j DROP
iptables -I INPUT -p tcp --dport 443 -j DROP

I know that CloudFlare has multiple IPs, but just for an example.
Would this be the right way?
Answer: Yes, that would work. You can also use ! to negate like this:
iptables -I INPUT ! -s <cloud_flare ip> -p tcp --dport 80 -j DROP
iptables -I INPUT ! -s <cloud_flare ip> -p tcp --dport 443 -j DROP

Comment: Sorry, obviously it's not possible to give many addresses when used with !, you'll have to create multiple rules.
Comment: Ah great, I didn't know about that.
Is it also possible to use that with multiple IPs? I need to accept about 10 IP ranges from CloudFlare.
Comment: From the manpage: Multiple addresses can be specified, but this will expand to multiple rules (when adding with -A), or will cause multiple rules to be deleted (with -D).
Comment: so like:
`iptables -I INPUT ! -s  -p tcp --dport 80 -j DROP`
`iptables -I INPUT ! -s  -p tcp --dport 80 -j DROP`?
Comment: Haha okay, no problem!
Comment: If you found my answer helpful please mark it as accepted answer, so I can get that sweet reputation :)
Comment: Will do, sorry ;)


Gravatar.com showing up in webfilter

Question: We have recently rolled out a web content filter.  I have noticed on many users www.gravatar.com even though these users are not going to this site, nor have any program loaded that would connect to this site.
Anybody know why this would be showing up.  Some google searching has mentioned possibly being attached to emails.
However, at this point, it isn't making sense.
Answer: If your users are frequenting sites who use Gravatar as their avatar provider, like StackOverflow or ServerFault, you'll see a flurry of requests to gravatar.com.
Each question and answer generates a hit for the user profile back to gravatar.
Comment: Just to clarify, OpenID has nothing to do with Gravatars.
Comment: thanks David, modified my answer. I created the mental association somehow, and I misspoke.
Answer: Serverfault and Stackoverflow both use gravatar as their avatar providers.
Answer: Weblogs and sites they are reading uses plugins or query with APIs the gravatar.com website. For example, serverfault.com does.

Gravatar.com showing up in webfilter


Why don't bands try to fade out songs live like they do in the studio?

Question: I am no music expert, but I am a huge sucker for fade out songs (songs which end in a fade out) and I love a lot of them!
I just want to ask: why don't bands try this in live performances?
I am sure with advances in computers and sound engineering, the technical people handling the concerts and live shows can emulate something to preserve the originality of the song by fading out.
So why don't bands try this?  They rehearse a ton, so it should not be a problem for them, right?
I am curious why bands don't try this at all.
P.S.: I hope there will be no arguments as such, I acknowledge that everyone has their taste and I have my taste, which is a genuine love for fadeout songs. I have a tendency for perfection in kind, hence the need to ask this very particularly specific question.
Comment: Fadeouts once meant something, just as  freeze-frame meant something when it appeared in "The 400 Blows," but now it's just an indicator of composers/bands being too lazy to write endings.
Comment: See also this question: https://music.stackexchange.com/q/47854/9426
Comment: As this is seems to be an opinion based question (why...) I very nearly migrated to Music Fans, however there are some excellent answers that show it is definitely on topic here as well. As an aside, when I used to have a covers band, if we were playing a song that had a fade out in the original version, we would create an ending, because fade-outs almost never work in a live gig, either from the performer or audience perspective.
Comment: For a rock band, a proper ending is the signal for the audience to stop what they were doing and start applauding.  If the ending is not totally obvious (long note, hold hold hold, DUM), then the audience will not realise the song has finished and will keep talking loudly.  In the studio, bands will continue to play (and be recorded) for perhaps minutes after the version you hear on a recording as faded out.  In this case, the version you hear is not really the complete song, it's just the edited version.
Comment: *I am curious why bands don't try this at all.*  Some do.  I have experienced many concerts where some of the pieces ended with a fade-out.
Comment: All the answers so far are incorrect. The answer is obviously [because 11 is louder than 10](https://www.youtube.com/watch?v=XuzpsO4ErOQ) ... and 0
Answer: There might be many different reasons for different bands. So I will be able to point just some possibilities.
Studio recording and live performance are different ways to present the songs. Recordings are being listened to in a different way than live songs. Different techniques might be appropriate for each of them.
In particular, at the end of the song the audience wants to clap or otherwise cheer the band. A smooth fade out doesn't really encourage such response.

so why don't bands try this ? they rehearse a ton so it should not be a problem to them , right ?

Note that fade out is normally not done by the band, by playing more and more quiet, but by gradually reducing the volume of the recorded music. It might be quite infeasible to do for a band, especially if they use non-electronic instruments, such as drums.
Moreover, the fade out might not even be directed by the band, but rather by the producer or the sound engineer.

the technical people handling the concerts

...are frequently not members of the band, at least not for smaller bands playing at smaller venues. The sound engineer in a club should know how amplify the band properly at their location, but they typically won't contribute to artistic elements of the performance.

emulate something to preserve the originality of the song

Bands often don't aim to preserve the originality of the song. They rather focus on delivering a live experience, something the audience cannot get from listening to a studio recording. A fade out, especially if directed by someone off the stage would not contribute well for that.
Consider this counterexample to what I wrote:

In this performance musicians leave the stage one by one during the course of the piece. It is very engaging for the audience due to the theatrical aspect, while the musicians remaining on the stage maintain full connection with the audience. This is also very different from a typical "fade out" effect used in studio recordings.
Comment: An _actual_ acoustic fade out in orchestral music is the end of Holst's [Neptune, the Mystic](https://www.youtube.com/watch?v=oFMXNUHuWug). It's implemented by having the choir that sings the final notes in a separate room, and slowly closing the doors!
Comment: @leftaroundabout that's cool! Thanks for this example! But also should be noted that this is a masterpiece that requires extraordinary preparations from the performers and from the venue.
Comment: I remember the brass band when I was in school standing up from their chairs and turning their backs to the audience, revealing signs spelling out F-A-D-E-O-U-T, and then walking off stage while still playing.
Comment: I agree that a fade out is not a very dynamic interaction with the audience in a live performance. An equivalent is to slow down the tempo at the end of a song: most of the time I've seen it done, it was used as a transition to another song without pause/cheers
Comment: @TurePålsson Excellent idea! And again, very different from a typical fade out in a studio recording.
Comment: The real tricky part of this is getting up, while carrying a (potentially heavy) instrument, without knocking over the music stand, scraping the chair on the ground, tripping over the other musicians, etc. while everyone else is still playing.
Comment: See Haydn's "Farewell Symphony"...
Answer: There are two different ways this can be done:
a) The band plays at a quieter and quieter dynamic level, until none of the players can be heard anymore (over the crowd etc. noise).
There are a couple of problems with this:

Playing quieter almost inevitably also changes other aspects of one's playing.What and how exactly depends on the instrument and the music being played. Many classical instruments are quite good at playing at a huge dynamic range, as indeed this happens in orchestral repertoire, but even violins (which are, I think, the most capable in this regard, with bow pressure- and speed being continuously variable from almost nothing to quite marked fortissimo) will have more trouble playing fast rhythmic material at low level without it dissolving into a mushy mumble, because the movements need to be much smaller and more precise.Now, that's not too bad if it's in an ambient accompaniment part and the orchestra is anyway held together by the conductor, but you can't affort to have the drummer in a band lose the rhythm. Even if it happens at already quiet level, it will be obvious and embarrassing.

For most instruments there are also specific technical hurdles. Wind instruments will have trouble getting the tones to speak at the correct register, voices may break to a hush. Guitars and drums are in principle able to play very quietly, but it may require switching to a completely different technique (e.g. pick to fingerstyle, sticks to hands), which is hard to do in a continuous manner and always changes the sound a lot as well as the loudness.The sound thing is an issue even for normal dynamic variations. It's most notable on distorted electric guitar: playing quieter means it will eventually become a clean sound! But other sound issues apply to basically all band instruments.In some cases, the diminiendo can be implemented with the instrument's electronic controls like volume pots on a guitar, swell pedals on an organ etc., but those usually aren't great for very fine, smooth transitions. You may end up taking away too much at some point and thus suddenly completely vanishing from the mix.

As the actual musical signal gets weaker, all noise components will get much more obvious. This includes noise that the audience would probably never have noticed. Again, electric guitar is particularly problematic: the pickups tend to catch a lot of hum-interference. Normally, when not playing, the guitarist will mute the amp or at least switch channels and/or pedal settings, but that's not an option in a played fade-out.

In a live setting, each instrument's signal goes through different processing. Amongst the things often done is dynamic compression, which is specifically designed so even quieter stuff doesn't get lost but still stays audible. That means you need to play even more quiet before the sound is actually gone for the audience. Meanwhile, the noise will get turned up even louder!

Still, a good band can pull this off, but it's difficult, risky, and still won't sound as smooth and uniform as a studio fadeout.
It can be really cool to do this once, but I definitely wouldn't make it more than once during a concert.
b) The sound engineer pulls down the faders whilst the band continues playing at normal (or only slightly reduced) levels.
That's the analogue to how fadeouts were done on old studio recordings (before automatisation became the norm). But again, there are problems doing it live:

Though most of the sound comes from the PA speakers, it's not like the band on stage is completely quiet. In fact, in smaller venues there's always quite a lot of bleed from the stage itself. (The engineer will take that into account during soundcheck, so the mix of stage sound and PA sound is satisfying.) But if you then turn down the PA, you'll be left with only the stage sound, and that will sound very poor in comparison. Not just quieter, but also either thinner or muddier in different parts, uneven, unbalanced. Maybe only cymbals, snare drum and electric guitar in an unpleasant mix. That's not an impression you want to leave at the end of a song.

Even if you manage to get the sound exactly as you want... it'll still come over as just pretty weird when the sound vanishes although the band members evidently still continue to play. The audience might even perceive it as evidence that the band hadn't actually been playing live at all the whole time, but only mimed to playback!

As user1079505 already wrote, the FOH engineer will often not actually part of the band. Even if she's hired specifically by the band, she'll often not have been at the rehearsals, not have a detailed plan for every song but rather just sets up the levels and keeps controlling. And she may be the only engineer, meaning that it could happen something breaks, she needs to run to fix it, the band continues playing thinking they'll be faded out... cluelessness ensues.

Applying to both techniques, the crowd may react funny anyway upon a fade-out. They won't know whether to also get real quiet, when to clap... You may well end up in a situation where most of the room is silent, but a few people didn't notice anything and just continue talking very loudly.
Summary
However you do a live fadeout, it's quite likely to end up being awkward in multiple different ways.
Comment: @Tim why _not_ "she"? — I do use _they_ when I don't know the gender of somebody, but it always leads somewhat ambiguous grammar, especially when there's a "they" in scope for the audience already. — Since the sound engineer is completely fictitious, it surely shouldn't matter what gender I choose? For all you know, I could have flipped a coin to decide between "he" and "she".
Comment: With electric instruments (guitar, bass, keyboards, etc) the artist is primarily dependent upon stage monitoring to hear what they're playing. Yes, an artist can play for a short amount of time without this, but it's uncomfortable. In-ear monitors might be an acceptable solution, but many people don't like them.
Comment: @GalacticCowboy guitar and bass normally don't rely on monitoring, but use onstage amps that the engineer can't control. Many keyboardist also have some kind of amp, though that may be used only for some of their sounds (e.g. Leslie cab for organ but floor monitor for piano).
Comment: That's sometimes true, but not always - we've been playing through DI for a couple years, which sends everything to the board and then back to monitors that are balanced by the sound engineer.
Answer: I have seen bands do fade-outs live, and I have played in bands that did fade-outs live.  So it does happen.
Exhibit A:

Why does it not happen more often?  It's hard to do convincingly, for one thing.  The musicians will need to play softer and softer until they are essentially playing silently.  Most electric instruments have some sort of volume control that makes this possible.  It's trickier for acoustic instruments.  Creating a convincing impression of a fade-out requires good control over dynamics.  Playing very softly on inherently loud instruments (eg drums) is difficult.  So there are technical hurdles to successfully executing a live fade-out.
Additionally, I think it's a bit of a gimmick.  Doing it once in a set is cool.  Each subsequent time will have less and less impact.
Comment: We do this in the big band. It's a gimmick, it makes the audience laugh. It's also hard for the guitars and keyboard, because they have to adjust their volume manually while playing. And of course the trumpets do not like playing anything but high and loud.
Comment: @RedSonja - yeah, but the good thing about volume pedals is they're also accessible to someone else's foot...Really give them something to whinge about.
Comment: @RedSonja - introduce your guitarist, bassist and keyboardist to what's called the *volume pedal*... Which I feel should be part of all those players' armoury anyway. I use one most of the time - specially for keys.
Comment: Could you add something about why live fade-outs are difficult?
Comment: can you link some videos ?
Comment: Answer edited to address comments.
Comment: @Tim They have all kinds of gizmos but they whinge so
Answer: They don't fade out in the studio. They keep playing in the studio.
The engineer just slides the fader. Thus "fade out".
A sound man can do that to a band, if the band has no acoustic drums and go thru D/I instead of amplifiers. Most bands hate playing like that, but sometimes that's what you can do.
But no band wants to be controlled by the engineer like that. They'd rather keep the control for themselves.
Also, that drains momentum, and the performance isn't the song, it's the set, increasing and decreasing momentum and tension.
Answer: It's trivially easy to play a fade-out 'live', particularly if everything is going through a mixing desk.  We don't do it, because the audience need an ending so they know when to applaud.   Audiences LIKE to applaud a song.  They feel cheated if they're not given an opportunity.
When a well-known song ends on a fade, backing tracks made for cabaret singers will often concoct an ending and proudly advertise 'no fade outs!'
A fade CAN be useful to a DJ, allowing them to mix from one track to another.   But it's death to a live performance.
Answer: I don't think I have heard/read from musicians explaining why live fade outs aren't common, but I think you can come to a sensible answer by first asking why bands often play so loud? Of course they play loudly to be heard over the crowd noise.
If the crowd is so noisy that the band plays loudly to begin with, then how will that effect a live fade out? When you are listening to a recorded fade-out at home there are usually no noisy distractions and you can linger on the infinite feeling implied by a fade-out. Recorded fade-outs are really an anti-ending; the song seems to never end.
Now imagine the same thing, but at a live show, and mid-way through a fade-out, the group next to you spills their drink, the person on the other side starts talking on their cell phone, and the guy over at the bar is flexing his beer muscles, etc. etc. The whole effect would be ruined!
That kind of show and distracting audience is very common. But, if the audience is more attentive or participating (usually dancing), then it could work. Although the example that comes to mind isn't a fade out ending, but the "little bit softer now" part of the song Shout. I've seen bands do that song and lead the audience in some participation thing. Because they are involved, there's less distracting noise, the band can fade down low, and there will be actual quiet.
Too often there will be distracting noise and interruptions, so why would bands bother to try live fade outs? I think this is the reason it's not done often.
One other thing to consider: I think the fade out in recordings is less popular now than in times past. I think it was especially popular in the 1970s. I can't quantify that; it's just my sense over about four decades of listening. If I'm right about that, then a lack of interest in live fade-outs in recent times would make sense.
Answer: As an audio engineer (self-taught, but the same skill-set), I can say from experience that the live environment is much different from the studio.  Audience interaction is a big part of that, but one of the greatest technical differences is "stage-bleed".
Lots of instruments have their own acoustic volume that escapes directly into the audience and can't be turned down: uncaged drums with a "cymbal basher" playing them, screaming guitar amps that the musicians refuse to turn down or off, etc.  There are ways to get the same sound into the PA with a silent stage or nearly so, but they're not always accepted.
Thus, the Front-of-House Audio Engineer has an absolute minimum volume coming directly from the stage, that (s)he has to mix around or in some cases drown out.  (like the "pad-slap" from an electric drum kit)  Fading out the PA allows the "stage bleed" to perceptibly take over, and that usually doesn't include enough parts to sound good when the entire band is meant to be amplified.

As a side-note, this stage volume is also a problem for getting good vocals and other things that must use a mic.  Mics don't know what you want; they always pick up everything that happens to be in their designed geometric pickup patterns.  So the choice of mic is not entirely about the tonal quality, but also about the pickup pattern.
There are a few tricks to minimize interference, like putting monitor wedges (speakers on the floor, aimed at the performers and controlled independently from the main PA and usually each other) in the null-point of the most critical mics' pickup patterns; but they're not perfect, like the same monitor reflecting off of something and coming in from a non-null direction for the same mic.
And then we have performers that insist on waving their mics around and/or holding them in a way that covers some of their ports and thus destroys the designed pickup pattern...
So we engineers have another motivation to keep the stage quiet: it makes our jobs SO much easier!  And it allows us to not criticize the talent as much for eating up all of our barely-existent technical wiggle-room with their artistic shenanigans.
In-ear monitors (IEM's) are WONDERFUL!  Essentially a set of earbuds, usually custom-fit, that are controlled in a similar way that the wedges used to be.  However, I have also heard, quite often, a click track (metronome) getting into a vocal mic from a too-loud IEM, so they're not perfect either.
If the stage really is that loud and can't be helped, then the screaming vocals that metal is known for, become necessary from a technical standpoint as well as artistic.
Comment: I wholeheartedly agree with most in this answer... but unfortunately, not much of it is actually on-topic here, and those points have been said before.
Comment: @leftaroundabout I'm providing a different perspective on the same situation (from the technical engineers who actually run the show), with lots of context to really understand it with.  Is that not allowed here???
Answer: For a fade out to really work as an ending to a song, one of two things must happen:

It must be sufficiently complete that there is no identifiable moment when the song ends.  This could be accomplished in a live show with accoustically-silent instruments if the audio fade were combined with a fade-out of the lights that was sufficiently complete that the audience couldn't see when/whether the performers stopped playing (any delay pedals or other equipment with lights that blink the beat would need to be shielded from audience view).  So long as the fade out wasn't extended too much beyond the point where the audience couldn't hear anything, lighting could be used to provide a cue for when the audience should applaud (when the lights come back on and the audience can see that the band isn't playing anymore).

It must be interrupted by the start of something else, an approach that would generally work better in musical theater works where the songs/actions are related, than in a performance of a "stand-alone" song.  Here, the dramatic implication would be that the song and any associated action would have continued for longer than shown, but without anything interesting happening until the action that interrupts it.

In an audio-only recording or a video, the first requirement can be met easily.  In a live concert, however, it might be difficult or impossible to satisfy depending upon the instruments and the venue.  The second form of fade can work well in dramatic works even if instruments cannot play silently or safety lighting would prevent darkness from completely obscuring the stage, but wouldn't be as useful for most concert songs.


Simpler stats for kids: alternative to p-value?

Question: I think most people leave high school with a very limited understanding of basic statistical concepts.  I think part of this is due to the intimidating looking formulas for things like standard error (many sigmas/indexes etc.).
I've always thought it would make much more sense to teach mean absolute deviation when introducing students to quantifying dispersion.  It turns out that I don't think I'm alone, this education researcher seems to feel the same way:
http://sru.soc.surrey.ac.uk/SRU64.pdf
http://dro.dur.ac.uk/12187/
This is easy enough, but it leads to the next obvious question: When a elementary school student is running a simple experiment and comparing means between groups, is there a simpler way the student can quantify the fact that a random sample would (not) likely show the difference they observed?  The p-value would be too complicated to teach the concepts behind and be computationally opaque. I'd like to use Cohen's d, but I can't point to a standard set of effect sizes when using mean absolute deviation so the student can say their differences are "small" or "large".
The idea is that I want the student to see that, say, the differences between their groups may appear small or large; but that argument should be reinforced with a numerical procedure. Maybe something  like comparing the difference between groups to the largest difference within a group? Does anyone have any good ideas?
Comment: This is a very broad and subjective question. Not so easy for the question and answer format here. Anyway what do you think about teaching Bayes Theorem? Or teaching simple laws of probability (not the reverse stuff) like estimating probabilities in card games. This is how it started 200-300 years ago. The binomial distributions and the application by John Arbuthnot in expressing p-values might be a simple expression. See for more links on history and inspiration of "simple" (original/key/fundamental) problems:  https://stats.stackexchange.com/questions/343268/who-first-used-invented-p-values
Comment: I think it is fairly specific, let me try again: I think the mean absolute deviation is a good way to introduce quantitation of dispersion vs. variance. Is there an established way to use mean absolute deviation with other appropriate approximations/heuristics to approximate the p-value (or something like it) in a way that is not opaque in the context of an elementary school student doing an experiment?
Comment: Is that "Is there an established way to use mean absolute deviation with other appropriate approximations/heuristics to approximate the p-value" your specific question?
Comment: Monte Carlo simulations can approximate a p-value. But is it an answer? (that is what I mean by broad and subjective)
Comment: Yes that is the specific question. Monte Carlo simulation isn't a bad idea but perhaps the implementation would be opaque and require an understanding of distribution. I suppose that really just leaves the question to be refined to: Can Cohen's d be used with mean absolute deviation instead of standard deviation and, if so, is there a way legitimately compare one's effect sizes to the standard scale of effect sizes (0.2 = small, 0.8 = big)?
Comment: Is the question whether it *can* be done or whether it *is* simpler to kids? Of course, it can be done.
Comment: I am certain that something like that (that could be done on a spreadsheet) would be simpler to an elementary school child (who understands the notion of 'mean').  The question is, is that valid? It is certainly intuitive (it's still just dividing the difference in means by some combination of the dispersions), but it isn't clear to me how the student can say "I found a d of 0.23, which is considered a small effect in statistics" legitimately this way if they are not using standard error for their measure of dispersion.
Comment: It is valid. When the distribution is a normal distribution then the mean absolute deviation (scaled by $\sqrt{\pi/2}$) is an estimator for $\sigma$. (this alternative cohen's d will not be following a t-distribution, but instead something more exotic, but for large sample sizes it should be well approximated by a z-distribution). Which is better to use is a hot debate. For a start, you can look at ([Fisher 1920,  A mathematical examination of the methods of determining accuracy of observation by the mean error and by the mean square error](http://adsabs.harvard.edu/abs/1920MNRAS..80..758F))
Comment: Ok. Is there a correspondingly simpler estimator for the pooled variance obtained from the mean absolute deviation? If n's are equal, can one use the mean of the two variances?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/91846/discussion-between-mittimithai-and-martijn-weterings).
Answer: If you have a whole class of elementary school students, you could introduce the concept of quantifying randomness of experiments on a more practical level. Say there's 25 students, and one of them has a lopsided coin, while the other 24 have fair coins. Everyone flips their coin $n=$ 5 (10, 15, 20, ...) times and writes down the number of heads. Collecting the results of the 25 students gives you a crude histogram of number of heads, where the one result of the lopsided coin should be among the outlying values, but with low $n$ there's actually the chance that some of the fair coins have the same or even more extreme numbers of heads, while this rate diminishes with increasing $n$.
Of course, this way you would have introduced the $p$-value empirically.


How to add reCaptcha while doing comments on my drupal website

Question: I am developing a drupal website. To avoid spam I have decided to use reCAPTCHA module while user registration and before putting comments on my website.
How to achieve this? Can I use reCaptcha while submitting comments?
Answer: Thank you all, Its done. Procedure as follows :
I have downloaded 2 modules CAPTCHA & reCaptcha.
Then extract them into /var/www/site/modules/ .
Then I have restart my web server. Then goto browser.
Next I have found CAPTCHA and reCaptcha options on modules section.
Then I configured CAPTCHA settings in configuration section according to my requirement.
Thats it !!  When I try to do comment on my website it was given me captcha challenge This is what all i need.
Thanks!! :)
Comment: I don't think restart webserver is mandatory here.
Comment: What am I post in my answer. Is anything wrong. What I post that just download & install & configure it.
Answer: Just download & install reCaptcha module.
Goto Configuration setting & configure it.
Or you can use these modules also. I think this may help you.

Honeypot : They kill 99% of spam.
Mollom
Comment: Samzha, are you sure OP can use this module for submitting comments? If yes please elaborate.
Comment: I think it'll work.
Comment: samzha OP already know about this module. If you are sure about this module then only post this as answer. right now your answer doesn't show any confirmation.
Comment: Ya this modules works.


Parametrizing an algebraic curve

Question: Suppose $C\subset \mathbb{R}^3$ is a path-component of an irreducible real-algebraic curve. Is there a smooth parametrization that covers all but possibly one or two points of $C$? If not, is there a finite collection of parametrizations that cover $C$ collectively? The parametrization doesn't need to be injective as long as it only ever maps finitely many points together.
My best attempt to construct a parametrization would be to construct smooth parametrizations on an open neighborhood of each point where the curve is nonsingular, and then somehow stitch these neighborhood parametrizations together, possible by using Zorn's lemma.
Answer: Just a sketch, showing that the answer is affirmative. Skipping many details.
If the curve is non-singular, then it is a smooth $1$-dimensional manifold ( with several connected components). Each component is analytically diffeomorphic to $S^1$ or $\mathbb{R}$. So you do have parametrizations in this case.
If $C$ has some singular points, then it can be desingularized: there exists a smooth curve $\tilde C $ mapping onto $C$. So now reduce to the previous case.
Comment: @subrosar: If the  curve is irreducible, but singular, then the desingularization is irreducible.  the theory is done by most people for complex curves. The theory for real curves  is a bit more complicated.  So: an irreducible real curve may still have several connected components ( e.g. hyperbola). For complex curves (even varieties) irreducible implies connected ( needs some work to prove).  about parametrizations: in general they are given by analytic functions, but not rational (the functions still have some "structure").  complex vs real algebraic geometry.
Comment: Awesome! I do have one question. A single connected component may become two after desingularization. Can this be avoided when the original curve is irreducible?

Parametrizing an algebraic curve


dictionary from csv file python

Question: I have read a cvs file and I would like to create a dictionary from the information I have on that file. I´ve tried to use class  csv.DictReader to that propose but it didnt gave me the results i wanted.
Now i am reading the file like this:
size_reader = csv.reader(f,dialect='excel-tab')

and I have as result this:
['chr1', '249250621']
['chr2', '243199373']
['chr3', '198022430']
['chr4', '191154276']
['chr5', '180915260']

I would like to make a dictionary with this structure:
dict ['chr4'] = 191154276
dict ['chr5'] = 180915260
dict ['chr2'] = 243199373

I tried regular expressions to split the elements the lines on the file but I had no success with it, maybe i used the wrong characters in the split function. Could you give some suggestion of how to separate the elements and built the dictionary?
Answer: Just convert it to a dict directly:
 result = dict(size_reader)

This takes each two-column result from your size_reader CVS reader and uses that as the key and value for a python dictionary.
To convert each value to integers, you'd need to use a dict comprehension to process each value:
result = {k: int(v) for k, v in size_reader}

Comment: @JonClements: Note to self: `{k: v for k, v in iterable}` == `dict(iterable)`.. Thanks.
Comment: @JonClements: Want to write an answer too? :-P
Comment: sure - but I don't think "See Martijn's answer" is a valid answer ;)

dictionary from csv file python


Cant find the canvas layer node in godot game engine

Question: When i try to find the canvas layer option in my scene it doesn't seem to appear. But all other developers on YouTube seem to have no such problem
Comment: Hi and welcome to stackoverflow. You may find the site [help](https://stackoverflow.com/help) section and this [question](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) checklist useful guidance for asking a good question.  It is easier for people to help you if you include the code that you've worked on to solve the problem and ideally provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
Answer: CanvasLayer is a type of node. If you need it, you would have to add it to your scene.
If you use the "Add Child Node" option from the scene panel (Ctr+A by default) you will get the "Create new node" dialog. It presents a tree with the different type of nodes that Godot has registered.
In the tree of node types CanvasLayer should be directly under Node in the the tree, so not inside the Spatial, nor inside the CanvasItem branch, just down. If you have problems finding a type of node, you can use the search bar at the top of the dialog and type the name of the type of node you want.

Now, it is possible CanvasLayer is not registered. This can be because it has been disabled, or because you have an (unofficial? custom?) build that does not have it.
You can disable nodes from the option "Manage Editor Features" on the "Edit" menu. There you can create, select or remove editor profiles. And on each editor profile you can select what features are available, including the CanvasLayer node type (which should appear there assuming you have an official build). So make sure you don't have an editor profile, or you have an editor profile that has CanvasLayer.


How can I create a custom ajax callback command?

Question: I found different type of ajax commands like htmlCommand, invoke command etc. I want to create a custom ajax command that sets the response of ajax callback as the value of specifying markup in the callback argument. Is it possible? I created one as per this tutorial.
    public function ajax_call_back_function() {
       $response = new AjaxResponse();
       $element  = $form_state->getTriggeringElement();
       $returnDelta = $element['#array_parents'][2]; // get levels
       $delta = $element['#value']; // eg : 944 THis is the ata i want to set as the value of markup
       $response->addCommand(new ReadMessageCommand($delta, $returnDelta));
       return $response;
    }

The ReadMessageCommand class is the following.
    class ReadMessageCommand implements CommandInterface {
      protected $message;
      // Constructs a ReadMessageCommand object.
      public function __construct($message,$level) {
      $this->message = $message;
      $this->level = $level;
      }
     // Implements Drupal\Core\Ajax\CommandInterface:render().
    public function render() {
       return array(
      'command' => 'readMessage',
      'message' => $this->message,
      'level' => $this->level,
     );
   }
  }

I include a JavaScript file.
    (function($, Drupal) {
      Drupal.AjaxCommands.prototype.readMessage = function(ajax, response, status){
      $('#edit-field-region-management-'+response.level+'-valueregion').val(response.message);
     };
    })(jQuery, Drupal);

The controller class is the following.
   class AjaxCommandsAddController extends ControllerBase {
     public function messagesPage() {
       $page[] = array(
         '#type' => 'markup',
         '#markup' => $content,
     );
// Attach JavaScript library.
       $page['#attached']['library'][] = wms_ajax_commands/wms_ajax_commands.commands';
       return $page;
      }
    }

But when executing, I get the following error.

Fatal error: Class 'Drupal\Core\Ajax\ReadMessageCommand' not found in Path-to-module/src/Plugin/Field/FieldWidget/RegionWidgetType.php
Comment: Use  a wrapper element. Where are you calling your ajax_callback_function()?
Answer: It seems like you have a namespace error(s). The error happens in a file you didn't mention RegionWidgetType.php. It's trying to use Drupal\Core\Ajax\ReadMessageCommand which as I understand it is something you made. Which means that the namespace should definitely not be \DrupalCore\... for the auto load to work.
The name space of your custom files should be Drupal\MODULE_NAME\folder\structure


How to Get CA Configured Certifiers names List in domino server programmatically using c#?

Question: To register using new user using CA Process option , CA Configured Certifiers Name is required how can i get that programatically ? I was tried reading documents in ($Certifiers) view in names.nsf file but there is no certifier name available.
Comment: Domino certificates are store in Files. Usualy with extension '.kyr'.
You need to use a tool 'kyrtool.exe' (Must be Domino 9 IF3 or bigger).

I'm not sure they are there but take a look
Comment: Just to get the certifier names i need use kyrtool.exe ?
Comment: sry.. but I don't know.
Answer: There's a hidden view $CertificateAuthorities where all the CA enabled certifiers are listed.
Comment: When i am reading $CertificateAuthorities view i have an entry in it with Certifier FullName is  O=Test. But when i try to register a user using CA Configured Certifier option in that the certifier name is like /Test this. Why both the names are differnet ? How can i derive this /Test name from FullName by just adding / and removing 0= ? is this way of deriving is correct ?
Comment: Notes names are hierarchical (like in ldap). There's a special NotesName class available for handling these conversions.


Idempotents and Factorization

Question: In the ring $\mathbb{F}_2[x]$, let $f(x)$ be a reducible polynomial of degree $n$. If we happen to know that there is a non-trivial idempotent $g$ in $\mathbb{F}_2[x] / (f(x))$, then one of gcd($f,g$) and gcd($f,1-g$) is a proper factor of $f(x)$. Why is this true?
Comment: Hint:Since $g^2 \equiv g \pmod{f(x)}$, therefore $f | g(1-g)$.
Answer: There are a lot of red herrings in this problem. If neither $\gcd(f,g)$ nor $\gcd(f,1-g)$ is a proper factor of $f$, then both are, without loss of generality, equal to $f$. Thus
$$
g=hf\qquad\text{and}\qquad 1-g=kf
$$
for some polynomials $h$ and $k$. Then
$$
1=g+(1-g)=\dots
$$

Idempotents and Factorization


How to relay mail via Google account using Postfix

Question: I want to non local emails to be relayed via my personal Google account and local to delivered to local user.
My configuration is:
/etc/postfix/transport
*            smtp:[smtp.gmail.com]:587

and /etc/postfix/main.cf
[root@media postfix]# cat main.cf
# This file contains only the parameters changed from a default install
# see /etc/postfix/main.cf.dist for a commented, fuller version of this file.
transport_maps = hash:/etc/postfix/transport
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_mechanism_filter = plain, login
smtp_sasl_security_options = noanonymous
smtp_use_tls = yes

/etc/postfix/sasl_passwd:
[smtp.google.com]:587    firstname.lastname@example.com:mypass

And after I run:
# postmap transport && postmap sasl_passwd
systemctl restart postfix.service

So now my server try to connect to gmail MX (without success but not deliver email localy
Logs from journalctl:
    Jul 06 18:38:01 media postfix/pickup[31431]: 30714960F8: uid=0 from=<root>
    Jul 06 18:38:01 media postfix/cleanup[31641]: 30714960F8: message- id=<firstname.lastname@example.com>
    Jul 06 18:38:01 media postfix/qmgr[31432]: 30714960F8: from=<email@example.com>, size=436, nrcpt=1 (queue active)
    Jul 06 18:38:01 media postfix/smtp[31643]: connect to smtp.gmail.com[2a00:1450:4008:c01::6c]:587: Network is unreachable
   Jul 06 18:38:01 media postfix/smtp[31643]: 30714960F8: to=<email@example.com>, relay=smtp.gmail.com[22.214.171.124]:587, delay=0.7, delays=0.03/0.04/0.55/0.07, ...M command))
    Jul 06 18:38:02 media postfix/cleanup[31641]: 0B85D960F9: message-id=<firstname.lastname@example.com>
    Jul 06 18:38:02 media postfix/qmgr[31432]: 0B85D960F9: from=<>, size=2555, nrcpt=1 (queue active)
    Jul 06 18:38:02 media postfix/bounce[31646]: 30714960F8: sender non-delivery notification: 0B85D960F9
    Jul 06 18:38:02 media postfix/qmgr[31432]: 30714960F8: removed
    Jul 06 18:38:02 media postfix/smtp[31643]: connect to smtp.gmail.com[2a00:1450:4008:c01::6d]:587: Network is unreachable
    Jul 06 18:38:02 media postfix/smtp[31643]: 0B85D960F9: to=<email@example.com>, relay=smtp.gmail.com[184.108.40.206]:587, delay=0.59, delays=0.02/0.01/0.51/0.06,...M command))
    Jul 06 18:38:02 media postfix/qmgr[31432]: 0B85D960F9: removed
    Jul 06 18:38:40 media auth[31778]: pam_tcb(dovecot:auth): Authentication passed for media from (uid=0)
    Jul 06 18:38:40 media dovecot[1442]: pop3-login: Login: user=<media>, method=PLAIN, rip=192.168.0.2, lip=192.168.0.7, mpid=31779, secured, session=<VZaXcdrgpADAqAAC>
    Jul 06 18:38:40 media dovecot[1442]: pop3(media): Disconnected: Logged out top=0/0, retr=0/0, del=0/0, size=0
    Jul 06 18:38:58 media postfix/pickup[31431]: CD15D960F8: uid=0 from=<root>
    Jul 06 18:38:58 media postfix/cleanup[31641]: CD15D960F8: message-id=<email@example.com>
    Jul 06 18:38:58 media postfix/qmgr[31432]: CD15D960F8: from=<firstname.lastname@example.com>, size=430, nrcpt=1 (queue active)
    Jul 06 18:38:59 media postfix/smtp[31643]: CD15D960F8: to=<firstname.lastname@example.com>, relay=smtp.gmail.com[188.8.131.52]:587, delay=0.63, delays=0.02/0/0.54/0.06, dsn=5.5....M command))
    Jul 06 18:38:59 media postfix/cleanup[31641]: BAB0E960F9: message-id=<email@example.com>
    Jul 06 18:38:59 media postfix/qmgr[31432]: BAB0E960F9: from=<>, size=2541, nrcpt=1 (queue active)
    Jul 06 18:38:59 media postfix/bounce[31646]: CD15D960F8: sender non-delivery notification: BAB0E960F9
    Jul 06 18:38:59 media postfix/qmgr[31432]: CD15D960F8: removed
Jul 06 18:39:00 media postfix/smtp[31643]: BAB0E960F9: to=<email@example.com>, relay=smtp.gmail.com[126.96.36.199]:587, delay=0.66, delays=0.02/0.01/0.56/0.07,...M command))
    Jul 06 18:39:00 media postfix/qmgr[31432]: BAB0E960F9: removed

Any help to make it working?
Comment: Is that asterisk really in your /etc/postfix/transport, or is it just something that got added inadvertantly to your question?
Answer: You have to enable TLS in Postfix's SMTP client, since Google requires it. This is indicated by them in the message Must issue a STARTTLS command.
In /etc/postfix/main.cf, you want something like this:
smtp_tls_policy_maps = hash:/etc/postfix/tls_policy
and then in /etc/postfix/tls_policy:
[smtp.gmail.com]:587 encrypt
The left hand side in tls_policy must appear exactly the same as your relayhost entry in main.cf.
Remember to run postmap on /etc/postfix/tls_policy after creating or changing it as required.
You can find more details in Postfix's TLS documentation.
Refer these links
http://blog.bigdinosaur.org/postfix-gmail-and-you/
http://www.postfix.org/TLS_README.html#client_tls
Answer: This is the procedure I use for this:
sudo apt-get install postfix.

If it asks what sort of mail server you are installed, choose no configuration (the first option)
sudo nano /etc/postfix/main.cf

and paste this in
# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname
# listen on localhost only
inet_interfaces = 127.0.0.1

smtpd_banner = $myhostname ESMTP $mail_name

biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

#Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

relayhost = [smtp.gmail.com]:587
smtp_use_tls = yes
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous

Save the file, Now we create the file with the username and password in
sudo nano /etc/postfix/sasl_passwd

and paste in the following making the required replacements
[smtp.gmail.com]:587    email@example.com:password

Save it, and at the command prompt
sudo postmap /etc/postfix/sasl_passwd

Then
chmod 600 /etc/postfix/sasl_passwd /etc/postfix/sasl_passwd.db

Finally,
sudo service postfix restart

Note that once you've successfully tested the email system, you can remove / obfuscate the password in sasl_passwd.
Test it with you application. If you have trouble, check /var/log/mail.log
You can apt-get install mail-utils to have it install a mail program. you can then test with
echo "this is a test" | mailx -s "This is the subject" email@example.com

Finally
Run
newaliases

to make an /etc/aliases.db file. If you don't it will log a lot of errors about it to /var/log/mail.err
If you get SASL errors (postfix)
Check the hostname is in /etc/hosts and /etc/hostname
If postfix complains about not being able to relay for a given host / ip address (postfix)
Add this to /etc/postfix/main.cf
mynetworks = 10.0.0.0/8

This will allow anyone with a 10.0.0.0 address to connect, obviously you should bolt this down as much as possible, either by restricting the network, and / or using any firewall or security policy available to you
Comment: My mistake, You shouldn't need that line. I've edited the post above to reflect this
Comment: I got info: : host smtp.gmail.com[126.96.36.199] said: 530-5.5.1
    Authentication Required. Learn more at 530 5.5.1
    http://support.google.com/mail/bin/answer.py?answer=14257 fc7sm2465531bkc.3
    - gsmtp (in reply to MAIL FROM command) - so in such configuration MAIL FROM must be included in relay definition. How can I do it?
Comment: Oh s*&^*t ! In /etc/postfix/sasl_passwd was [smtp.google.com]:587 instead [smtp.gmail.com]:587. Sometimes is terribly difficult to find out such simple error. THX! WORKS!
Comment: OK. THX. But what You use to create/obtain /etc/ssl/certs/Equifax_Secure_CA.pem certificate?
Answer: Firstly, make sure to check first Google's authentication method:
https://www.google.com/settings/security/lesssecureapps
If the page is not available for your account, then the the domain administrator disabled this settings for all users (default).
When you whitelist your IP/range in Relay SMTP in google admin, you can send emails with this settings
relayhost = [smtp-relay.gmail.com]:587
smtp_use_tls = yes
smtp_tls_loglevel=1
smtp_tls_security_level=encrypt
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sasl_mechanism_filter = login, plain
smtp_tls_CApath = /etc/ssl/certs
smtp_sasl_tls_security_options = noanonymous

However, when Allow less secure apps: OFF I was always getting these messages:
(SASL authentication failed; server smtp-relay.gmail.com[126.96.36.199] said: 534-5.7.14
... Please log in via your web browser and?534-5.7.14 then try again.?534-5.7.14
Learn more at?534 5.7.14  https://support.google.com/mail/answer/78754 g133sm1077601qkb.1 - gsmtp)

but messages were still delivered (which is a bit strange), although it took a bit longer to get message to its recipient.


How to name systemd mount unit properly?

Question: I'm trying to automount CephFS after boot via systemd
I've got the next unit:
[Unit]
SourcePath=/etc/fstab
DefaultDependencies=no
After=remote-fs-pre.target
After=network.target
Wants=network.target
After=network-online.target
Wants=network-online.target
Conflicts=umount.target
Before=umount.target

[Mount]
What=ceph-node1:6789,ceph-node2:6789,ceph-node3:6789:/dev
Where=/mnt/cephfs-dev
Type=ceph
Options=name=devuser,secretfile=/etc/ceph/cephuser.secret

[Install]
WantedBy=remote-fs.target

As I know Where= setting must match unit name. I do next:
[root@centos system]# systemd-escape -p --suffix=mount '/mnt/cephfs-dev'
mnt-cephfs\x2ddev.mount
[root@centos system]# vi /etc/systemd/system/mnt-cephfs\\x2ddev.mount

But something went wrong:
[root@centos system]# systemctl status mnt-ceph\\x2ddev.mount
● mnt-ceph\x2ddev.mount - /mnt/cephfs-dev
   Loaded: error (Reason: Invalid argument)
   Active: inactive (dead)
    Where: /mnt/cephfs-dev
     What: ceph-node1:6789,ceph-node2:6789,ceph-node3:6789:/dev

May 05 10:07:12 centos.imoldovan-lpt systemd[1]: mnt-ceph\x2ddev.mount's Where= setting doesn't match unit name. Refusing.

How to name unit properly? Obviously the problem with a dash in mount point /mnt/cephfs-dev but I need exactly this mount point.
Comment: So change the name of the unit to match the mount point.
Comment: The unit is alredy have right name "mnt-cephfs\x2ddev.mount" but I still have got an error
Comment: That's not the name of the unit given in your question!
Answer: To put some closure to this:
The problem was that mnt-ceph\x2ddev.mount was a typo. It should have been mnt-cephfs\x2ddev.mount instead.
Answer: Mount units must be named after the mount point directories they control.
Example: the mount point /home/lennart must be configured in a unit file home-lennart.mount.
Mount]
What=/dev/vdc
Where=/a/b/c
Type=xfs
Unit file name must be "a-b-c.mount", /usr/lib/systemd/system/a-b-c.mount
Comment: This is all true, but it's completely useless to solve the problem.


Nexmo - Undefined method send_message in Rails

Question: I am trying to send an sms using nexmo gem,
The code was working fine up till a couple of days ago.

def send_sms
    @number = params[:number]
    @nannytel = params[:phone]
    nexmo = Nexmo::Client.new(
    key: 'xxxxxxx',
    secret: 'xxxxxxx'
    )

    notification = "The contact number is following #{@nannytel}"

    response = nexmo.send_message(
      from: "SENDERID",
      to: @number,
      text: notification
    )

    if response['messages'].first['status'] == '0'
    flash[:success] = "Yayy!  We just sent you details for the nanny "
    redirect_to root_path
    else
    flash[:alert] = "Uh Oh! Something went wrong, please try entering your number again"
    redirect_to root_path
    end
  end

Above is the method in pages controller
Comment: which version of `nexmo` gem you are using?
Comment: It's the latest one 5.0.2
Answer: Please modify following code
response = nexmo.send_message(
  from: "SENDERID",
  to: @number,
  text: notification
)

AS
response = nexmo.sms.send(
  from: "SENDERID",
  to: @number,
  text: notification
)

above changes are needed as per documentation for version 5.0.2
OR
Use version 4.8 instead of 5.0.2
gem 'nexmo', '4.8'

Comment: Downgrading the gem did the job :)
Thanks a lot Ganesh


(RN) Possible Unhandled Promise Rejection (id: 0): Push Notification

Question: I'm new to React Native. I am sending a link to the app with "push notification". When I tested it, everything works both in the background and when the application is closed. But every time I open the application, I get the following warning. How can I resolve this situation?
WARN  Possible Unhandled Promise Rejection (id: 0):
TypeError: null is not an object (evaluating 'remoteMessage.data')
My codes:

import React, { useEffect } from 'react'
import { Button, Linking, View } from 'react-native'

import styles from './styles/SplashStyles'
import messaging from '@react-native-firebase/messaging'
import { DASHBOARD } from '../navigation/routesNames'

const Splash = ({ navigation }) => {

    useEffect(async () => {

        messaging()
            .subscribeToTopic('users')
            .then(() => console.log('Subscribed to topic!'));

        //Notification caused app to open from background state:'
        messaging()
            .onNotificationOpenedApp(remoteMessage => {
                if (remoteMessage.data.url) {
                    Linking.openURL(remoteMessage.data.url)
                }
            });

        //Notification caused app to open from quit state
        messaging()
            .getInitialNotification()
            .then(remoteMessage => {
                if (remoteMessage.data.url) {
                    Linking.openURL(remoteMessage.data.url)
                }
            });
    }, [])

    return (
        <View style={styles.container}>
            <Button
                title={"Start"}
                onPress={() => {
                    navigation.reset({
                        index: 0,
                        routes: [{ name: DASHBOARD }]
                    })
                }}
            />
        </View>
    )
}

export default Splash
Answer: I think it is because at initialization, the value for remoteMessage is not yet defined when it is rendered specifically via remoteMessage.data, causing the error. If you don't mind introducing a dependency on the lodash package, there's a helper called 'has' that checks if path exists. For example:
if (_.has(remoteMessage, 'data.url') { ....


I have made two template classes,could any one tell me if these things are useful?

Question: Recently i made two template classes,according to the book "Modern C++ design". I think these classes are useful but no one in my company agree with me,so could any one tell me if these things are useful?
The first one is a parameter wrapper,it can package function paramters to a single dynamic object.It looks like TypeList in "Modern C++ design".
You can use it like this:
some place of your code:
int i = 7;
bool b = true;
double d = 3.3;
CParam *p1 = CreateParam(b,i);
CParam *p2 = CreateParam(i,b,d);

other place of your code:
int i = 0;
bool b = false;
double d = 0.0;
GetParam(p1,b,i);
GetParam(p2,i,b,d);

The second one is a generic callback wrapper,it has some special point compare to other wrappers:
  1.This template class has a dynamic base class,which let you use a single type object represent all wrapper objects.
  2.It can wrap the callback together with it's parameters,you can excute the callback sometimes later with the parameters.
You can use it like this:
somewhere of your code:
void Test1(int i)
{
}

void Test2(bool b,int i)
{
}

CallbackFunc * p1 = CreateCallback(Test1,3);
CallbackFunc * p2 = CreateCallback(Test2,false,99);

otherwhere of your code:
p1->Excute();
p2->Excute();

Here is a part of the codes:
parameter wrapper:
class NullType;
struct CParam
{
    virtual ~CParam(){}
};

template<class T1,class T2>
struct CParam2 : public CParam
{
    CParam2(T1 &t1,T2 &t2):v1(t1),v2(t2){}
    CParam2(){}
    T1 v1;
    T2 v2;
};

template<class T1>
struct CParam2<T1,NullType> : public CParam
{
    CParam2(T1 &t1):v1(t1){}
    CParam2(){}
    T1 v1;
};

template<class T1>
CParam * CreateParam(T1 t1)
{
    return (new CParam2<T1,NullType>(t1));
}

template<class T1,class T2>
CParam * CreateParam(T1 t1,T2 t2)
{
    return (new CParam2<T1,T2>(t1,t2));
}
template<class T1,class T2,class T3>
CParam * CreateParam(T1 t1,T2 t2,T3 t3)
{
    CParam2<T2,T3> t(t2,t3);
    return new CParam2<T1,CParam2<T2,T3> >(t1,t);
}

template<class T1>
void GetParam(CParam *p,T1 &t1)
{
    PARAM1(T1)* p2 = dynamic_cast<CParam2<T1,NullType>*>(p);
    t1 = p2->v1;
}

callback wrapper:
#define PARAM1(T1) CParam2<T1,NullType>
#define PARAM2(T1,T2) CParam2<T1,T2>
#define PARAM3(T1,T2,T3) CParam2<T1,CParam2<T2,T3> >

class CallbackFunc
{
public:
    virtual ~CallbackFunc(){}
    virtual void Excute(void){}
};

template<class T>
class CallbackFunc2 : public CallbackFunc
{
public:
    CallbackFunc2():m_b(false){}
    CallbackFunc2(T &t):m_t(t),m_b(true){}
    T m_t;
    bool m_b;
};

template<class M,class T>
class StaticCallbackFunc : public CallbackFunc2<T>
{
public:
    StaticCallbackFunc(M m):m_m(m){}

    StaticCallbackFunc(M m,T t):CallbackFunc2<T>(t),m_m(m){}

    virtual void Excute(void){assert(CallbackFunc2<T>::m_b);CallMethod(CallbackFunc2<T>::m_t);}

private:
    template<class T1>
    void CallMethod(PARAM1(T1) &t){m_m(t.v1);}

    template<class T1,class T2>
    void CallMethod(PARAM2(T1,T2) &t){m_m(t.v1,t.v2);}

    template<class T1,class T2,class T3>
    void CallMethod(PARAM3(T1,T2,T3) &t){m_m(t.v1,t.v2.v1,t.v2.v2);}

private:
    M m_m;
};

template<class M>
class StaticCallbackFunc<M,void> : public CallbackFunc
{
public:
    StaticCallbackFunc(M method):m_m(method){}
    virtual void Excute(void){m_m();}
private:
    M m_m;
};

template<class C,class M,class T>
class MemberCallbackFunc : public CallbackFunc2<T>
{
public:
    MemberCallbackFunc(C *pC,M m):m_pC(pC),m_m(m){}

    MemberCallbackFunc(C *pC,M m,T t):CallbackFunc2<T>(t),m_pC(pC),m_m(m){}

    virtual void Excute(void){assert(CallbackFunc2<T>::m_b);CallMethod(CallbackFunc2<T>::m_t);}

    template<class T1>
    void CallMethod(PARAM1(T1) &t){(m_pC->*m_m)(t.v1);}

    template<class T1,class T2>
    void CallMethod(PARAM2(T1,T2) &t){(m_pC->*m_m)(t.v1,t.v2);}

    template<class T1,class T2,class T3>
    void CallMethod(PARAM3(T1,T2,T3) &t){(m_pC->*m_m)(t.v1,t.v2.v1,t.v2.v2);}

private:
    C *m_pC;
    M m_m;
};

template<class T1>
CallbackFunc *CreateCallback(CallbackFunc *p,T1 t1)
{
    CParam2<T1,NullType> t(t1);
    return new StaticCallbackFunc<CallbackFunc *,CParam2<T1,NullType> >(p,t);
}

template<class C,class T1>
CallbackFunc *CreateCallback(C *pC,void(C::*pF)(T1),T1 t1)
{
    CParam2<T1,NullType>t(t1);
    return new MemberCallbackFunc<C,void(C::*)(T1),CParam2<T1,NullType> >(pC,pF,t);
}

template<class T1>
CParam2<T1,NullType> CreateCallbackParam(T1 t1)
{
    return  CParam2<T1,NullType>(t1);
}

template<class T1>
void ExcuteCallback(CallbackFunc *p,T1 t1)
{
    CallbackFunc2<CParam2<T1,NullType> > *p2 = dynamic_cast<CallbackFunc2<CParam2<T1,NullType> > *>(p);
    p2->m_t.v1 = t1;
    p2->m_b = true;
    p->Excute();
}

Comment: I, for one, would never use a function that returns a pointer which I have to call delete on.
Comment: Questions phrased like "Is this useful?" are going to be subjective and a matter of opinion.  Not a good fit for SO.
Answer: They look useful to me. In the standard library, there is std::tuple and std::function which do similar things.
So, if it's worth having something like this in the standard library, lots of other people probably think being able to write code using patterns enabled by your wrappers is useful.
Comment: If it's in the standard library, then surely you should use the standard library versions instead of reinventing the wheel.
Comment: Maybe... but that wasn't the question. And implementing these yourself is a great way to learn and develop skills.
Comment: Thanks for the advice,but i have to say no one carefully check my classes. My class is very diffrent from std::function,because it has a base class which is not a template,so you can restore 100 diffrent callback objects in a pointer array,like vector. Imaging how could you restore 100 diffrent callback objects through std::function,they are totally diffrent type objects.


State not persisting between functions with useState

Question: I am practicing React useState hooks to make a quiz with a ten second timer per question.
Currently I am able to get the quiz questions from an API, set them to state, and render them. If a user clicks an answer, the question is removed from the array in state, the seconds in state is reset to 10 and the next question renders.
I am trying to get the timer to clear when there is nothing left in the array of questions in state. When I console.log(questions) in the startTimer function, it is an empty array, despite the same console.log showing the data in the userAnswer function? What am I missing here?
I've removed the referenced shuffle function to save space
function App() {

  // State for trivia questions, time left, right/wrong count
  const [questions, setQuestions] = useState([])
  const [seconds, setSeconds] = useState(10);
  const [correct, setCorrect] = useState(0);
  const [incorrect, setIncorrect] = useState(0);

  // Get data, set questions to state, start timer
  const getQuestions = async () => {
    let trivia = await axios.get("https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=multiple")
    trivia = trivia.data.results
    trivia.forEach(result => {
      result.answers = shuffle([...result.incorrect_answers, result.correct_answer])
    })
    setQuestions(trivia)
    startTimer()
  }

  const startTimer = () => {

    // Empty array here, but data at beginning of userAnswer
    console.log(questions)

    const interval = setInterval(() => {

      // If less than 1 second, increment incorrect, splice current question from state, clear interval and start timer back at 10
      setSeconds(time => {
        if (time < 1) {
          setIncorrect(wrong => wrong + 1)
          setQuestions(q => {
            q.splice(0,1)
            return q;
          })
          clearInterval(interval);
          startTimer()
          return 10;
        }
        // I want this to hold the question data, but it is not
        if (questions.length === 0) {
          console.log("test")
        }
        // Else decrement seconds
        return time - 1;
      });
    }, 1000);
  }

  // If answer is right, increment correct, else increment incorrect
  // Splice current question from const questions
  const userAnswer = (index) => {

    // Shows array of questions here
    console.log(questions)

    if (questions[0].answers[index] === questions[0].correct_answer) {
      setCorrect(correct => correct + 1)
    } else {
      setIncorrect(incorrect => incorrect + 1)
    }
    setQuestions(q => {
      q.splice(0,1);
      return q;
    })

    // Shows same array here despite splice in setQuestions above
    console.log(questions)
    setSeconds(10);
  }

  return (

      <button onClick={() => getQuestions()}></button>
      {questions.length > 0 &&

          <Question question={questions[0].question} />
          {questions[0].answers.map((answer, index) => (
            <Answer
              key={index}
              answer={answer}
              onClick={() => userAnswer(index)} />
          ))}

      }

{seconds}

Correct: {correct}

Incorrect: {incorrect}

  )
}

export default App;

Answer: Each render of your App will create new bindings of its inner functions and variables (like questions and startTimer).
When the button is clicked and getQuestions runs, getQuestions then calls the startTimer function. At that point in time, the startTimer function closes over the questions variable that was defined at the time the button was clicked - but it's empty at that point. Inside the interval, although the function has re-rendered, the interval callback is still referencing the questions in the old closure.
Rather than depending on old closures, I'd initiate a  setTimeout on render (inside a useLayoutEffect so the timeout can be cleared if needed) if the questions array is populated.
Another issue is that splice should not be used with React, since that mutates the existing array - use non-mutating methods instead, like slice.
Try something like the following:
// Get data, set questions to state, start timer
const getQuestions = async () => {
  let trivia = await axios.get("https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=multiple")
  trivia = trivia.data.results
  trivia.forEach(result => {
    result.answers = shuffle([...result.incorrect_answers, result.correct_answer])
  })
  setQuestions(trivia);
  setSeconds(10);
}
useLayoutEffect(() => {
  if (!questions.length) return;
  // Run "timer" if the quiz is active:
  const timeoutId = setTimeout(() => {
    setSeconds(time => time - 1);
  }, 1000);
  return () => clearTimeout(timeoutId);
});
// If quiz is active and time has run out, mark this question as wrong
// and go to next question:
if (questions.length && time < 1) {
  setIncorrect(wrong => wrong + 1)
  setQuestions(q => q.slice(1));
  setSeconds(10);
}
if ((correct || incorrect) && !questions.length) {
  // Quiz done
  console.log("test")
}

Comment: You could use `useEffect` above instead of `useLayoutEffect`, the only reason I used `useLayoutEffect` is that it'll run a bit faster when the component is rendered; `useEffect` only runs after a delay. So, `useLayoutEffect` will result in a more accurate timer.
Comment: Apart from the timing issue, in this case, they behave identically.
Comment: It's testing whether at least one of `correct` or `incorrect` is non-zero, which will occur only if the quiz has been started. You could use `null` as an initial value too, if you wanted, but starting at 0 makes things a bit easier to work with, since then you can just add one to it when it comes to scoring.
Comment: Thank you for the response.  I went with the other solution due to being more familiar with useEffect, but I will definitely be looking into useLayoutEffect soon.
Comment: Interesting. I will try this solution as well.  Thanks again.
Comment: This solution is definitely much cleaner and makes more sense than what I initially had.
regarding this part:
`if ((correct || incorrect) && !questions.length)`
Should i then set `correct` and `incorrect` as null initially?   If I'm understanding this part right, it is testing if correct or incorrect are defined and there are no questions left.
Answer: This is because of closure.
When getQuestions executes this part:
    setQuestions(trivia)
    startTimer()

Both functions run in the same render cycle. In this cycle questions is still [] (or whatever previous value it held). So when you call console.log(questions) inside startTimer, you get an empty array.
You can fix that by invoking startTimer in the next render cycle with useEffect
  const [ start, setStart ] = useState(false)

  const getQuestions = async () => {
    let trivia = await axios.get("https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=multiple")
    trivia = trivia.data.results
    trivia.forEach(result => {
      result.answers = shuffle([...result.incorrect_answers, result.correct_answer])
    })
    setQuestions(trivia)
    setStart(true)
  }

  useEffect(()=>{
   if (start) {
    startTimer();
    setStart(false)
   }
  },[start])

Comment: Cool, but @CertainPerformance raised an important point about `setInterval`'s callback which I overlooked. Inside the callback, the `questions` array will always have whatever values `trivia` initially had. This is again because of how closures work. If you just use `setQuestions` is fine, though.
Comment: Thank you for the response and helpful article. I had already been reading up on useEffect so I will go with this solution.


Como criar um link para executar um arquivo ".bat" que fica dentro do diretorio PHP?

Question: Galera, boa tarde!
Seguinte, eu tenho uma página em PHP que fica aberta monitorando um link, eu gostaria de saber como eu faço para colocar um link que abra um arquivo .bat que fica no mesmo diretorio da página...
Exemplo:
"Loja 1 Down - Click aqui" <-- Ao clicar nesse link ele abriria uma BAT que roda no servidor.
Eu não quero fazer isso com o PHP em sí, apenas chamar a BAT pelo Windows mesmo.
:P
Answer: Se preferir da pra chamar via Javascript:
<input type="button" value="Click aqui" onclick="window.open('file:///C:pasta/teste.bat')" />
Comment: esse metodo executaria um arquivo na maquina do usuário, e na pergunta ele quer que rode no servidor.
Comment: é infelizmente até agora não consegui! Isso que você postou faz o download do arquivo, e na verdade eu queria abri-lo! E o que complica ainda mais é o Google Chrome :/

Se alguem tiver sugestões!!!
Answer: Tenta algo assim:
system("cmd /c C:[caminho para o arquivo]");
A função System serve para rodar comando no servidor da aplicação.
Comment: é infelizmente até agora não consegui! Isso que você postou faz o download do arquivo, e na verdade eu queria abri-lo! E o que complica ainda mais é o Google Chrome :/

Se alguem tiver sugestões!!!
Comment: acho que então voce misturou as coisas, da uma olhadinha na função system, ela nao faz download, ela executa algo no servidor


Graph cut size, under Bernoulli edge perturbations

Question: Suppose we have an undirected graph $G(V, E)$.
Perturbed graph: I construct the modified graph $G'(V', E')$ based on $G$. For each node $v \in V$, replace it with new vetices $F(v)$, such that $|F(v)| = k$ (hence |V'| = k|V|). Here is how the edges $E'$ are defined:
For any edge $u \rightarrow v \in V'\times V'$:

if their corresponding vertices in G are connected (i.e. $F^{-1}(u) \rightarrow F^{-1}(v) \in E$),  with probability $p_+$ add the edge: $E' \leftarrow E' \cup \{ u \rightarrow v \}$
if their corresponding vertices in G are NOT connected (i.e. $F^{-1}(u) \rightarrow F^{-1}(v) \notin E$),  with probability $p_-$ add the edge: $E' \leftarrow E' \cup \{ u \rightarrow v \}$

A cut in $G$: A given cut $C=(A, B)$ (i.e. $A \cup B = V$ and $A \cap B = \{\}$) and the size of the cut is denoted with $w(C)$.
Corresponding cup in $G'$: For the given cut $C=(A, B)$ in $G$, define the corresponding cut on $G'$ to be $C'=(\cup_{i \in A} F(i), \cup_{i \in B} F(i))$. Define the size of this cut to be $w(C')$.
A probability distribution over the size of the cuts in the new graph: The goal is to find a probability distribution over the size of the corresponding cuts in $G'$:
$$
P\left( w(C') = \ell | w(C)=\tilde{\ell} \right) = ?
$$
for some $\ell \leq k^2w(C)$.
Answer: Since the edges are modified independent of each other, we can think about them as a Binomial distribution. The tricky part is that, there are two Binomial distributions: $Bin\left(k^2w(C), p_+\right)$ and $Bin\left(k^2(|A||B|-w(C)), p_-\right)$.
$$
P\left( w(C') = \ell | w\left(C\right) = k, C=\left(A,B\right) \right) = \sum_{i = 0}^{\ell} \left[ {k^2w(C) \choose i} p_+^i (1 - p_+)^{k^2w(C) - i} \right] \left[ { k^2(|A||B|-w(C)) \choose \ell - i}p_{-}^{\ell - i} (1-p_-)^{k^2(|A||B|-w(C)) - (\ell -i)}  \right]
$$


Displaying roman character on html

Question: How to write the following roman letter in html  with out using unicode
Φ
Ω
ω

i just pasted it like below

 Φ : phi
 Ω : ohm
 ω :omega

but it is not rendering
Comment: These are Greek letters, not roman. More importantly, they work just fine in HTML, provided that the character encoding is properly declared. The question now contains no hint of what has been done in order to declare the encoding.
Answer: HTML Entities and/or ISO Latin-1 codes can be placed in source code like any other alphanumeric characters to produce special characters and symbols that cannot be generated in HTML with normal keyboard commands.
Phi     Φ       Φ
phi     φ       φ
Chi     Χ       Χ
chi     χ       χ
Psi     Ψ       Ψ
psi     ψ       ψ
Omega   Ω     Ω
omega   ω     ω

source : http://www.utexas.edu/learn/html/spchar.html http://www.degraeve.com/reference/specialcharacters.php

Displaying roman character on html


Compare location data of passes made by two teams in the same game in a coordinate system

Question: I have two sets of data (courtesy of Statsbomb), where each contains the x,y location of where passes occured during a football game as well as the minute of the event for the two different teams. My idea was to visualize this data using heatmaps, in order to get an overview of how each respective team passed the ball on the pitch. My intention was that such an illustration would provide the foundation of asking/answering questions such as;

Where the opponent team prefered to play (i.e how can the opposing focus their resources on putting extra pressure to avoid the opponents from playing as they want)
By splitting the game into four intervalls, can one detect changes of how the game is played throughout the game?

Therefor I have visualized the data in heatmaps containing all the passes as well as based on four time intervalls, where the x,y values are mapped onto a coordinate system
xlim = 0 - 120
ylim = 0 - 80
The number of registered passes (size of data set) vary between the teams, $n_1 = 447$ , $n_2 = 202$.
The time intervalls is the length of each period (1 & 2) divided by two, rounded so they do not overlap. Example period 1: Intervall1 = [0, 24], Intervall2 = [25, 48]
Now I would like to in some way compare the data (not solely based on what I can see with my bare eye in the heatmaps), and analyze the difference between the two teams. I don't have previous experience in doing this, so I would appreciate any suggestions on how I could do this.
The mapped data for the entire game looks like this (arrow indicates attacking direction):
Comment: You shouldinclude some guide for the colors on the maps! Is this for the first interval? One idea to help in comparison, is to switch left/right on one of the figures, so that the attacking direction is the same.
Comment: The colors on the maps goes from 0 (Dark grey-ish) to 1 (Yellow), where yellow indicates a larger concentration of observations - but yes I agree I should include this! The plots above are for the entire game, and the attacking direction is the same for both teams (left to right) as of now, indicate by the small arrow in the top left corner (perhaps I should make it a more distinct color).
Comment: I would be tempted to visualize these data as vector fields (one for each team), where each vector goes from the origin of the pass to where it was completed (next touched or out of bounds).  That would both show all the details while visually aggregating the data and would not rely on some model, as is required by drawing a contour map.  Coloring the vectors by another covariate, such as the time of the pass, its length, whether it was successful, *etc.*, could reveal interesting patterns related to your questions.
Answer: The smoothing introduced in these plots would concern me a little, because there may be important fine-scale patterns that this misses. I would be inclined to begin instead with a hexbin plot, which would show this data well without the need for any smoothing. You can do with in R with the hexbin package or the geom_hex command in ggplot2.


What symbols indicate the major chord, besides the root note alone and "maj"/"major"?

Question: I am making a tab schema, and I was wondering if there was a symbol one could use to refer to the root note's major triad, without reference to the actual note itself.  For example, I believe "C" in a tab refers to the C major chord, C-E-G ( also 1-3-5).
Is there a way one can use to refer to the major chord besides using the root note alone?  Is "maj" or "major" the only one (i.e. Cmaj or Cmajor)? Are there other symbols?
The help would be very appreciated!
Answer: You're correct that C without a qualifier usually implies C major in the context of a chord sheet.  However, you can explicitly indicate it as CΔ, CM or Cmaj.  The triangle/delta is more common in a handwritten context than typed, I prefer it in general, but of course it's up to you.  You won't see it in tabs because they're conventionally written using the ASCII character set, for monospaced fonts.
There are a range of symbols used, but I tend to use the below: they're universally understood, 1 character long, and unambiguous.
Δ major
- minor
+ augmented
o Diminished
ø Half diminished
Alternatively you have, respectively, maj/M, min/m, aug, dim, and m7b5, which are easier to type.
It's worth noting that while C- is commonly used for a minor chord, C+ is used to indicate augmented rather than major.
Comment: I've only ever seen `Δ` in reference to major/major seventh chords. Is it used for triads, too? (I legitimately don't know.)
Comment: @Richard It's common to not explicitly indicate major chords, and just write "C" or whatever. On on a sheet following that convention, you'll only come across Δ when representing a specific voicing (CΔ7 for example).  Personally, I prefer explicit major indication, especially in a minor tune. Also, I didn't want to overcomplicate the answer, but Δ and - are generally used to indicate a major/minor "flavour" in jazz sheets; how you interpret depends on the music context (and ultimately, you). So Δ could be played as Δ7, 6, 6/9 chord for example, and "-" could be -6,-7,-9 etc. (or as triads)
Answer: I think this is the beginnings of what you want (although I'm using notes rather than tab).
Comment: I am sorry if I was unclear, but I wanted a comprehensive list of shorthand symbols like what @Some_Guy indicated.   Thanks for answering anyway.
Answer: "C" and "Cmaj/Cmajor" are the usual ways to do it in tablature/lead sheets, but in music theory annotation, it's fairly common to write "C" for C major (which is the same as the above) and "c" or "Cm" for C minor, or even "C+" for C major and "C-" for C minor. (Edit: I now suspect the latter was the idiosyncratic notation of one of my profs.)
This is for English; other languages have their own conventions, like "Des Dur" in German for D flat major.
Comment: C+ is never C major. It's always C augmented. Unlike the opposite C- which is always C minor, never C diminished!
Comment: If an academic musician decides to re-assign 'C+' to mean 'C major' he is being very foolish.  He doesn't (or shouldn't) have the excuse of ignorance of real-world practice.
Comment: Really?  People actually write 'C+#5'?
Comment: "Never" is a bold claim. I studied music theory in university and it was pretty common while annotating music. Not for performance, but OP didn't specify that.
Comment: I'm stating from the Western world perspective, having *never* seen + to mean major in 60 yrs of playing and teaching. Perhaps in Canada it's different. If so, how did your lecturers denote C augmented?
Comment: @Tim, that would be C+#5.
Comment: @prooffreader - Googled it - nothing at all comes up.
Comment: google is crap for things like like this, anything punctuation or diacritic based gets filtered out.  I've never seen this notation before but it doesn't mean it doesn't exist.  Having said that, proofreader, where did you see this??
Comment: I'm Canadian and learned lots of music theory with the Royal Conservatory of Music syllabus, and I also learned that C+ is C major and C- is C minor (at least in a classical context). Then again, I also learned that Cx is C augmented and C° is C diminished from the same source. I forget which source it is, though.
Comment: I think I'm going to walk this back. This is going back 20 years ago in University, and I'm starting to think it was the idiosyncratic notation of one teacher I had for four courses.
Comment: @Dekkadeci - Cx could be confused with C##, although I can't think of a place where a chord would be Cx instead of D.


Accessing parent parameters from child package SSIS 2012

Question: I know this subject has been covered here several times but I could not get any of the answers worked for my problem.
I have 7 packages running in a Master Package and 7th child has 3 parameters. To be able to let user define those 3 parameters, I have to ask and get them during master package run so master package needs to pass them to package number 7 that is running under it. I have the same set of 3 parameters defined in child package as well as the master but could not pass them down for some reason.
Comment: I think I found my answer and want to share it here in case somebody else needs the exact same answer: 3 parameters defined in master package level are to be mapped in execute package task editor that is used to run the 7th child package under the master. To do that, go to execute package task editor of 7th child package and go to Parameter Bindings. There, for each Child Package Parameter (those are the parameters defined in the child package) enter Binding Parameter or variable by selecting it from drop down (they are available as soon as created in master package level)
Comment: Post this as an answer and mark it as solved, so that others may find it in the future more easily.
Answer: I think I found my answer and want to share it here in case somebody else needs the exact same answer: 3 parameters defined in master package level are to be mapped in execute package task editor that is used to run the 7th child package under the master. To do that, go to execute package task editor of 7th child package and go to Parameter Bindings. There, for each Child Package Parameter (those are the parameters defined in the child package) enter Binding Parameter or variable by selecting it from drop down (they are available as soon as created in master package level)


Groups with the same amount

Question:
Let there be an array of digits $ [0,0,1,1,2,2,\ldots,9,9] $, how many ways to split this array into two subarrays, so that the sum of numbers in the subarrays is different by a multiple of $11$?

This problem has arisen through the solution of some other problem, so I do not cite my attempts at solution. I will be glad to any help.
P.S. If it is difficult to calculate manually, then I will be glad to see an effective algorithm.
Comment: First of all, note that if $A > B$ are the sums of the elements of the two subarrays, then $A+B = 90$ and $A-B = 11k$  for some $k$. Subtracting, we get $2B = 90 - 11k$, so $k$ better be even i.e. $k = 0,2,...$. Thus, $B$ can be equal to $45,34,23,12,1$. So you are reduced to the question : how many subarrays have sum $45,34,23,12$ or $1$. This seems easier  than the given problem.
Comment: Also, if you get a subarray with no $0$, you can adjoin one or two zeros without changing the sum, so you can eliminate the two zeros, and multiply the answer by $3$.
Comment: Does order matter here? I.e. is $[1], [0,0,1,2,2,\ldots,9,9]$ the same as $[0,0,1,2,2,\ldots,9,9],[1]$, or are those two different splits? Also, most of the time when I encounter the word "array", the order of the entries _within_ the array matters. Is that the case here?
Comment: Order is important.
Answer: I assume that we have eliminated the $0'$s, in line with my comment.
Following up астон вілла олоф мэллбэрг's observation, I think a good way to approach it is to figure out all the subarrays that sum to $11$.  Then we successively compute the subarrays that sum to $1$, $12$, $23$ etc.  We know that there is only subarray that sums to $1$.  We can adjoin any of the subarrays that sum to $11$, unless that results in a subarray with more than $2\ 1'$s, to generate the subarray that sum to $12,$ and so on.
I can't see a way to compute the number without constructing the subarrays.

Groups with the same amount


How to display a table view and an add/edit form on the same page?

Question: I'm trying to build a page in my site where users can create a new project (fill out a few text boxes to give the project a title/description), see a list of all of their projects, and edit any of those projects.
I've created a new content type called "Projects" that includes all the text fields needed for creating a new project. And I've figured out how to use Views to display a list of user projects. I've tried to display these 2 elements together using Panels, but that means I need to create a new Variant for both the Node View and the Node Edit pages, which feels clumsy in terms of development. And the end result on the web site is 3 slightly different pages (one to create a new project, one when you click on a particular project to view it, one when you edit the project). But ideally, it would feel like one slick page.
Am I taking the right approach with using Panels, or is there another module or approach that is better?
Comment: Hello Erin, and welcome on _Drupal Answers_. To which Drupal version are you interested?
Comment: I'm using 6 right now.
Answer: Hey Erin, certainly a good way to build customized pages is use Context module instead of Panels... (Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context. Link: Context).
In addition of that, you can create a block (be sure to have PHP Filter enabled), and include the following code.
For a existing node edit form:
<code>//you should have your nid (May be loaded by a custom arg or even a given GET variable)
$nid = 99;
$node = node_load($nid);
//load needed file from node module
module_load_include('inc','node','node.pages');
//load node edit form
$form = drupal_get_form($new_node->type . '_node_form', $node);
//print the form you have loaded
echo($form);
</code>
In case you want to load a fresh node add form, instead of loading a node with node_load, you should create a stdClass object, and give the type name just as bellow:
<code>//load the current user info
global $user;
//empty object for node
$new_node = new stdClass();
// your machine name content type
$node->type = 'page';
// set the author for the node to be created
$node->name=  $user->name;
//load needed file from node module
module_load_include('inc','node','node.pages');
//load node edit form
$form = drupal_get_form($node->type . '_node_form', $node);
//print the form you have loaded
echo($form);
</code>
Actually it may not be the best way to do that, but certainly is a functional method.
Comment: Good point. Worked for me. tks