How do I use Nested For Loop in this question? (Without Arrays)

Question: The question is from the Nested For Loops chapter, so I assume that I should use Nested For Loops for this.
In an entrance examination, students have answered English, Maths and Science papers. Write a program to calculate and display average marks obtained by all the students. Take number of students appeared and marks obtained in all three subjects by every student along with the name as inputs.
And this is my code:
import java.io.*;
class average
{
public static void main(String args[]) throws IOException
{
    InputStreamReader read = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(read);
    int i,j,m,s,e,sum;
    String name;
    double a;
    System.out.println("Enter number of students that appeared");
    int n = Integer.parseInt(in.readLine());
    for(i=1;i<=n;i++)
    {
        System.out.println("Enter name");
        name = in.readLine();
        System.out.println("Enter marks obtained in English");
        e = Integer.parseInt(in.readLine());
        System.out.println("Enter marks obtained in Maths");
        m = Integer.parseInt(in.readLine());
        System.out.println("Enter marks obtained in Science");
        s = Integer.parseInt(in.readLine());
        sum = e + m + s;
        a = sum/3.0;
        System.out.println("Average Marks = "+a);
    }
}
}

So how do I exactly use Nested For Loop with this? Have I misunderstood the question? If so, then what should I do?
Comment: @NicholasK Well I just assumed that I _need_ to use Nested For Loop because its from that chapter. If I don't need to use it, then I've got no problems in all honesty.
Comment: I think perhaps you are imagining the wrong interaction. I think what the exercise meant was an interaction like this "Enter number of students" (`8`). "Enter name" (`Andrew`). "Enter marks in all three subjects" (`89 56 72`). This means you have to *loop* over the three marks to sum them up. Imagine if you had 20 subjects. Would you still put the marks in 20 different variables?
Comment: You don't need a *nested* loop here. Maybe  you can use a *collection* or an *array* to store the information of all the students.
Comment: I don't see anything in the question requiring you to use a nested loop.
Comment: @NicholasK Well I have not yet learnt of those. The chapter in which this question is given is Nested For Loops, so I assume that I should use a Nested For Loop.
Comment: @Bjarke Well I have not yet learnt of those. The chapter in which this question is given is Nested For Loops, so I assume that I should use a Nested For Loop.
Comment: @CodeLearner - That does seem like a reasonable assumption. :-) I'd use the "edit" link to add that information to the question.
Comment: Also curious here, what's wrong with you current code? It does find the average of each student and displays it. Or do you want to find the average by *each* subject? Specifically what *average* do you want to calculate?
Comment: @NicholasK The only problem in here is as stated, not being able to use Nested For Loop, and I assume I should use Nested For Loop as this question is from the chapter of Nested For Loops.
Comment: Well if you have achieved the target without nested for-loops, then you don't need it I guess.
Answer: I think you should not use nested loop in the code snippet. You should split it with two parts: receive student's data and pring student's data.
First, define a class that represents student's score:
public final class StudentScore {

    private final String name;
    private final int scoreEnglish;
    private final int scoreMaths;
    private final int scoreScience;
    // TODO a put this parameter hered, but probably it's is better to calculate id every time when required
    private final double avg;

    public StudentScore(String name, int scoreEnglish, int scoreMaths, int scoreScience) {
        this.name = name;
        this.scoreEnglish = scoreEnglish;
        this.scoreMaths = scoreMaths;
        this.scoreScience = scoreScience;
        avg = (scoreEnglish + scoreEnglish + scoreEnglish) / 3.;
    }

    // getters
}

Second, define a method that use Scanner (this is more useful that InputStreamReadr when working with console) to receive amount of students and student's data:
private static List<StudentScore> getStudentsScore() {
    try (Scanner scan = new Scanner(System.in)) {
        System.out.print("Enter number of students that appeared: ");
        int total = scan.nextInt();

        List<StudentScore> studentScores = new ArrayList<>(total);

        for (int i = 0; i < total; i++) {
            System.out.print("Enter name: ");
            String name = scan.nextLine();

            System.out.print("Enter marks obtained in English: ");
            int scoreEnglish = scan.nextInt();

            System.out.print("Enter marks obtained in Maths: ");
            int scoreMaths = scan.nextInt();

            System.out.println("Enter marks obtained in Science");
            int scoreScience = scan.nextInt();

            studentScores.add(new StudentScore(name, scoreEnglish, scoreMaths, scoreScience));
        }

        return studentScores;
    }
}

Third, all you left to do is just receive list of student's data and pring required parameters:
List<StudentScore> studentScores = getStudentsScore();
studentScores.forEach(studentScore -> System.out.format("Average Marks for student '%s' is '%.2f'\n", studentScore.getName(), studentScore.getAvg()));

P.S.
It is not pretty clear what exaclty average score should you calculate, but when you receive List<StudentScore> studentScores, you can calculate all you need.


Solid of Revolution Issue

Question: I need to create a solid of revolution for an ice cream cone. Will these 2 equations do it or will the gap between them cause a problem? Thanks.
$y=\frac{x}{2.5}\left\{0\le x<6\right\}$
$y=\sqrt{-\left(x-6\right)^2+4}\left\{6\le x<8\right\}$
Answer: Even though it's a disconnected curve, that won't affect the volume for the solid of revolution. This is because, with respect to the volume, the discontinuity is of "measure zero". That means, in this case, "an ultra-thin piece of paper has no volume." In other contexts, it means "A point has no length" or "a line has no area".
Note that this does not work with the surface area. Even if you set up the integral for the two curves to find surface of revolution, you would be missing the washer-like area between the cone and the ice cream, with outer radius $2.4$ and inner radius $2$.
Comment: Just calculate surfaces of revolution separately, and then add the "washer" area.
Comment: How could I fix the surface area issue? I don't want to overcomplicate the equations.
Comment: So it would be $2\pi\int_0^6(\frac{x}{2.5})dx + 2\pi\int_6^8(\sqrt{-2(x-8)})dx +$ the donut-disc here? Doesn't the second integral already include the small radius circle, so would I just add $5.76\pi-4\pi$?

Solid of Revolution Issue


Intel NIC teaming or server 2012 R2?

Question: I'd like to implement NIC teaming on one of my servers and would like to know if it's better to use the Intel NIC teaming from the drivers or to use the NIC teaming from Windows Server 2012 R2.
Answer: Definitely windows server 2012 teaming. Remember if your objective is to maximize throughput you should use LACP, this implies that you have also to configure your switch to accept LACP negotiation.
Else if you prefer "switch indipendent teaming" the server will use both nic in send direction but, in recive direction, the server will use only one nic the other will be just failover.
If you want more, and you like to go deep:
http://www.aidanfinn.com/?p=13984

Intel NIC teaming or server 2012 R2?


Chrome border-radius is ignored when child element uses relative positioning

Question: I am working on a project that utilizes a circular div laying over images to create a sort of looking glass effect, where you can drag an image around within the circular div.
The markup for the app is as follows:

jQuery autopopulates the nav object with numbers that fade out the current images and fade in whichever is clicked.
Here is the Sass code for the object as well
@mixin border-radius($size)
    border-radius: $size
    -webkit-border-radius: $size
    -moz-border-radius: $size

.looking-glass
    display: block
    height: 100%

    .looking-glass-nav
        li
            display: inline
            padding: 5px

    .looking-glass-images
        overflow: hidden
        display: block
        height: 500px
        width: 500px
        @include border-radius(50%)

        img
            -webkit-user-select: none
            -moz-user-select: none
            user-select: none
        img.active
            display: block
        img.inactive
            display: none

When I impose the draggable effect on the images they are given a relative position style and for some reason that stops the div containing the images from being roundable.  Is this a bug in Chrome or is there something I am doing wrong here?
Comment: Im looking for an answer to a very similar problem as well. For me it also happens in Safari. Have you managed to find an answer yet? +1
Answer: May this can help you
The right way to write vendor prefixes is to put nonvendor property name on the last position,  like this way:
-webkit-property: value;
   -moz-property: value;
    -ms-property: value;
     -o-property: value;
        property: value;


What are the primary (or most common) chords of the minor scale?

Question: I'm trying to figure out what chords appear most often in minor scales, in major scales it's easy: the I IV and V, it's not even a question. You can harmonize almost any major song with just these chords.
But what would you say are the primary chords in the minor scale . I looked it up and most are saying the i iv v (since minor notes are supposed to function just like in the major scale).
But in practice I dont find this is the case. In natural minor the "v" doesn't have a strong resolve to the "i". and most songs I played don't really use the v. one thing I noticed is that songs tend to use the VII quite alot. (I'm talking chords here).
So if the primary chords in major are I IV V, what are the minor equivalent?
I'm not necessarily talking strict theory I'm talking about practicality and what appears the most in songs from your experience. currently I'm leaning towards the I IV VII but I am still researching this.
Comment: Can you elaborate on what you mean by primary? Do you mean most important, best-sounding, most commonly used, etc.? I would think the answer to this question depends on the particular genre you're thinking of.
Comment: Also, this might be useful: https://music.stackexchange.com/questions/58290/what-chords-count-as-diatonic-in-minor
Comment: @jdjazz I'm not sure how this is in minor scales. but in major scales we have the tonic, subdominant (4th), dominant (5th). and almost always these are the only chords needed to harmonize a melody. the 4th is almost always the chord I use (apart from the 1). and the 5th usually an ending harmony that leads back to the 1. looking for the same in minor. the weird thing in minor I found sometimes the V is major or minor depending on the type of minor scale. so I'm confused...
Comment: Highly related (maybe a dupe): https://music.stackexchange.com/questions/16248/understanding-minor-key-harmony
Answer: It's still 1, 4 and 5, but with a subtle change. i and iv are standard, but v can be V. In Am, for example, i=ACE, iv=DFA, and v=EGB. V=EG#B sometimes, as in the harmonic and melodic minor scales, G# features, whereas in natural minor (and descending classical melodic) minor, there's Gnat.
It's unusual to call the chords with reference to the relative major, as in vi, ii, and either iii or III.
Comment: modifying the natural minor scale to have a major V chord, which subsequently raises the 7th degree of the scale (leading tone) is the definition of Harmonic Minor scale.
Comment: Compositionally, usualy both Harmonic and Melodic versions of minor are used simultaneously, where the raised leading tone may be used melodically to resolve to the octave (tonic), or used in a harmonic stack or arpeggio to voice a Dominant chord.
Answer: 'Primary triad' is a term from Common Practice functional harmony, where dominant chords lead to tonic chords and leading notes rise to tonic notes.  So, although minor tonic and subdominant chords don't buck this system, if we're talking about 'primary triads', V is going to be major. The answer to your question is i, iv, V.
Yes, some minor modes have a minor V (or rather v) chord.  But we're now in a world where 'primary triad' isn't a useful idea. In C minor, the G chord, including the leading note, B nat, has a powerful function.  G minor chord, not so much.
Comment: What's this in THE scale idea?   Music isn't a matter of picking a scale and being restricted to it.   Play a major V chord.  Maybe think 'Oh look, I'm using the Harmonic Minor scale. That's moderately interesting!' Or play a minor v chord.   That's fine too. (It fits the Natural Minor scale, interesting, but not really important.)    My point was that if you go in this direction, you're moving away from the sort of harmony where 'primary triads' are a thing.
Comment: I've mainly been practicing the natural minor. If I make the V a major chord, than it is not in the scale. so should I use harmonic or melodic instead? (I would like the V to want to go back to the I... it's what I mainly use it for when playing songs in a major key)
Comment: When 'the scale' is mentioned, it cannot be specific to a particular minor scale. When in a minor *key*, notes from *all* minor scales are used. I nearly wrote *permissible*, but that would be silly. So, the V in a minor key is actually more often than not, **V** rather than **v**. So please stop thinking in terms of 'is it melodic, is it harmonic, is it natural. It's actually **ALL**.
Answer: In classical harmony, things are very clear. The main triads are in I, IV, and V degrees. There are three types of moles: natural, harmonious and melodic:
natural (a-c-e minor) iv (d-f-a minor) v (e-g-h minor)
(a-c-e,minor) iv (d-f-a minor) V (e-G-h major)
melodic: a: i (a-c-e minor) IV (d- # F-a major) V (e- # G-h)
Comment: This answer is unclear. -1. And I understand what 'h' is.


Can Apache 2 be configured to start sending gzipped data early?

Question: We have Apache set up to gzip compress html pages before they are sent to the client browser.
However, some of our pages are slowish to generate and it seems that Apache is holding on until it has the complete page, compressing it, then sending it to the browser.
There are big chunks of the page (the main important bits) that are actually generated and output fairly quickly.
Is it possible to configure Apache to start compressing and send data for the page as soon as the script starts outputting something? Is it is, can you offer any help is how to do this?
If not, can you suggest any other way to get gzip compression working for the server?
The scripts that generate the pages are written in PHP. We are using Apache 2.0 on Linux.
Answer: We had this same problem with a perl backend.  I'm looking up the docs that pointed me @ the solution.  It ultimately had to do with gzip trying to compress the entire document to compute the content-length.
We had some long-running scripts that this ruined the user-experience for -- instead of getting output incrementally, they were waiting for 2-3 mins with no activity!
Update:
I'm afraid I can't find it.  Reviewing our activity logs, it seems I simply disabled it on our web server, then moved an nginx-based frontend for this and other reasons (it will gzip with chunked encoding w/o having to send content-length)
Try upgrading to Apache 2.2, iirc newer versions of apache handled the chunked/gzip thing much better.
Answer: It's called 'Early flushing', and its mostly a matter of just running 'flush();' before the entire page has been generated.  Normally, an optimised PHP server will, as you've found, buffer the entire page, but a deliberate call to flush() overrides that.  The tips page on Yahoo has more information: http://developer.yahoo.com/performance/rules.html#flush
Comment: Yep, we already do that. However, apache does not start sending the data until the complete page has been output. In other words, apache is caching the result as well so that it can gzip it up before transmission.
Answer: Send flush() from time to time or after your blocks and unless you use obstart(), apache will send chunked responses.


5th Fret Method of standard guitar tuning

Question: I usually use some some of tuner to tune my guitar, but occasionally I will try to use the 5th fret method. In attempting to do so today, something puzzled me about the string setup on the guitar.
The 6 strings are as follows (from top to bottom):
E
A
D
G
B
E
The 5th fret method works based upon the fact that E is 5 notes from A, A is 5 notes from D, and so on.
However, G is only 4 notes away from B!!! If I play the 5th fret on the G string, the result is a C (verified by my tuner as well). Because of this, the 5th fret method does not work for me for the G and B strings: if my B string is tuned correctly (as a B) then it will be a B while the 5th fret of G will be a C.
What is going on? I have heard the mnemonic phrase "Eddie Ate Dynamite, Good Bye Eddie" all of my life. But it does even seem to be right?
Summarized, here are my questions.
(1) Does the 5th fret system work, or not?
(2) Why was the standard guitar built the way it was, with each string being 5 notes apart except for G and B? I know that other versions of guitars (say with more strings) exist. Is there a good reference I could have that compares the setups for guitars, weighing their pros and cons.
Thanks so much for your time!
Comment: It's standard knowledge that the B is a major 3rd from the G, not a perfect 4th like all other strings. When taught, the 5th fret method of tuning accounts for this exception by using the 4th fret only to tune the B string with the G.
Comment: EADGBE might be top to bottom physically, but guitarists know the top string to be the thin E. Therefore it's clearer to state 'bottom to top' as being EADGBE.. And - 5 'notes' away is better stated as 5 'semitones' away. We don't call each fret a note, in interval terms. Pretty sure this is a dupe, also!
Comment: one minor point to mention is that if the guitar intonation if off, then this method of tuning may give you well-tuned strings at the 5th fret area, bu the open chords are sometimes out of tune. If you hear this, maybe get it set up properly
Answer: Don't get hung up on the idea that a method name like "5th fret method" provides an adequate description of the method. I have never heard it called the 5th fret method myself, but of course that is one common way to tune by ear. There are many other ways to tune by ear, too.
Does the 5th Fret System Work?
Standard tuning for a guitar is E A D G B E. The notes are all a fourth apart, except for G and B which are a third apart. To tune by ear, you compare the note on the 5th fret of a string with the open string above it, unless you are comparing the G string with the B string, in which case you compare the note on the 4th fret of the G string with the open B string. This is a very common way of tuning by ear; of course you need to get at least one string in tune by other means, e.g., using a tuner, tuning fork, pitch pipe, or some other reference (say, another instrument you are playing with).
When you tune like this what you are really doing is finding the same note in the same octave in different places on the neck and comparing the two sounds. I often tune by comparing the notes at the 10th fret with the notes on the 5th fret. That is, D on the 10th fret of the sixth string and D on the 5th fret of the fifth string, etc., but F at the 10th fret of the third string compares with F at the 6th fret of the second string (because the sixth fret of the B string is an F in standard tuning). I do this because I spend a lot of time playing in the middle region of the neck, and this can help get things to sound the most in-tune in the places that I am usually playing.
Another method I sometimes use is to play across the neck: the harmonics at the 7th fret of the sixth and fifth strings, the fretted notes at the 9th fret of the fourth and third strings, the open B and high E strings. Here the harmonic on the sixth string, the fretted note on the 4th string, and the open B string are all B in the same octave, and should sound as the same pitch. The harmonic on the 5th string, the fretted note on the third string, and the open E string are all E in the same octave. With this method there are three points of comparison for two notes spread out over a part of the neck that gets used a lot. This can be a very useful comparison for tuning.
Pros and Cons
The standard tuning evolved over many years. There are other ways to tune. One of them is "all-fourths tuning" which makes the tuning symmetrical by removing the third between G and B. This tuning is E A D G C F.
This has what some consider an advantage in that scale and chord shapes do not change from lower string sets to higher string sets. Say you are playing a chord that uses only the 6th, 5th, 4th, and 3rd strings. If your guitar is tuned in all-fourths, you can just move the same shape to the 5-4-3-2 string set, or to the 4-3-2-1 string set without any changes to play the same chord (possibly with a different root). In standard tuning you would have to modify the first shape to play the same chord on 5-4-3-2, and then modify the shape again to play the same chord on 4-3-2-1.
There are also disadvantages to all-fourths. Barre chords become much more difficult to play. In Standard tuning when you barre across a fret with a single finger you get the fifth and root of the chord on top, with the top root doubling the bottom root on the low E string. In all-fourths you have to form a "crooked" barre to catch the notes of the top two strings one fret lower than the root on the low E string. Not impossible, but not for beginners. Another disadvantage of all-fourths, in my opinion, is that it reduces the variety of possibilities when chording. That is, in standard tuning some fingerings that are difficult or impossible to play on the lower strings become playable on a higher string set, and vice-versa. With all-fourths there is no variation in fingerings across the fretboard so an impossible fingering on one string set is an impossible fingering on all string sets. As I said before, this is an advantage for some, but can also be a disadvantage for others.
All of that said, there have been some notable players who use all-fourths tuning. Off the top of my head, I believe that Stanley Jordan and Tom Quayle both use or have used all-fourths.
Comment: Worth noting that there have been [many SE questions comparing standard to all-fourths tuning](https://music.stackexchange.com/search?q=all+fourths+tuning).
Answer: This method works only for the strings which are a five semitones apart, you cannot tune the B string from the G string this way as you noticed. You have to do it with fourth fret with this couple of strings.
One reason the guitar is tuned this way is that it's fairly convenient to have the lowest and the highest strings playing the same note, which would not be the case if they were all spaced the same.
Comment: @JohnBelzaguy Actually, I misread the question, and though the op was talking about tuning with harmonics on fret 7/5...
Comment: @JohnBelzaguy Especially the beating is way easier to hear IMO, especially with a bit of disto ;). Thanks for the correction!
Comment: @JohnBelzaguy - more good ideas! Off piste, but I use 19th and 24th frets for bass tuning, played with r.h. finger and thumb, leaving left hand free to twiddle the knobs.
Comment: What about using the G string 4th fret to tune the B?
Comment: Yes of course, but this does not imply harmonics, harmonics are cool no?
Comment: Oh, I see, I guess an edit is in order, which it looks like you already did.  Although because of inaccuracies in a guitars intonation harmonics are usually a better way to go than 5th fret tuning.
Comment: Yes, as long as the harmonics ring out nicely they are very easy to tune with. It also frees up your left hand to turn the peg :)
Comment: @JohnBelzaguy - as you're probably aware, it's possible to tune *all* strings using harmonics. 24th (or 5th) fret low E is the same pitch as top E open, then 5-7 with B string, and Bob's your uncle!
Comment: @Tim, yes I am, I've done it that way for years. This question itself is about using frets, not harmonics. The original answer makes my first comment in context.
Comment: @Tim there are even other options, you can tune the low E 7th fret to the B string (unison) and the A string 7th fret to the high E string (also unison).
Comment: "_because of inaccuracies in a guitars intonation harmonics are usually a better way to go_": @JohnBelzaguy I have gone back-and-forth on this for many years. Harmonics seem good in principle, but because of guitar intonation issues, fretted comparisons often seem to work better to me because I am usually playing fretted notes, and those are the ones I care about being in tune. Or sometimes a combination of harmonics and fretted notes seems to work better for me, but my final test is always to play a tune. On the other hand, some weeks it seems nothing can make my guitar play in tune ;)
Comment: @user87976 I probably should have said "possible inaccuracies". Acoustics with fixed bridges are generally more problematic than electric guitars with adjustable bridges. I also have experimented with different types of fretted tuning because ultimately the strings interact with each other, open or fretted. One thing I like to do is for the 4 low strings, tune the lower string open to the next higher string 7th fret octave. Then I tune the 2 high strings with harmonics from the low strings. I've gotten some really sweet sounding chords with this method (sometimes, lol!)
Answer: Answer 1). Bass guitars are usually tuned by what you call the '5th fret method'. That's mainly because basses aren't used for chord playing. (They can and are, of course, but nowhere near as much as guitars!)
Whereas guitars are often played as chordal instruments, with barre chords being utilised as we go up the neck to the dusty region. To facilitate that, the top and bottom strings are best tuned to play the same note name - namely E in most circumstances. That means that in order to achieve that, somewhere along the strings' tuning, there has to be an oddity - 4 frets to the next, rather than 5.
After many tries at reconciling this, the 3/2 string interval was found to make it easiest to play all sorts of chord shapes (beginners may disagree!), rather than any other pair of strings. Thus we have it. 5 frets between strings, except 3/2, which bottomed out at 4 frets.
7 string guitars continue the lower pattern, and retain the 5 frets interval, which is sort of in keeping with basses, and, again, works best.
Answer: A visual would seem to make this much clearer...

I've not heard the name "5th fret method" but I understood what you meant. The important thing is to see that the tuning method is not all on the fifth fret.

Why was the standard guitar built the way it was

Standard tuning is almost all in perfect fourths. It's the B string that isn't tuned to a perfect fourth above the G string. Instead it's a major third. Why? If you tuned to all perfect fourths, the last two strings would be C and F. As an experiment you can actually to that tuning, then try playing the different open chords and barre chords. It's a big fingering problem! Tuning those top two strings down to B and E - the high E then being on the same fret as the low E string (think of the open strings as fret zero) makes chord fingering a lot easier.
There is a similar method of tuning the guitar using harmonics that may interest you. Here is a picture...

Notice how the B string again is the odd one out with the tuning pattern. You need to compare open B with low E string 7th fret harmonic. You can find lots of web pages and videos demonstrating it too.

Is there a good reference I could have that compares the setups for guitars, weighing their pros and cons.

I think you may be asking about alternate tunings. There are many ways to tune a guitar beside standard EADGBE. I don't have a handy reference for alterative tunings, but you should be able to find a lot online. There are a few reasons to use alternate tunings:

you can get different chord voicings that aren't easy in standard tuning
some alternate "open" tunings tune to an open chord and are popular for playing with a slide
many alternate tunings lower strings and that will change the guitar timbre (tone) and provide a deep resonant sound different from standard tuning.


Pattern matching on Type in Idris

Question: Probably it's elementary but I don't understand why the following function answers 1 for fnc Nat and also, for fnc Integer, which is not even included as a pattern.
fnc : Type -> Integer
fnc Bool = 1
fnc Nat = 2

Answer: You can't pattern match on type and you shouldn't. When I compile your code I receive next error:
warning - Unreachable case: fnc Nat

This was already discussed earlier:

Old discussion.
Some similar question.
Some similar issue on GitHub.

UPDATE:
Finally found more relevant question with answer:
Why is typecase a bad thing?
Comment: @Shersh Thanks for the last link! Could you vote for reopening this perfectly good question? I think it's a shame it has been closed.
Comment: @AntonTrunov I also think so. Voted for reopening.
Answer: You can in fact now do this in Idris 2:
fnc : Type -> Integer
fnc Bool = 1
fnc Nat = 2
fnc _ = 3

Pattern matching on Type in Idris


R - Counting the number of a specific value in bins

Question: I have a data frame (df) like below:
Value <- c(1,1,0,2,1,3,4,0,0,1,2,0,3,0,4,5,2,3,0,6)
Sl <- c(1:20)
df <- data.frame(Sl,Value)

> df
   Sl Value
1   1     1
2   2     1
3   3     0
4   4     2
5   5     1
6   6     3
7   7     4
8   8     0
9   9     0
10 10     1
11 11     2
12 12     0
13 13     3
14 14     0
15 15     4
16 16     5
17 17     2
18 18     3
19 19     0
20 20     6

I would like to create 4 bins out of df and count the occurrences of Value=0 grouped by Sl values in a separate data frame like below:
Bin Count
1   1
2   2
3   2
4   1

I was trying to use table and cut to create the desire data frame but its not clear how I'll specify df$Value and the logic to find the 0s here
df.4.cut <- as.data.frame(table(cut(df$Sl, breaks=seq(1,20, by=5))))

Comment: Table would need two arguments : `table(cut(df$Sl,4),df$Value)` ; access the count of 0 with : `table(cut(df$Sl,4),df$Value)[,"0"]`
Comment: Your sample input and output don't match up.  Can you clean up your question?
Comment: @TimBiegeleisen I've updated the question
Comment: @mts could you kindly show how to use tapply with cut?
Comment: The solution using `table` is also helpful. Thanks a lot :)
Answer: Using your df
tapply(df$Value, cut(df$Sl, 4), function(x) sum(x==0))

gives
> tapply(df$Value, cut(df$Sl, 4), function(x) sum(x==0))
(0.981,5.75]  (5.75,10.5]  (10.5,15.2]    (15.2,20]
           1            2            2            1

In cut you can specify the number of breaks or the breaks itself if you prefer and the logic is in the function definition in tapply
Comment: That works !! I just modify the `cut` as
tapply(df$Value, cut(df$Sl, breaks=seq(0,20,by=5)), function(x) sum(x==0))
Comment: Alternatively, you can use `table()`: `table(cut(df$Sl, breaks=seq(0,20, by=5)), df$Value==0)`.
Answer: Or using data.table, we convert the 'data.frame' to 'data.table' (setDT(df)), using cut output as the grouping variable, we get the sum of 'Value' that are '0' (!Value).  By negating (!), the column will be converted to logical vector i.e. TRUE for 0 and FALSE all other values not equal to 0.
library(data.table)
setDT(df)[,sum(!Value) , .(gr=cut(Sl,breaks=seq(0,20, 5)))]
#        gr V1
#1:   (0,5]  1
#2:  (5,10]  2
#3: (10,15]  2
#4: (15,20]  1

Answer: Your question used table(), but it lacked a second argument. It is needed to produce a contingency table. You can find the count of each bin with :
table(cut(df$Sl,4),df$Value)

             0 1 2 3 4 5 6
(0.981,5.75] 1 3 1 0 0 0 0
(5.75,10.5]  2 1 0 1 1 0 0
(10.5,15.2]  2 0 1 1 1 0 0
(15.2,20]    1 0 1 1 0 1 1

And the count of Value == 0 for each bin :
table(cut(df$Sl,4),df$Value)[,"0"]

(0.981,5.75]  (5.75,10.5]  (10.5,15.2]    (15.2,20]
           1            2            2            1

Answer: A more convoluted way using sqldf :
First we create a table defining the bins and ranges (min and max):
bins <- data.frame(id = c(1, 2, 3, 4),
                   bins = c("(0,5]", "(5,10]", "(10,15]", "(15,20]"),
                   min = c(0, 6, 11, 16),
                   max = c(5, 10, 15, 20))

   id    bins min max
1  1   (0,5]   0   5
2  2  (5,10]   6  10
3  3 (10,15]  11  15
4  4 (15,20]  16  20

Then we use the following query using both tables to bin each sl into its respective group using BETWEEN for those Value equal to 0.
library(sqldf)
sqldf("SELECT bins, COUNT(Value) AS freq FROM df, bins
      WHERE (((sl) BETWEEN [min] AND [max]) AND Value = 0)
      GROUP BY bins
      ORDER BY id")

Output:
     bins freq
1   (0,5]    1
2  (5,10]    2
3 (10,15]    2
4 (15,20]    1

Another alternative to simplify the construction of bins suggested by mts using cut, extracting the levels of the factor:
bins <- data.frame(id = 1:4,
                   bins = levels(cut(Sl, breaks = seq(0, 20, 5))),
                   min = seq(1, 20, 5),
                   max = seq(5, 20, 5))

Comment: Interesting solution, +1. Likely you could simplify the construction of `bins` with `cut` as used in the other answers, i.e. `cut(Sl,breaks=seq(0,20, 5))`?
Comment: @mts I edited it to include your suggestion. Thank you!


Angular 5 error with "@angular/core" after installing bootstrap 4

Question: I am building my first application using angular 5 and .net core2 in visual studio 2017; I am using .Net core2 to create APIs and handle data through models... and those APIs are called from client side using angular 5; In order to make my web app responsive I decided to use Bootstrap 4; Before i installed it, dependencies where working fine, everything was great as you can see here :

But when after I installed bootstrap successfully using this command: npm install bootstrap --save suddenly an error appeared in the dependencies and I can't be able anymore to build my solution...
Why this error appeared and how can I solve it? Please note that I have created a pure angular5 using visual studio 2017 and I did the same --> installation worked successfully and I was able to use bootstrap 4;

Error:

Update:
In order to solve my error I have tried this:
npm install

npm i @angular/core

But below error was thrown:

Could not install from ""@angular\core"^5.2.0"," as it does not
  contain a package.json file

This is my package.json file:
{
  "name": "angular",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "\"@angular/core\"^5.2.0\",",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "bootstrap": "^4.1.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.5.6",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular/cli": "~1.7.3",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~2.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  }
}

Comment: did you try installing @angular/core again ?
Comment: @CornelC please check my updated question
Comment: In package.json the angular/core dependency is wrong `"@angular/core": "\"@angular/core\"^5.2.0\",",` . I should be `"@angular/core": "^5.2.0"`
Comment: Thank you, I don't know how I missed this
Answer: The package.json is wrong.
Replace
"@angular/core": "\"@angular/core\"^5.2.0\",",
with
"@angular/core": "^5.2.0"


Install mongodb driver in docker with dockerfile

Question: I have a mongodb docker container. I need another docker container which will have php and apache installed. I want to run a php script from this container and send some data to the mongodb container to save the data in mongodb database. So i need to install mongodb driver in the php-apache container.
To do that, i have created following dockerfile:
FROM php:7.3-apache
COPY src/ /var/www/html
RUN apt-get update
RUN apt-get install openssl libssl-dev libcurl4-openssl-dev
RUN pecl install mongodb
RUN cp /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini
RUN echo "extension=mongodb.so" > /usr/local/etc/php/php.ini
EXPOSE 80

It first builds php-apache docker image. Then it should install mongodb driver.
But when i run the following command
docker build -t my-mongo .

At one point it shows following message and stops the execution:
Need to get 2213 kB of archives.
After this operation, 9593 kB of additional disk space will be used.
Do you want to continue? [Y/n] Abort.
The command '/bin/sh -c apt-get install openssl libssl-dev libcurl4-openssl-dev' returned a non-zero code: 1

What went wrong here? Is there anything wrong in the dockerfile ?
Answer:
What went wrong here? Is there anything wrong in the dockerfile ?

There are at least three things wrong with your Dockerfile IMO.
The first one is not in direct relation to your problem, but you are creating way too many layers (one for each RUN command) for something as simple as adding a driver to your image. You should put all this in a single layer (i.e. a single RUN command) and cleanup after yourself at the end to keep the layer footprint small.
Now the core of your real problem. As you can see in your output, apt-get is launched in interactive mode and asks for a confirmation. The docker build process can't handle that and therefore aborts the command causing the build to fail. To overcome this, apt-get has a -y option to answer 'yes' to all prompts by default.
The last one is in the line where you add the mongo driver to php.ini: you are redirecting echo output to your file with a single gt; sign (>), hence you are replacing the full content of the file you just copied. You must use a double gt; sign (>>) for content to be appended.
The following Dockerfile should fix the problems above (tested without the copy of sources + cp of your own php.ini file since I don't have them)
FROM php:7.3-apache
COPY src/ /var/www/html
RUN apt-get update \
    && apt-get install -y --no-install-recommends openssl libssl-dev libcurl4-openssl-dev \
    && pecl install mongodb \
    && cp /usr/local/etc/php/php.ini-production /usr/local/etc/php/php.ini \
    && echo "extension=mongodb.so" >> /usr/local/etc/php/php.ini \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*
EXPOSE 80

Some explanation:

The && notation allows to run all commands one after the other in a single docker RUN command resulting in a single intermediate container, thus a single layer.
-y --no-install-recommends options to apt-get ask apt to not go interactive (answer yes everywhere) and to install only needed packages, not the recommended ones.
The two last instruction apt-get cleann && rm -rf /var/lib/apt/lists/* remove all caches made by running apt so that the layer stays as small as possible. (see apt-get chapter in docker best practice)
Comment: thank you for your response. i found another issue. when i check phpinfo() on browser. it doesn't show mongodb loaded. Moreover, usr/local/etc/php/php.ini-production is not copied to /usr/local/etc/php/php.ini. php.ini file has just one line - extension=mongodb.so. is there any further scope to improve the dockerfile ? my work is very simple. I just need to run a php script from this container and send data to the mongodb container.
Comment: Although this is actually an other issue and should be asked in a new question, it is quite trivial so I answered here. See my edit.
Comment: many thanks, but mongodb is still not shown in phpinfo() page
Comment: It is shown on my instance running from the image built from the Dockerfile above. Mongodb extension version 1.6.0
Comment: Not necessarily bad to have more than one layer. More layers can lead to faster image re-builds.
Comment: @spinkus I agree to your remark on a very general and theorical level and as long as all the process is optimized. But note that I was cautious enough to precise: `you are creating way too many layers.. for something as simple as adding a driver to your image`. In the context of the question, creating 5 layers where several are pure package cache updates without any cleanup (e.g. `apt-get update` on its own....) for simply adding a php mongodb driver is definitely a bad practice. If you can further optimize what I proposed above for this particular install, I'm happy to hear about it.
Answer: put this at the beginning  of your Docker file, it is important to have it before installing all other extensions, otherwise it fails.
FROM php:7.3-apache
RUN apt-get update -y && apt-get upgrade \
    && pecl install mongodb && docker-php-ext-enable mongodb

That's all what I needed to get mongodb running FROM php:7.3-cli-buster Probably it will work for other versions - fpm, apache etc as well.
Comment: i tried your 2 lines at the beginning of dockerfile, but it shows error - Sending build context to Docker daemon  8.704kB
Error response from daemon: No build stage in current context
Comment: @A.Chy See edited Dockerfile - it works well for me, perhaps you have a problem due to different `FROM` - try `7.3-apache-buster` instead. Here's a [full list of supported tags](https://github.com/docker-library/docs/blob/master/php/README.md#supported-tags-and-respective-dockerfile-links)
Comment: @A.Chy Try the docker file with only these three lines to build and once working add lines of the rest of your target Docker file and see what causes the error.
Comment: i tried it, but it shows the old problem. php.ini file not shown in /usr/local/etc/php folder
Comment: @A.Chy add the line `RUN echo "extension=mongodb.so" >> /usr/local/etc/php/php.ini`
Comment: now php.ini file is created and there is one line - extension=mongodb.so. but why mongodb is not shown in phpinfo() page ?
Comment: @A.Chy run docker image and log into its console `docker run -it --entrypoint="" your-image-name:latest bin/sh` and type `php -m` and you should see `mongodb` under the `[PHP Modules].`. Play with the php.ini and turn on/off some other extensions to see if it makes any difference. If you're using apache version of php image, make sure your PHP loads the ini file as you expect and not the different - check that [this way](https://www.ostraining.com/blog/coding/phpini-file/)
Comment: i can see mongodb under the [PHP Modules]. but it's still not shown in phpinfo() page on browser.
Comment: i modified php.ini file like mysqli.reconnect = On/Off. but there is no effect on phpinfo() page on browser


Interpreting FE and RE from plots in an lmer

Question: I am currently trying to understand mixed effect models. And I would like to ask for some help understanding these results.
The data that I have is the mass volume of different rats across different days. Each rat has different time points where they took the measurement of that volume. There are 6 rats with volume measurements and 2 groups 3 rats came from Chile and 3 from England.
So the model is:
 m1 <- lmer(lVolume ~ Country*Day + (1|Rat))

I am trying to understand how I can interpret the results from these plots:
***Update ***
I plotted the estimates:
Fixed parameters betas:

  coeff <- fixef(m1)[2] :

PassageChile
         0.0458
  (respectively for England*Day)

Random parameters :

coeff <- sqrt(VarCorr(m1)$Rat[1])

To see left plot (similarly for the right one just changes the coeff and conf_int):
ggplot(df, aes(x = Set_Rat_1, y = coeff, color = Country)) +
      geom_point(show.legend = FALSE, size = 3,
      position = position_dodge(0.5)) +
      geom_errorbar(aes(x = Set_Rat_1, ymin = Lower_confidence,
      ymax = Upper_confidence), width = 0.2,
      position = position_dodge(0.5), show.legend = FALSE) +
      scale_shape_manual(values = cols) +
      labs(x = "Set_Rat_1", y = "FE", title = "Set Rat 1") +
      theme_bw()

In addition, I got this but how do interpret these single points in terms of fixed effect, random effect and volume growth?
df.plot = ggpredict(model = m1,
                    terms = "Day",
                    type = "fe")

ggplot(data = df.plot,
       mapping = aes(x = x,
                     y = exp(predicted),
                     ymin = exp(conf.low),
                     ymax = exp(conf.high))) +
  geom_ribbon(fill = "lightblue") +
  geom_line(size = 1)

plot_model(
  m1,
  bpe = "mean",
  bpe.style = "dot",
  prob.inner = .4,
  prob.outer = .8
)

In that sense,
a) I would like to interpret these plots with the model, what this single value in each country is telling me for both the fixed effect and the random effect.
b) Is there a way to check the significance between these 2 points from the fixed effect and the 2 points from the random effect?
c) Also, when I include more rats and plot the predictions from the m1 model, you can kind of notice a clustering in the growth, is there a statistical way to check that or the lmer tells you about this in some of the parameters?
This is partial data that the model uses:
For rat 1 I have volume c(78, 304, 352, 690, 952, 1250) at days c(89, 110, 117, 124, 131, 138) that belong to country Chile.
For rat 2 I have volume c(202, 440, 520, 870, 1380) at days c(75, 89, 96, 103, 110) that belong to country Chile.
For rat 3 I have volume c(186, 370, 620, 850, 1150) at days c(75, 89, 96, 103, 110) that belong to country Chile.
For rat 4 I have volume c(92, 250, 430, 450, 510, 850, 1000, 1200) at days  c(47, 61, 75, 82, 89, 97, 103, 110) that belong to country England.
For rat 5 I have volume c(110, 510, 710, 1200) at days  c(47, 61, 75, 82) that belong to country England.
For rat 6 I have volume c(115, 380, 480, 540, 560, 850, 1150, 1350) at days  c(47, 61, 75, 82, 89, 97, 103, 110) that belong to country England.
Comment: How to interpret the estimates and the p values in the stats table from the lmer model ? This is quite hard....
Answer: When you have an interaction you have to be very careful when interpreting "fixed effect" coefficients even if there aren't random effects. With default coding in R, the (Intercept) is the estimate when all categorical predictors are at their reference levels (here, country of Chile) and continuous predictors are at 0 (here, Day = 0).
The coefficient for England is the difference from Chile only when Day = 0! That doesn't seem to be a situation of much practical interest in your study. There isn't much point to interpreting a plot of that form of your fixed effect for England
The coefficient for Day is the change per day for Rats from Chile. That assumes a linear change in "mass volume" per day. Your plots suggests that isn't a very good assumption for your data.
The England:Day interaction is the extra change per day for Rats from England over those from Chile. Again, the linearity assumption seems hard to support here.
All that the p-values in your table indicate is whether the corresponding coefficient is significantly different from 0. With interactions you typically want instead to examine differences among realistic combinations of conditions. For example: do Rats from Chile have different "mass volumes" than those from England at Day = 100? That requires extra calculations based on the coefficient estimates and their standard errors. I find the emmeans package to be helpful for performing that type of calculation with associated standard errors and p-values.
With a simple (1|Rat) random effect, the random effects are estimates of the variance of the differences of the individual rats from the overall (Intercept) value. Your model imposes a Gaussian distribution on those intercepts and doesn't allow for any further differences in terms of Country or Day (or their interaction) among the Rats. Thus for an individual Rat you would just add the corresponding fixed effects of Country and Day (including the interaction) to that individual's intercept.
You'd have to use other methods to look for clustering among Rats. The clustering might in part be due to predictors that you have omitted from the model, such as sex (if your Rats weren't all the same sex). I'd recommend evaluating such omitted predictors first.
Comment: @Rachel overlapping confidence intervals only bear rough relationships to "significance" differences. See [this page](https://stats.stackexchange.com/q/18215/28500). The `England` coefficient in the table near the end shows p < 0.001, for a significant difference from `Chile` when `Day = 0`. The interaction term, however, suggests that the difference becomes smaller over time. I don't know of a way to "squeeze hidden clusters" out of an `lmer` model. I wouldn't do that with this model anyway, as the assumption of linear changes with `Days` is incorrect according to your plots at the bottom.
Comment: @Rachel if a simple biological model doesn't describe the data adequately, then you _gain_ something with a more complex model. It's hard to know how well your model described your data, as you didn't show things like plots of residuals (differences between observed and fitted values) versus fitted values. Exponential increases in rat volume _might_ hold over some early time periods, but not over the whole lifespan. Males and females can differ. You could use parametric models as you suggest (logistic, etc.), or flexible approaches like restricted cubic splines or generalized additive models.
Comment: Thank you very much! So but for example, in the plot with confident intervals, they overlap in both countries, so does that mean that there is no statistical significance of the beta values of each country? And,also regarding the plot of the ¨cluster behaviours¨ is there a way to kind of squeeze the lmer model and determine if there are ¨hidden cluster¨ within the model ?
Comment: Hi agai @EdM, this is taking me time to digest, but I really appreciate your answer. Quick questions: when you mentioned that in the coefficient Day, "Your plots suggests that isn't a very good assumption for your data" Do you mean that the fitting is not doing a correctly job? So then try to assume a different approach? in the sense of maybe not assuming that this growth is linear by taking the log(Vol)(but in really what I plotted what exp(fitted) values, so then assuming that the growth is exponential)? Similarly, with you comment over the linearity in the interaction coefficient ? Thanks
Comment: In your opinion @EdM, do you think that this data would require a non-linear approach? I have been reading some other approaches for growth mass, such as the Gompertz, the power-law or the logistic models. But don't you think that by including more parameters in a more complex model, we would lose biological interpretation like the nice one you described in your main answer? Sorry for the question is just like it is a fascinating topic, and I would like to learn as much as possible from experts like you and others on this website. Sometimes books are more lack interpretation on examples here
Comment: Thank you! I tried to expand the model where now I am allowing the rate of change in Volume to vary between rats, and it seems to work much better. Could I have your opinion on this please: https://stats.stackexchange.com/questions/566103/levels-in-a-mixed-effect-model-with-interaction-representation   ?
Answer: I suggest doing this, for starters:
library(emmeans)
RG <- ref_grid(m1, at = list(Day = c(0, 50, 100, 150),
    options = list(tran = "log"))
emmip(RG, Country ~ Day)

(or whatever Day values are most important.) The plot will show a line for each country, and having tran = "log" in there gives you the flexibility to undo the log transformation later that you apparently applied to the response variable.
One useful way to think about the model you have is that there are two non-parallel lines. You can use something like
emmeans(RG, ~ Country | Day)
pairs(.Last.value)

To view estimates (on the log scale) and comparisons thereof. If you want to see those on the original response scale, add the argument type = "response" to the emmeans() call.
Another thing you can do is compare the slopes of those two lines:
emtrends(m1, ~ Country, var = "Day")
pairs(.Last.value)

I recommend looking at some of the vignettes in the emmeans package, especially in this case the one on interactions.
Finally, I should be remiss not to mention that you should check that the model fits reasonably well. For example,
plot(resid(m1) ~ Day)

If you see any curvature there, it may be appropriate to choose a more complex model that models that.
Comment: Hi @RussLenth, thank you for your answer. This is very interesting, I plotted what you suggested ( https://ibb.co/TPwpG8G ), and this is the interpretation that I would give but I really would like to know yours: the plot is saying that English mice start with a larger volume but tend to grow at a slightly slower rate than Chilean mice (you can see that by day 180, there is only a very small difference between the two) ? Also in that sense is there a way to check that there is statistical significance of mass growth between these two countries ? Thanks again.
Comment: The two lines of code for `emtrends` provide those estimates and comparison. But what I am concerned about is that the plot you give *could not have resulted from the model* `m1` that is shown in the question. That model fits two straight lines. It is really difficult to answer people's questions when what they show is different from what they actually did.
Comment: The plot you see is from emmeans(RG, ~ Country | Day) (ibb.co/TPwpG8G) having for each line the marginal distribution of each country, and from the code emtrends (https://ibb.co/5YV3Qfk).
Comment: Right, but the model `m1` that went intoRG is a model for two straight lines. Yet what you show is curves.
Comment: Because I put the Log as you suggested (tran = "log") since I am taking the logVol of the y variable.
Comment: This might be without the "Log". https://ibb.co/XYM6T5k
Comment: @rachel Important note: I made an error in how `RG` is constructed and it gives wrong results. That explains some of my comments. I edited my answer and changed it to something that works correctly. Please re-do using what is shown. The confusion is due to my poor choice of having an option of `tran` and a `ref_grid` argument of `transform`. I think I am going to have to deprecate the latter in future versions to keep this from happening in other similar situations.


What is the correct way to configure actors in Play 2.x?

Question: I noticed a slight difference between the documentation for 2.1 and 2.0:
2.0
akka.default-dispatcher.core-pool-size-max = 64
akka.debug.receive = on

2.1
akka.default-dispatcher.fork-join-executor.pool-size-max =64
akka.actor.debug.receive = on

Akka's own documentation has a core-pool-size-max setting like 2.0, but no pool-size-max like 2.1. Why did this change between 2.0 and 2.1? Which is the correct way to configure Akka in Play? Is this a documentation bug in one of the versions?
(In the meantime, I'm going to try and stick both config styles in my Play 2.1 config and hope for the best).
Answer: First of all, always use the documentation for the version you're using, in your case you're linking to the snapshot documentation which is for an unreleased Akka version (i.e. a snapshot).
Here's the 2.1.2 docs: http://doc.akka.io/docs/akka/2.1.2/scala/dispatchers.html (also accessible from doc.akka.io)
When we look at that page, we see that under the example configuration for fork-join-executor and thread-pool-executor it says: "For more options, see the default-dispatcher section of the Configuration.", linking to:
Where we can find:
  # This will be used if you have set "executor = "thread-pool-executor""
  thread-pool-executor {
    # Keep alive time for threads
    keep-alive-time = 60s

    # Min number of threads to cap factor-based core number to
    core-pool-size-min = 8

    # The core pool size factor is used to determine thread pool core size
    # using the following formula: ceil(available processors * factor).
    # Resulting size is then bounded by the core-pool-size-min and
    # core-pool-size-max values.
    core-pool-size-factor = 3.0

    # Max number of threads to cap factor-based number to
    core-pool-size-max = 64

    # Minimum number of threads to cap factor-based max number to
    # (if using a bounded task queue)
    max-pool-size-min = 8

    # Max no of threads (if using a bounded task queue) is determined by
    # calculating: ceil(available processors * factor)
    max-pool-size-factor  = 3.0

    # Max number of threads to cap factor-based max number to
    # (if using a  bounded task queue)
    max-pool-size-max = 64

    # Specifies the bounded capacity of the task queue (< 1 == unbounded)
    task-queue-size = -1

    # Specifies which type of task queue will be used, can be "array" or
    # "linked" (default)
    task-queue-type = "linked"

    # Allow core threads to time out
    allow-core-timeout = on
  }

So to conclude, you need to set the default-dispatcher to use the "thread-pool-executor" if you want to use the ThreadPoolExecutor, by akka.default-dispatcher.executor = "thread-pool-executor" and then specify your configuration for that thread-pool-executor.
Does that help?
Cheers,
√
Comment: Amm, I don't want to change executors, just tweak the default one as in the examples in Play's config - I was just wondering as to why the docs for Play 2.1 differ from Play 2.0 - whether the was a real API change, or if this is a docs bug. Regardless, I just want to set `core-pool-size-max` or `pool-size-max`.
Comment: But you need to change the setting for the right implementation. The default-dispatcher uses fork-join-executor so you'll have to change the settings for that unless you change executor. Please refer to the documentation.


functional form for modeling hazard function

Question:
What functional form do you suggest to model this hazard function?
Can it be a quadratic form, even tough it's skewed?
Comment: Does it need to be a parametric function?  If not, you could always simply use the sequence of point estimates you have here, or apply something like a smoothing spline.
Comment: You would presumably want something for which the hazard increases and decreases; so the lognormal, the generalized gamma models are possibilities. If you want additional flexibility, you might look at the generalized F. See [here](http://data.princeton.edu/pop509/ParametricSurvival.pdf) for example
Comment: It needs to be a parametric function. Something more parsimonious then the general model. There's a clear rise, peak and decline. So I was thinking quadratic. But it's skewed, the rise is more rapid then the decline. It's this a problem? If so, would you suggest a cubic or quartic form.
Answer: I would say a spline would be the right idea.  You want parsimony, but you also don't want to ignore the structure of the data (for example the spike at two years) which would likely happen with something like a single quadratic or cubic function.  You could either fit the spline directly to the scatterplot of points (which is probably the easier idea at this point), or another common approach would be to estimate a function of the form
$$
h(k) = \frac{e^{s(k)}}{e^{s(k)} + 1}
$$
where $h(k)$ is the hazard function and $s(k)$ is a smooth function.  However, this latter method requires some data manipulation if one wants to use standard statistical techniques, so I wouldn't really recommend it at this point.


Building a classification rule for geographical mapping of cell phone number

Question: I have a database of some 10000 cell-numbers with mapping of geographical areas they are associated to. I believe the first 5-6 characters in the numbers can point to the geo. area the cell number belongs to.
I want to build the rules for such mapping so that geographical area for a new number can be calculated. Can someone point how should I approach the problem?
Update: I am not sure how many digits are specific to geo. location. It is only my guess that 5-6 digits may be involved.
Also, more than one set of digits can be associated to a particular geo-area. Every operator will have their own digit-set to refer to area and my database has cell-numbers from several operators.
Comment: Maybe http://gis.stackexchange.com/ would be more appropriate in your case. Anyway, you might think of updating the title of your question because as it stands it doesn't really reflect your aims (the use of "classifier" is misleading here).
Comment: I'm not understanding something: if a prefix of the numbers "points to" a geographic region, isn't that your solution?  If a new number has a unique new prefix and you are hoping to determine (or guess) which region it might indicate, then you need to supply more information about the nature of the prefix-region relation in order to begin addressing this problem.
Comment: @chl Well, I think it is a general stats question. Instead of GIS, it could have been mapping to anything else. Can you suggest me a better title? I am sorry I am very new to http://stats.stackexchange.com and not very good with stats.
Comment: "Building a classification rule for geographical mapping of cell number"? Maybe provide additional details, per @whuber's request, and this might be clarified further.
Comment: @chl: Done. Thanx for the title suggestion. And, I have provided more information.
Answer: Ah!  "Cell" apparently means "cell phone" (rather than a generic cell such as a square on a map grid).  Thus, for each prefix, you would like to identify a geographic region in which that prefix is found.  These regions are not predefined; rather, you would like to estimate their extents from the data you have.  (This is why it's not a simple database tabulation problem.)
If this is right, then you probably would like to apply a "concave hull" algorithm with a GIS.  Each prefix gives a set of points in your database which translates to a polygonal region (the concave hull).  By applying this algorithm separately for each prefix, you would obtain a set of possibly overlapping geographic regions.
Statistical clustering algorithms look promising in this context, but they don't seem appropriate for several reasons.  First, you already have the clusters: the cell phone number prefix gives the cluster identifiers.  Second, the clusters might not be spatially separated, because sets of distinct ids can be geographically overlaid.
If you want to pursue the concave hull idea, we can migrate this question to the GIS site.
Comment: Thanx. I would like to try concave hull algorithm.
Comment: @curious PostGIS, Python, and R solutions are referenced at http://gis.stackexchange.com/q/1200/664 .  (Ignore references to "convex hull" algorithms and focus on "concave hull" and "alpha shapes".)
Answer: This can be done using relational database. R has a nice implementation of this (see this post on sqldf). MS Access (or even Excel) will work just as well.
The idea here is you want to create a table that maps a number (as you say, of 5/6 digits) to a geographical region (75 or however many you have). Then, you join your table of 10000 records onto your reference table.
Let table mydata contain your 10000 records and holds at least 1 column:

ID - contains your 'cell number'

Let table myreftable contain your reference table, which should have exactly 1 row for each geographic region, and holds 2 columns:

ID - contains the relevent 5/6 digits of your 'cell number'
Geo - contains the description of the geographic region

The table you'd want would be generate by the following SQL:
select
   m.ID as cell_number
   ,r.Geo as geo_region
from mydata m
inner join myreftable r on left(m.ID,6)=r.ID

... where 'left()' is any function that takes the first 'n' characters of a string. Each database has different text/string functions you can use for this purpose.


Update Series Array on HighChart after editing chart

Question: I have an areaspline HighChart, where I have it implemented in a way that I can drag series points up and down on the Y-Axis and return the new of the point. I followed this example http://jsfiddle.net/highcharts/AyUbx/. The series of points is create from the following array data = [6,4,13,6,21,22]
In my code there is the following function:
 drop: function() {
 $('#drop').html(
 this.series.name + ' to was set to ' +
 Highcharts.numberFormat(this.y, 2) + ''
 ),
}

This is the function that updates the point I choose to move with the new value after I stop dragging the point.
However I am struggling to get my head around one or two things.
First of all, say for example I move the point 4 in the array, and I increase the value to 8. When I log the array after I move this point the new array is returned with the x co-ordinate as well as the new value for that point, so for example the returned array is now data = [6,1(or this.x value),8(new this.y value), 6,21,22]. Or if I log the series.data, it returns:
 series.data = [object, Object],[object, Object],[object, Object],[object, Object],[object, Object],[object, Object]

I am presuming the reason it returns the x co-ordinate value is so that the graph can correctly get the new position of the point you choose to move.
How do I just return the the array with the updated this.y value? So in the example above the returned array will be data = [6,8,13,6,21,22] or just return the value Object to the array?
Secondly, when I log the array output after I finish editing, it logs the output twice. Is there any particular reason for this?
Answer: All yData you can find in: series.yData and example: jSfiddle
Answer: I figured this out. It may be a roundabout way of doing it, but it works.
So looking into the issue more, the new value of a point after I update is returned as an array [Xpos, Ypos]. So in the example above, data = [6,8,13,6,21,22] is the array I begin with and the returned new array: data = [6,8,13,[Xpos,Ypos],21,22].
So to remove the Xpos value in the new returned array I had to go through the array after it is updated, and for each element in that array, check if it was an instance of an array. If it was an instance of an array, I set that element equal to the Ypos element. This return the new value for the point on its own.
So where this was done was in the drop function in this example:
     function drop(e) {
        if (dragPoint) {
            if (e) {
                var deltaX = dragX,// - e.pageX,
                    deltaY = dragY - e.pageY,
                    newPlotX = dragPlotX - deltaX, //dragPoint.series.xAxis.minPixelPadding,
                    newPlotY = chart.plotHeight - dragPlotY + deltaY,
                    series = dragPoint.series,
                    newX = dragX === undefined ? dragPoint.x : dragPoint.series.xAxis.translate(newPlotX, true),
                    newY = dragY === undefined ? dragPoint.y : dragPoint.series.yAxis.translate(newPlotY, true);

                newX = filterRange(newX, series, 'X');
                newY = filterRange(newY, series, 'Y');
                dragPoint.update([newX, newY]);
            }

         //My code to remove the newX from after the dragPoint.update([newX, newY]);
         for (var i = 0; i<data.length; i++)
                    {
                        if(data[i] instanceof Array)
                        {
                            data[i] = data[i][1];

                        }
                        else
                        {
                            data[i] = data[i];
                        }
                    }


Genetic Algorithm - Parent Selection vs. Crossover Probability

Question: I read the tutorial on TutorialsPoint and this question and answer on StackOverflow. However, I still do not understand the meaning of Crossover Probability in the Parent Selection and Crossover process of a genetic algorithm.
Say I have a population of size 100 and the crossover probability is 0.9. What does it mean? Do I:

select precisely 10 parents (since 90 % of offsprings shall be made by crossover), or
run a RNG 100 times and for each time the 0.9 probability fails, I select a parent?

Then, the parents are somehow crossed over and some individuals mutate. Does the population need to have exactly 100 members at this point, or there is an additional selection of which individuals make it to the next generation?
Comment: The precise definitions and how they're implemented don't *really* matter unless you're trying to adhere to an exact specification. The point is just to randomly cross parents. It doesn't matter exactly how you achieve that. Play around with a few ways.
Answer: As mentioned by Carcingenicate, the implementations can vary. A 0.90 crossover rate indicates that 90% of the offspring, or child, population will be created through a crossover operation on parent solutions. This might be implemented such that exactly 90% of the child are produced by crossover each generation, or it may be implemented probabilistically (as is done in AI_Learning's example). The children produced by crossover may or may not be also subject to mutation.
How the parent solutions are selected can also vary. It may be that more fit parent solutions are more likely to be selected to produce offspring, and whatever offspring are produced will constitute next generation's parent population. Alternatively, the parent solutions may be randomly chosen to produce offspring. Selection is then performed on the combined parent and offspring populations to create the next generation's parent population.
Generally, the parent population will always be equal to the prescribed population size. However, it is possible to produce a greater number of offspring and then select only a subset. Or only a few offspring may be created each generation, each potentially replacing a parent solution. Some implementations may also vary the population size over time, perhaps using large populations initially to promote exploration and then reducing the population size over time to promote exploitation.
Answer: Its not exactly 10 parents, on average 10 parents.
Following is the pseudo code, which I follows.
<code>current_population <- comes from previous generation
new_population <- []

for i upto number of chromosomes in current_population :
    parent1, parent2 <- pick 2 parents from current population based on fitness function

    if random_number is less than cross_over_ratio :
        offspring <- crossover (parent1, parent2)
    else:
        if random_number is 0.5:
            offspring <- parent1
        else:
            offspring <- parent2

    append the offspring to new_population

for i upto number of chromosomes in new_population :

    if random_number is less than mutation_ratio :
        i_th chromosome in new_population <- mutation (i_th chromosome in new_population)
</code>


Use odt2txt for Diff on Gitweb

Question: I followed the instructions here and I cannot get them to work.  I am using Git and Gitweb 1.7.5 on shared hosting, custom compiled and deployed using GNU Stow but basically following this howto on Dreamhost (just forked, no modifications made to reflect Stow and other stuff).  Essentially I modfied my ~/.gitconfig and /path/to/repo/.gitattributes and/or /path/to/repo/info/attributes; neither worked.  I still see this in the gitweb interface.

diff --git a/2011/randomdoc.odt
  b/2011/randomdoc.odt
index 5890ee7..168582b 100644 (file)
Binary files a/2011/randomdoc.odt and b/2011/randomdoc.odt differ

What am I doing wrong?  It does not even show
Answer: I was having the same problem but after a torough search found the solution in a mail list: http://www.spinics.net/lists/git/msg160731.html
Modified config like this
[core]
    repositoryformatversion = 0
    filemode = true
    bare = true
[diff "odf"]
    textconv=odt2txt

Modified info/attributes:
*.ods diff=odf
*.odt diff=odf
*.odp diff=odf

Modified /etc/gitweb.conf:
    push @diff_opts, '--textconv';
IMPORTANT: As I've read, enabling diff_opts might lead to security problems allowing git users to execute code!
I've realized that is you the one writting on the list, anyway, I'll leave this here for future searches... :)
Answer: gitweb might

not honour these attributes, or
your executables might not be reachable from within the webserver context

try specifying absolute paths to git-oodiff

Inside git-oodiff you can easily extend the environment for any other applications you need:
export PATH="/usr/local/bin/ooutils:$PATH" # e.g.

Comment: `git-oodiff` exists for pre-1.6.4 versions of Git. Post-1.6.4 you use textconv to use custom commands to get text output for the diff.  [the method you mention is obsolete now, sort of](https://git.wiki.kernel.org/index.php/GitTips). I am perplexed because it appears it can access Git (which is not the normal one on the server, I compiled it and control it with Stow so I will have access to multiple versions).  The symlinks to `git` and `odt2txt` are in the same path, so one should work so long as the other does. Kind of at a loss.  I guess I have to ask the git mailing list.

Use odt2txt for Diff on Gitweb


Update state values with props change in reactjs

Question: I have a modal component that should be called when setState changes but for some reason it is not updating. In the first file Im setting the following in render.
<ModalParcel showModal={this.state.showModal} parcelToConfirm={this.state.dataForParcelToConfirm} />

Within the Modal component constructor() I am setting the following.
constructor(props) {
    super(props);

    console.log("Constructor for modal componenet called.")

    //this.renderRowForMain = this.renderRowForMain.bind(this);

    this.state = {
      show: this.props.showModal
    };

  }

render() {

    if(this.state.show == true){

        var content =
        <View style={styles.modal}>
            <View style={styles.modalContent}>
                <TouchableHighlight onPress={() => this.closeModal()}>
                    <Text>Close</Text>
                </TouchableHighlight>
            </View>
        </View>;

    }else {

        var content = null;

    }

    return ( content );

  }

The problem is that the constructor() only gets called once on initial creation. I was under the impression that when I update the state to show the modal the constructor would be called again but this isn't happening.
I basically want to change the state to show the modal and then re-run render().
Answer: No constructor will not get called when component re-rendered, it will get called only on initial rendering.
I think, there are two ways by which you can solve your issue:
1. Use componentWillReceiveProps(){ lifecycle method it will get called whenever any change happens to props values, so you can update the Modal component state value showModal here, like this:
componentWillReceiveProps(nextProp){
   this.setState({
      show: nextProps.showModal
   });
}

As per DOC:

componentWillReceiveProps() is invoked before a mounted component
  receives new props. If you need to update the state in response to
  prop changes (for example, to reset it), you may compare this.props
  and nextProps and perform state transitions using this.setState() in
  this method.

2. Don't store the props value in state variable and directly use this.props.showModel in Model component, by this way whenever any change happens to props values, Modal component will take the updated values.
Comment: Thank you for the response, just tried it and it works great.


is it impossible to parse this query statement in c++?

Question: String values = L"'Bob, and Tom''s', 1, '2013-03-19'";
I tried to parse this statement in cpp but it still has error.
This is the SQL statement.
It is different '' and ".
I wonder that is it difficult or dangerous to parse the query statement not in SQLengine?
Answer: It is difficult to parse a SQL statement without a precise SQL grammar for the DB engine you are using and strong parsing technology. Anything else you attempt to do will be buggy in its ability to parse, and thus in its ability to deliver practical value.
Yes, you can do that in C++ if you are determined enough.  I've met very few people that are that determined.  The fact that you are asking this question hints pretty strongly which camp you are in.


Have there been (successful) attempts to use something other than spheres for homotopy groups?

Question: Homotopy groups are famous invariants in algebraic topology. They have a myriad of wonderful properties:

For $n \ge 1$, $\pi_n(X,*)$ is a group; for $n \ge 2$, this group is abelian.
$\pi_n$ defines a functor from based spaces to (abelian) groups.
$\pi_n$ is invariant under homotopy equivalences, and homotopic maps induce the same morphism on homotopy groups.
The Seifert–van Kampen theorem allows one to compute the fundamental group of $X \cup_A Y$.
A fibration $F \to E \to B$ yields a long exact sequence of homotopy groups.
There is a natural suspension morphism $\pi_n(X) \to \pi_{n+1}(\Sigma X)$, and it eventually stabilizes as described by the Freudenthal suspension theorem.
If $f : X \to Y$ is a map between two CW-complex that induces an isomorphism on all homotopy groups, then it's a homotopy equivalence.
The Whitehead product endows $\pi_*(X)$ with a shifted Lie algebra structure.
Etc., etc.

But after all, $\pi_n(X,*)$ is "merely" the set of morphisms in the homotopy category of pointed spaces from the $n$-sphere to $X$: $\pi_n(X,*) = \hom_{\mathsf{hTop}_*}((S^n,*), (X, *))$. This has always seemed somewhat "biased" to me; spheres are given a preponderant role in the definition. They are certainly a fundamental type of spaces, but they're not all there is to life. So my question is:

Have there been (successful) attempts to use something other than spheres for homotopy groups, in a way that some part of the structure described above is retained (in one form or the other)?

For example, maybe I'm interested in totally disconnected spaces, and I'd consider something like $\{ [0,1]^n \cap \mathbb{Q} \to X \}$ (with boundary conditions) up to "homotopy". And even here we see spheres (or at least Euclidean spaces) lurking in the background: the definition of a homotopy involves a path $[0,1] \to Y^X$, so why not consider "homotopies" of the type $[0,1] \cap \mathbb{Q} \to Y^X$...? One problem that could crop up here is that $[0,1] \cap \mathbb{Q}$ is not compact, so a lot of the theory goes out of the window.
Or maybe I'm interested in what happens in infinite dimension, so why not replace the spheres with some compactification of an infinite dimensional Banach space, for example? I have no idea what such a thing would look like.

So far, I've found three things in this direction:

Homotopy groups with coefficients replace the sphere with a Moore space $M(G,n)$ (i.e. a space with a single nonzero reduced homology group). A sphere is in particular a Moore space of type $M(\mathbb{Z},n)$. Unfortunately such Moore spaces are not, in general, co-H-spaces, so $[M(G,n), X]$ is not a group, merely a pointed set. One reference for this seems to be Weibel K-book, but as far as I can tell they are only used as motivation for the definition of K-theory with coefficients (I haven't had the chance to read the book in detail).
Hazewinkel, in Encyclopaedia of Mathematics, mentions something called "toroidal homotopy groups". I haven't been able to find much information about it anywhere and I can only guess it has something to do with tori. (I don't have access to the book, only to a few pages on Google Books (and other people may not even be able to see the same pages as I do))
Last week I saw this preprint about "big fundamental groups" (the interval is apparently replaced with an interval of large cardinality) in the daily arXiv email, which I think pushed me towards this question.
Comment: This doesn't address alternatives, but two possible reasons for the motivation are: (1) Historically, homotopy theory arose from considering the fundamental group $\pi_1(X) = [S^1; X]$ of (based) loops, and expanding that to the higher $[S^n; X]$ seemed like a natural extension; (2) The stable homotopy groups correspond to the spectrum $E_n = \Sigma^n S^0 = S^n$, and the two-point space $S^0$ is the simplest (nontrivial) based space.
Comment: @anomaly Sure, I'm not saying homotopy groups aren't natural objects to consider, I understand they are very important. But note that $\Sigma X = S^1 \wedge X$, so spheres are already hidden here too... What if instead I consider iterates of something like $([0,1] \cap \mathbb{Q}/\sim) \wedge X$? I don't get a spectrum in the traditional sense, obviously.
Comment: @anomaly Good point about obstructions, this is definitely something to consider for applications. BTW, note that spheres/disks are also built into the notion of CW-complexes... They're everywhere! Down with the tyranny of spheres! More seriously this "bias" towards spheres is completely pervasive in algebraic topology, for example: we use simplicial sets to model spaces. Why? Because they're Quillen equivalent to the model category of spaces. You know, the one where weak equivalence are defined in terms of homotopy groups, i.e. maps from spheres...!
Comment: @Najib: the point of CW complexes is that they encode presentations of spaces as iterated homotopy cofibers starting from points. (Note that this description doesn't explicitly mention spheres at all, just a higher categorical universal property.) They have the same relationship to homotopy theory that presentations of groups have to group theory. Simplicial sets and spaces both model $\infty$-groupoids, which are a thing that makes sense independent of any particular model of them.
Comment: Note that I would in particular be interested in some detailed summary of what any of the three items I mention at the end are about, and what they achieve.
Comment: Hmm, I'm not sure. Offhand, I'd say that $\mathbb{Q}^+\wedge X$ would be a badly-behaved space; if we try to set up a homotopy theory with that construction, we wouldn't be able to stay in the world of CW-complexes. (This is less of a problem if you're interested in totally-disconnected spaces.) Maybe we're looking at this the wrong way, though. There are a lot of obstructions that live in the $\pi_n X$; what sorts of obstructions, or other cool things, can we study, and what sorts of invariants like $[E; X]$ can we build to deal with them?
Comment: In rational homotopy theory you are interested in the rational spheres and the rational Moore spaces, but maybe that's not what you had in mind.
Answer:
But after all, $\pi_n(X,*)$ is "merely" the set of morphisms in the homotopy category of pointed spaces from the $n$-sphere to $X$: $\pi_n(X,*) = \hom_{\mathsf{hTop}_*}((S^n,*), (X, *))$. This has always seemed somewhat "biased" to me; spheres are given a preponderant role in the definition.

Spheres emerge naturally out of the relationship between homotopy theory and higher category theory. One example of this is that you might object that the study of $\pi_1$ somehow arbitrarily picks out $S^1$, but in fact you can define $\pi_1$ without mentioning $S^1$ at all, using the theory of covering spaces or locally constant sheaves. One definition is the following: $\pi_1(X, x)$ is the automorphism group of the functor given by taking the stalk of a locally constant sheaf on $X$ at $x$. This is a functor on the homotopy category of reasonable pointed spaces and the circle naturally emerges as the object representing this functor.
Similarly you can describe the fundamental $n$-groupoid $\Pi_n(X)$ of $X$ (which knows about the first $n$ homotopy groups) without mentioning paths at all, using a theory of "higher" locally constant sheaves (locally constant sheaves of $(n-1)$-groupoids, rather than sets).
If you believe one way or another that fundamental $n$-groupoids are reasonable things to study (inductively: if you believe that homotopies are reasonable, then you believe that homotopies between homotopies are reasonable, etc.; this means you care about the interval $[0, 1]$ but it doesn't yet obligate you to care about spheres), then the higher homotopy groups naturally emerge by repeatedly taking automorphisms:

$\pi_1(X, x)$ is the automorphism group of $x$ as an object in the fundamental groupoid $\Pi_1(X)$,
$\pi_2(X, x)$ is the automorphism group of the identity path $x \to x$ as an morphism in the fundamental $2$-groupoid $\Pi_2(X)$,

etc. None of this explicitly requires talking about spheres, but again, these are all very natural functors on pointed homotopy types and spheres represent them.
Said another way, among homotopy types, the $n$-sphere $S^n$ has a universal property: it is the free homotopy type on an automorphism of an automorphism of... of a point. These aren't just arbitrary spaces we picked because we like them; they're fundamental to homotopy theory in the same way that $\mathbb{Z}$ is fundamental to group theory.
Comment: @Qiaochu Yuan: I'd be grateful for a reference to what you call $\Pi_2(X)$ and $\Pi_n(X), n>1. $. Thanks.
Comment: Incidentally, the locally constant sheaf definition above makes sense even on terrible topological spaces, and it should be able to detect "loops" that the usual fundamental group doesn't, e.g. I think it detects the Warsaw circle. At this level of generality I have no idea if it remains homotopy invariant.
Comment: @NajibIdrissi This answer by Eric Wofsey to a question of mine explains that $[0,1]$ can be characterized by a universal property relating to compact Hausdorff spaces, so perhaps that answer combined with Qiaochu's answer means that spheres are arbitrary in defining homotopy groups only to the extent that this universal property that the interval $[0,1]$ satisfies is arbitrary and no more. http://math.stackexchange.com/a/1824082/327486 That being said I can't reasonably claim to understand Qiaochu's answer, so this might be a completely irrelevant remark, in which case I apologize.
Comment: Thanks, these are all insightful remarks. I guess it counts as an answer in the sense that spheres are already quite good for defining homotopy groups, considering how fundamental they are. What follows is contrarian purely for the sake of being contrarian, don't taker it the wrong way: most of the second part of your answer relies on the fact we care about $[0,1]$. What if instead I want to take as basic object something like $[0,1] \cap \mathbb{Q}$ (not compact though) or its closure in $\mathbb{Q}_p$ (not ordered)? It's not clear that spheres would appear naturally then.
Comment: @Najib: sure, but I claim you won't get a reasonable theory that way. I'm trying to convince you here that it's massively overdetermined that homotopy theory as usually developed is a cool and interesting thing to do - think about e.g. the origins of the theory of the fundamental group in the theory of Riemann surfaces. And once again, I don't even need to single out $[0, 1]$ if I instead pay a lot of attention to the theory of locally constant sheaves and its higher relatives.
Answer: The "big" homotopy theory was first defined/explored in a paper J. Cannon and G. Conner wrote several years ago.  It was simply a tool constructed to understand a sort of generalization of the Hawaiian Earring (and its fundamental group).
Consider the one-point compactification of uncountably many open (real) intervals.  The fundamental group of this space is too restrictive, only allowing a loop to traverse countably many loops, whereas the big fundamental group has no such restriction.  So its advantage over the fundamental group is merely a counting problem.  When you're trying to detect holes in spaces which have too high cardinality, or too many points packed in, or something like that.
Consider the long line, with the ends identified--a path cannot make it all the way around, but a "big path" can.  Problems like this arise when you have "huge" spaces, and the big fundamental group is a sort of workaround.
Answer: I can give specific information on the "toroidal" question, which I expect refers to:
Homotopy Groups and Torus Homotopy Groups
Ralph H. Fox
Annals of Mathematics
Second Series, Vol. 49, No. 2 (Apr., 1948), pp. 471-510.
I heard ages ago from Brian Griffiths that Fox was hoping for, but did not succeed in getting, a higher version of the van Kampen Theorem.
Such versions are available, and involve cubes rather than spheres; they do not calculate directly homotopy groups, but some homotopy $n$-types, and moreover they work on certain "structured spaces", either filtered spaces, or $n$-cubes of spaces. There are presentations on my preprint page (...., Paris, Galway, Aveiro)  if you want more information.
To comment on one of your initial bullet points, the work referred to in the last paragraph started in 1965 with disappointment  that the standard Seifert-van Kampen theorem for the fundamental group of based spaces did not yield the fundamental group of the circle, THE basic example in algebraic topology. That was just the start of computations of fundamental groups with which that theorem did not cope.  It turned out one needed more than one base point, hence groupoids.  See this mathoverflow discussion on using more than one base point.
Nov 5, 2016 Here is a recent article on Modelling and Computing Homotopy Types: I developing part of the Aveiro talk.
Comment: The book on Nonabelian Algebraic Topology covers the work on crossed complexes, but does not deal with the work with Loday on cat$^n$-groups, and $n$-cubes of spaces, which is nearer to what Fox wanted. For that, see 74.  ``Computing homotopy types using crossed $n$-cubes of groups'', (pdf) on my publication list.
Comment: Thanks, I've looked at the slides, it definitely looks interesting. Is it all in the book *Nonabelian algebraic topology*?
Answer: One can indeed replace the sphere $S^n$ in the definition of homotopy groups $\pi_n(X,*)=[S^n,X]_*$ by any pointed space $A$, giving the $A$-homotopy groups $\pi_n(X;A)=[\Sigma^n A, X]_*$. As it happens, these $A$-homotopy groups are actually just the (usual) homotopy groups of the mapping space $Map(A,X)$:$$\begin{aligned}
\pi_n(X;A)=[\Sigma^n A, X]_* &\cong [A\wedge S^n, X]_* \\
&\cong [S^n, Map(A,X)]_* \\
&\cong \pi_n (Map(A,X), \text{const})
\end{aligned}.$$
Many tools of homotopy theory can be generalised to the $A$-cellular theory: there are $A$-cellular complexes, obtained by inductively gluing $n$-dimensional $A$-cells $\Sigma^nA \hookrightarrow C\Sigma^nA$ (or taking homotopy cofibers of maps from $\Sigma^n A$), and an $A$-Whitehead theorem : a map between $A$-cellular spaces that induces isomorphisms on all $A$-homotopy groups is a weak equivalence.

This material can be found in Dror Farjoun's 'Cellular spaces, null spaces and homotopy localization'.


How to change logged-in user permission in hook_node_view?

Question: Can anyone please let me know how can we achieve the following scenario
I want to change the role of the logged-in user before viewing the node. When you click on the node for viewing it, I want the roles to be changed and then display the content accordingly with the access permissions.
Answer: using  hook_node_access(),here you can check user role by using
global $user;
$roles=$user->roles;

Comment: I wanted to compare the logged in user is same as the one associated with the node (my understanding on associated with the node means the creator of the node) if they are same then allow the access else deny access to the node.
Comment: Is my understanding correct? The following code is not working as expected. Can anyone please correct me if i'm wrong.

if ($op == 'view') {
      if (user_access('view any ' . $type . ' content', $account) || (user_access('view own ' . $type . ' content', $account))
        {
                global $user;
                if ($user->uid == $node->uid) {
                return NODE_ACCESS_ALLOW;
                }
                else
                {
                return NODE_ACCESS_DENY;
                }
        }

  }
Answer: Use Rules module
Consider using the Rules module for this. The actual details of your question need some further refinement (to better explain what you actually want to achieve, and to include some of your extra comments), but here is a draft version of the rule to do what you are lookiung for:

Event : Content is viewed (located within "Node")
Condition : logged in user = userid associated with the node
Action : Grant role to user

However, since this event only seems to happen "after" the content is viewed, you probably encounter some access denied situation (refer to open issue 1336402 for more details). I haven't been able to find some event like "when a user encounters an access denied" (need to do more research if that's doable). Therefor consider the alternative described below also.
Use Content Access module integration with the Rules module
Another approach might be to use the Content Access module, and the Content Access Rules Integrations module. So that "After saving content" (= Event), you "Give 'authenticated user' the permission to 'view own content' for the specific node" (= Action). That way, the permission is set when the node is edited already (which is not exacty what you are asking for in your question, but would achieve the same result) I believe.
This would be a variation of what is explained in this article also (within "Access Control Customized for Your Needs").
Use Rabbit Hole module
In one of your comments you wrote "I wanted to compare the logged in user is same as the one associated with the node ... if they are same then allow the access else deny access to the node". Even though I've no experience with it, it appears to me that possibly the Rabbit Hole module might be a solution for you. Here is part of what it says on its project page:

... Perhaps you want a user to be able to view nodes that he has created, but no one else's.
Comment: Yes. I need exactly what you have written. But there is no event called "Before viewing the node", is it?
Comment: I enhance my answer (exact event to be used), and added the Content Access alternative to consider. Does this help somehow?
Comment: If I use "content is viewed" event, actions are not executed after opening the node details page but are executed only if you refresh the opened node details page. Content Access module I shall try.
Comment: These modules cannot resolve my problem. Is there any way I can do it in the code itself? I have created a view for nodes and i'm opening the node from there. So can I add something to the code in view/modules/node/ files and achieve this?
Comment: Just discovered a possible alternative for the "Content is viewed" event (to be used in Rules): You may want to try using even "System > Drupal is initializing". Curious to hear if that gets it to work ...
Answer: You can do this by using below modules :

Nodeaccess

Nodeaccess is a Drupal access control module which provides view, edit
  and delete access to nodes. Users with the 'grant node permissions'
  permission will have a grant tab on node pages which allows them to
  grant access to that node by user or role. Administrators can set
  default access controls per content type, and also define which roles
  are available to grant permissions to on the node grants tab.

Userpoints Node Access

The Drupal userpoints nodeaccess module enables you to sell access to
  a single node for a specific category and amount of userpoints.


Having trouble with overfitting XGBoost on a large dataset with many features and samples

Question:
I have tried tuning every hyperparameter to avoid overfitting but I cannot get XGBoost to generalize well. While this dataset is difficult to get excellent results, I have seen a genetic linear regression algorithm do well. So I figure that XGBoost should be able to do at least as well since it is much more complex than a linear regression, and this dataset should have interaction between features. The genetic linear regression was more successful in the sense that train and test rmse both went down, although the rmse scores wouldn't blow your socks off.
Are there any other tricks I can do to prevent this overfitting?
Comment: How are you controlling the number of estimators? I strongly recommend not "hyperparameter tuning to find the best n_estimators" but instead, set "n_estimators" to an unreasonably large number and then use early stopping against a validation set.
Answer: To control overfitting:

train with more samples
reduce the number of features (compare the importances)
reduce the maximum depth
increase the minimum samples at the leaves
Comment: 1. I have 400 features with about 800,000 samples
2. Ok, haven't tried that
3. have set it to 4, still overfits.
4. i have set it to 10% of the number of samples, still overfits.
Comment: I think your main problem is that there are too many features. Try about 30-50 features.
Comment: ok I will try that. out of curiousity, how do you come up with 30-50 features? depends on number of samples?
Comment: I used 5000+ features to train 100k samples once. It turned out that just 25 features would way outperform the 5000+ features.


NSCalendar calendarWithIdentifier throwing error on ios 7

Question: I am creating my app with Xcode 6 and it works fine on ios8. I just tested the app on ios7 and i get this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSCalendar calendarWithIdentifier:]: unrecognized selector sent to class 0x3a78418c

This is the code i am using as part of converting dates from Gregorian calendar to Persian Calendar:
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:@"persian"];

Answer: The +[NSCalendar calendarWithIdentifier] class method is only available on iOS 8/OS X 10.9 and later.
But you can use the designated initializer method instead, this works on all iOS releases:
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:@"persian"];

Answer: It is supposed to work from iOS 8.
+ (NSCalendar *)calendarWithIdentifier:(NSString *)calendarIdentifierConstant NS_AVAILABLE(10_9, 8_0);