History of NFL scoring format

Question: Can anyone tell me why the NFL uses the current scoring format of 6 points plus extra point for a touchdown, 3 points for a field goal, 2 points for a safety?
Is there a history or story behind why they picked this format? Was a different format ever used?
Why was this format chosen over a 5-2-1 format for example?
I don't know if this question has a good answer or not, but I couldn't find anything definitive on this in my research. Does anyone else know something I don't?
Answer: Based on The Anatomy of a Game.
The current scoring rules weren't decided on all at once. They evolved over the years.
At the outset, football was played according to whatever rules the two teams agreed to. The first rules meeting was in 1876. Before this, there was no standard ruleset for the sport of football.
Initially, it was the students at Rutgers, Princeton, Yale, and Harvard who created rules that varied from a strictly kicking game to a game that allowed running the ball.
The first ruleset, created in Princeton in 1871, included these rules related to scoring:

Games are played to to 4 of 7 goals (best of 7)
No player shall toss or carry the ball
Goalposts were 25 feet apart (kicking the ball through the goal posts was the only way to score)

Harvard drafted their own ruleset in 1872, based off of the Princeton/Rutgers rules. Theirs was closer to rugby, due to their Canadian connection with McGill University. Theirs allowed running and throwing:

No player may run with the ball unless pursued by an opponent, and only then so long as pursued
No player may pass or throw the ball unless pursued by an opponent
Scoring was still only by kicking through the goalposts

Yale created a ruleset very similar to Princeton's, prohibiting picking up, throwing, or carrying the ball.
In 1873, Princeton, Rutgers, and Yale met to organize a standard ruleset. The outcome was a set of 12 rules. Out of those, these related to scoring:

Games are to 6 goals. Goals are scored by the ball passing between the goal posts.
No player shall throw or carry the ball.

In 1876, Princeton, Yale, Columbia, and Harvard met to further unify the rulesets (Harvard had not attended the previous meeting due to their commitment to a running/Rugby style of game). The outcome was 61 rules. Here is how they related to scoring:

The rules defined punts, placekicks, and dropkicks
Goalposts now were based on top of a crossbar 10 feet from the ground
Goals are scored by any kick other than a punt that goes through the goalposts
Matches are decided on a majority of touchdowns (touchdowns had a different meaning than today)
A goal equals 4 touchdowns
A touchdown is when a player on the ball on the ground in touch or in goal so that the ball is dead
Players may run. If a player runs with the ball across the goal line and touches it down, it is called a run in.
Backward throws were allowed.
After a touchdown, the ball is brought out for an attempt at a goal (just like the extra point today)
In these rules, the safety was not explicitly stated but it was called a touch-in-goal. A team that has touched down the ball in their own goal were to immediately kick it away. These did not count against the team.

In 1881, the safety was officially included in the rules, and counted against the team, but only in a tie-break situation:

In case of a tie, [play more]. If the game still remains a tie, the side which makes four or more safeties less than their opponent shall win the game.

In 1882, safeties became part of the scoring, and the tie-break advantage switched from kicks to touchdowns:

Four touchdowns takes precedence over a goal from the field (which is worth four touchdowns)
Two safeties equals one touchdown

This was all part of an overall strategy to increase the pace of the game and eliminate stalling that occurred under the previous rules. Downs were also added at this time.
In early 1883, scores were first attached to the various ways of scoring:

Safety: 1 point
Touchdown: 2 points
Goal after touchdown: 4 points
Goal from the field: 5 points

Later in 1883, scores were further amended:

Safety: 2 points
Touchdown: 4 points
Goal after touchdown: 4 points
Goal from the field: 5 points

In 1887, scores became:

Safety: 2 points
Touchdown: 5 points
Goal after touchdown: 1 point
Goal from the field: 5 points

In 1904 and 1909, the goal from the field was reduced to 4, and then 3 points.
In 1912, touchdowns became worth 6 points.
That is the history. It was never a decision involving the current scoring system versus something dramatically different. They were all incremental changes, being made to encourage certain types of play.
Comment: Note that football was an offshoot of rugby - therefore it was adopting a lot of the same rules rugby had.  The two main differences in early football were the stoppages in play and downs.
Answer: The evolution of the scoring system in American Football is described in https://en.wikipedia.org/wiki/History_of_american_football and other nearby articles.
The game evolved from Rugby Union, and at the time, the scoring just counted goals (similar to association football where this system is obviously still in place despite the rules of Rugby being officially 19-years older than soccer's (The Football Association) rules). Reaching the end zone merely gave you a chance to kick at the goal.  Over time, both American football and rugby tweaked the scoring system to put more emphasis on reaching the end zone versus the kicking game.
The reason they arrived at these particular numbers was obviously just a long series of tweaking until the administrators arrived at a balance that they liked.  For the same reason, numerous other rules are tweaked every year.

History of NFL scoring format


Use success() or complete() in AJAX call

Question: I want to understand the AJAX call below, in terms of the complete() method;
When I replace complete() with success(), I get an empty responseText just  as with the AJAX error() method.
On the other hand, when I leave the complete() method there as it is, everything works as expected.
Is it that success() returns earlier than complete()?
$("#formnaw").submit(function() {
  var fnc = invoerFnc.attr("value");
  var vnaam = invoerVnaam.attr("value");
  var anaam = invoerAnaam.attr("value");
  var str1 = invoerStr1.attr("value");
  var nr1 = invoerNr1.attr("value");
  var pc1 = invoerPc1.attr("value");
  var pl1 = invoerPl1.attr("value");
  var tel1 = invoerTel1.attr("value");
  var mob1 = invoerMob1.attr("value");
  var em1 = invoerEm1.attr("value");
  var goknop = $("#formnaw > .instelling_go");
  //we deactiveren de submit knop tijdens het verzenden
  goknop.attr({
    disabled: true
  });
  goknop.blur();
  //stuur de post variabelen naar livetabs.php
  $.ajax({
    type: "POST",
    url: "registraties/instellingenact.php",
    data: "actie=wijzignaw&vnaam=" + vnaam + "&anaam=" + anaam + "&functie=" + fnc + "&straat=" + str1 + "&nr=" + nr1 + "&postcode=" + pc1 + "&plaats=" + pl1 + "&tel=" + tel1 + "&mob=" + mob1 + "&email=" + em1,
    timeout: 5000,
    success: function(data, textStatus) {
        alert('bij success');
        //doe iets
      } //EINDE success
      ,
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        if (textStatus == 'timeout') {
          //doe iets
        } else if (textStatus == 'error') {
          //doe iets
        }
        //her-activeer de zend knop
        goknop.attr({
          disabled: false
        });
      } //EINDE error
      ,
    complete: function(data) {
        updatelijst.append(data.responseText + "
");
        if (data.responseText.indexOf("Fout") != -1) {
          $('#formnaw').find('td.foutnr1').prepend(data.responseText);
        } else {
          updatelijst.animate({
            opacity: 'show'
          }, 1000, function() {});
        }
        //her-activeer de zend knop
        goknop.attr({
          disabled: false
        });
      } //EINDE complete
  }); //EINDE ajax
  //we stoppen het standaard gedrag van een submit, zodat de pagina niet wordt vernieuwd.
  return false;
});

Answer:
Is it that success() returns earlier than complete()?

Yes; the AJAX success() method runs before the complete() method.
Below is a diagram illustrating the process flow:

It is important to note that

The success() (Local Event) is only called if the request was successful (no errors from the server, no errors with the data).
On the other hand, the complete() (Local Event) is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.

... more details on AJAX Events here.
Answer: complete executes after either the success or error callback were executed.
Maybe you should check the second parameter complete offers too. It's a String holding the type of success the ajaxCall had.
The different callbacks are described a little more in detail here jQuery.ajax( options )

I guess you missed the fact that the complete and the success function (I know inconsistent API) get different data passed in. success gets only the data, complete gets the whole XMLHttpRequest object. Of course there is no responseText property on the data string.
So if you replace complete with success you also have to replace data.responseText with data only.
success

The function gets passed two
  arguments: The data returned from the
  server, formatted according to the
  'dataType' parameter, and a string
  describing the status.

complete

The function gets passed two
  arguments: The XMLHttpRequest object
  and a string describing the type of
  success of the request.

If you need to have access to the whole XMLHttpRequest object in the success callback I suggest trying this.
var myXHR = $.ajax({
    ...
    success: function(data, status) {
        ...do whatever with myXHR; e.g. myXHR.responseText...
    },
    ...
});

Comment: complete gets the whole XMLHttpRequest object. success gets content of the XMLHttpRequest.responseText property. Your code above should work without the success callback too, without any sideeffects as it does nothing anyway.

But there is a difference in using success or complete. Success only gets called when the request completed successfully. But the complete callback fires on success and on error. Check out http://docs.jquery.com/Ajax_Events to understand better in which order and under which circumstances which callbacks are executed by jquery
Comment: oops, comment came at the same time
So, if I get this right. The complete function contains all the information I need. Success contains less unless you pass two arguments in the function. I hope I am not getting stupid, but is complete like I used then not enough all the time? Or is it that success is more lightweight??
Comment: Also in addition to my last comment, will my code from above still cath the error. In short, will it do everything without any drawbacks if I leave out the success option. Sorry if it's sounding like I don't understand it yet. It's a little confusing to me.
Comment: I edited my question to contain the complete code I used
It doesn't give any errors, but I can probably cut the success option out. If the result is the same.
Answer: "complete" executes when the ajax call is finished. "success" executes when the ajax call finishes with a successful response code.
Comment: thanks,but to be clear, do I have to use the code to execute under a complete option and not under success. And will the error option also work with the complete option alone?
Comment: or, it suggests that I do not get a success responsecode, strange?
Answer: Well, speaking from quarantine, the complete() in $.ajax is like finally in try catch block.
If you use try catch block in any programming language, it doesn't matter whether you execute a thing successfully or got an error in execution. the finally{} block will always be executed.
Same goes for complete() in $.ajax, whether you get success() response or error() the complete() function always will be called once the execution has been done.


Why is my .bashrc and .bash_profile different from echo $path

Question: i was trying to add something to my path. But since i'm nog very familiar with the terminal i think i messed something up.
when i do echo $PATH i get:
/Users/christoph/.node/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

but when i open .bashrc i see this:
alias homestead=~/.composer/vendor/bin/homestead

echo 'export PATH="$PATH:$HOME/.composer/vendor/bin"' >> ~/.bashrc

export PATH="$PATH:$HOME/.composer/vendor/bin"

And when i open .bash_profile i see this:
export PATH="$HOME/.node/bin:$PATH"

I want to do this step : (to install laravel valet)

Install Valet with Composer via composer global require laravel/valet.
  Make sure the ~/.composer/vendor/bin directory is in your system's
  "PATH".

And i am very confused on how i should add this path. Also in which file do i need to put it?
I am using MAC OSX El Capitan
Comment: see if this helps: https://unix.stackexchange.com/questions/26047/how-to-correctly-add-a-path-to-path
Answer: Remove this line from your .bashrc!!!
echo 'export PATH="$PATH:$HOME/.composer/vendor/bin"' >> ~/.bashrc

It appends a new line to your bashrc each time you log in.
Overall you should modify your PATH env variable only in single file (.bash_profile, but many people will make an error of modifying .bashrc). It works like this: PATH is list of directories splitted by ':' character, $PATH expands to previous value of this list. Example:
export PATH=/fooo:/barr:/bazzz

Places exactly these tree directories in PATH variable. In your case you should have following line in your .bash_profile:
export PATH=$PATH:$HOME/.node/bin:$HOME/.composer/vendor/bin

And remove all unnecessary aliases.
Comment: It's OK - you can remove this line from bashrc completely :)
Comment: thanks for your answer! Can you explain why the use of aliases is bad practive? Also since i use that path in my bash_profile, what should be the path inside my main .bashrc file? Just an empy file? or the basic path like this: export PATH=$PATH:$HOME ?
Comment: if i echo $path after these changes i get the following : `/Users/christoph/.node/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`, the changes are not visible it seems.
Comment: You need to login again (or you can invoke `source .bash_profile`) for it to update. Aliases are not bad practice, but they are designed for something different: modifying behaviour of existing commands - e.g.: I have defined following aliases: `alias ll='ls -l'` `alias ssh='ssh -X'`, `alias ocaml='rlwrap ocaml'`, etc.
Comment: ok, that makes sense . My bash_profile has the longer path and is working now, and my .bashrc file has this path : export PATH="$PATH" .  is this correct or should i change the main file to something different?


Calculate the end of the previous quarter

Question: I'm looking for an elegant and pythonic way to get the date of the end of the previous quarter.
Something like this:
def previous_quarter(reference_date):
   ...

>>> previous_quarter(datetime.date(2013, 5, 31))
datetime.date(2013, 3, 31)

>>> previous_quarter(datetime.date(2013, 2, 1))
datetime.date(2012, 12, 31)

>>> previous_quarter(datetime.date(2013, 3, 31))
datetime.date(2012, 12, 31)

>>> previous_quarter(datetime.date(2013, 11, 1))
datetime.date(2013, 9, 30)

Edit: Have I tried anything?
Yes, this seems to work:
def previous_quarter(ref_date):
    current_date = ref_date - timedelta(days=1)
    while current_date.month % 3:
        current_date -= timedelta(days=1)
    return current_date

But it seems unnecessarily iterative.
Comment: Have you tried anything?
Comment: Looking at my solution it clearly won't work if `ref_date.month` is divisible by 3...
Answer: You can do it the "hard way" by just looking at the month you receive:
def previous_quarter(ref):
    if ref.month < 4:
        return datetime.date(ref.year - 1, 12, 31)
    elif ref.month < 7:
        return datetime.date(ref.year, 3, 31)
    elif ref.month < 10:
        return datetime.date(ref.year, 6, 30)
    return datetime.date(ref.year, 9, 30)

Comment: I like it- clean, simple, and effective.
Answer: Using dateutil:
import datetime as DT
import dateutil.rrule as rrule

def previous_quarter(date):
    date = DT.datetime(date.year, date.month, date.day)
    rr = rrule.rrule(
        rrule.DAILY,
        bymonth=(3,6,9,12),    # the month must be one of these
        bymonthday=-1,         # the day has to be the last of the month
        dtstart = date-DT.timedelta(days=100))
    result = rr.before(date, inc=False)  # inc=False ensures result < date
    return result.date()

print(previous_quarter(DT.date(2013, 5, 31)))
# 2013-03-31
print(previous_quarter(DT.date(2013, 2, 1)))
# 2012-12-31
print(previous_quarter(DT.date(2013, 3, 31)))
# 2012-12-31
print(previous_quarter(DT.date(2013, 11, 1)))
# 2013-09-30

Answer: Exploit the data pattern involved and turn the problem into a table-lookup - your classic space-time tradeff:
from datetime import date

PQTBL = (((12,31,-1),)*3 + ((3,31,0),)*3 + ((6,30,0),)*3 + ((9,30,0),)*3)

def previous_quarter(ref):
    entry = PQTBL[ref.month-1]
    return date(ref.year+entry[2], entry[0], entry[1])

Comment: should be: `return date(ref.year+entry[2], entry[0], entry[1])`  (sign should be changed)
Comment: @Gerrat: Fixed. Thank you.
Answer: Find the first day and month of the quarter, then use relativedelta to subtract a day.
from dateutil.relativedelta import relativedelta
def previous_quarter(ref):
    first_month_of_quarter = ((ref.month - 1) // 3) * 3 + 1
    return ref.replace(month=first_month_of_quarter, day=1) - relativedelta(days=1)

Answer: It's almost certain you would be happier using pandas (a python library), it has many functions for "business time" data.
http://pandas.pydata.org/pandas-docs/dev/timeseries.html
Comment: It's not an unreasonable suggestion, but perhaps you'd like to show an example?
Answer: Reworked Justin Ethier's code for a "next quarter" version. Also added timezone via pytz and strftime formatting. @justin-ethier
import pytz
from datetime import datetime, timedelta
import datetime as dt

def nextQuarter():
    ref = datetime.now(pytz.timezone('America/New_York'))
    if ref.month < 4:
        next = dt.datetime(ref.year, 3, 31, 23, 59, 59).strftime('%m-%d-%Y %H:%M:%S')
    elif ref.month < 7:
        next = dt.datetime(ref.year, 6, 30, 23, 59, 59).strftime('%m-%d-%Y %H:%M:%S')
    elif ref.month < 10:
        next = dt.datetime(ref.year, 9, 30, 23, 59, 59).strftime('%m-%d-%Y %H:%M:%S')
    else:
        next = dt.datetime(ref.year + 1, 12, 31, 23, 59, 59).strftime('%m-%d-%Y %H:%M:%S')
    return next
next = nextQuarter()

Answer: import datetime
def previous_quarter(ref):
    quarter = (ref.month - 1) // 3
    prev_quarter = (quarter - 1) % 4
    return datetime.datetime(ref.year if quarter>0 else ref.year-1, prev_quarter*3+1, 1)

Answer: Solution using only python's datetime library -
import datetime

def get_quarter_end(dt):
     '''
         given a datetime object, find the end of the quarter
     '''
     quarter_of_month = int((dt.month-1)/3 + 1)
     #======================================================
     # find the first day of the next quarter
     #======================================================
     # if in last quarter then go to the next year
     year = dt.year + 1 if quarter_of_month==4 else dt.year
     # if in last quarter then month is january (or 1)
     month = 1 if quarter_of_month==4 else (quarter_of_month*3) + 1

     first_of_next_quarter = datetime.datetime(year  = year,
                                               month = month,
                                               day   = 1
                                              )
     # last day of quarter for dt will be minus 1 day of first of next quarter
     quarter_end_dt = first_of_next_quarter - datetime.timedelta(days=1)
     return quarter_end_dt

if __name__=='__main__':
    dt = datetime.datetime.strptime('2016-07-15', '%Y-%m-%d')
    target_dt = get_quarter_end(dt)

Comment: Is this Python 2 or 3? I ask because I'm wondering if you meant `int((dt.month-1)/3 + 1)` or `int((dt.month-1)//3 + 1)`. NVM: it works in Python 3 just fine. But you could do `quarter_of_month = (dt.month-1)//3+1`, to be more concise.
Answer: and if you want to retreive the last fours quarter you can do this
    if ref.month < 4:
        list1 = [datetime.date(ref.year - 1, 12, 31),
                            datetime.date(ref.year - 1, 9, 30),
                            datetime.date(ref.year - 1, 6, 30),
                            datetime.date(ref.year - 1, 3, 31)]

        list1 = [i.strftime('%Y%m%d') for i in list1]

        return list1

    elif ref.month < 7:
        return [datetime.date(ref.year, 3, 31),
                datetime.date(ref.year - 1, 12, 31),
                datetime.date(ref.year - 1, 9, 30),
                datetime.date(ref.year - 1, 6, 30)]
    elif ref.month < 10:
        return [datetime.date(ref.year, 6, 30),
                datetime.date(ref.year, 3, 31),
                datetime.date(ref.year - 1, 12, 31),
                datetime.date(ref.year - 1, 9, 30)]

    return [datetime.date(ref.year, 9, 30),
            datetime.date(ref.year, 6, 30),
            datetime.date(ref.year, 3, 30),
            datetime.date(ref.year - 1, 12, 31)]


Struct e lista encadeada

Question: Criei uma estrutura do tipo pessoa e pretendo usá-la em uma lista encadeada, porém o seguintes erros aparecem:

'No' has no member named 'dados', 'No' has no member named 'prox' e  unknow type name 'p'.

O programa nem chegou a rodar, alguém pode me ajudar?
O arquivo .h é o seguinte:
#ifndef Pessoa
#define Pessoa

typedef struct pessoa{
    char nome[25];
    char sobrenome[25];
    int registro;
}Pessoa;

typedef struct no{
    Pessoa dados;
    struct no *prox;
}No;

typedef struct lista{
    No *cabeca;
    No *cauda;
    int tamanho;
}Lista;

No* criaNo(Pessoa p);
Lista* criaLista();
void inserir(Lista *l, Pessoa p, int posicao);
void remover(Lista* l, int registro); //pesquisa registro e remove a pessoa
void imprimeLista(Lista* l);
void destruirLista(Lista* l);

#endif

O arquivo .c é o seguinte:
#include <stdio.h>
#include <stdlib.h>
#include "Pessoa.h"

No* criaNo(Pessoa p)
{
    No* n;
    n=(No*)malloc(sizeof(No));
    n->dados = p;
    n->prox = NULL;
    return n;
}

Lista* criaLista()
{
    Lista* l = (Lista*)malloc(sizeof(Lista));
    l->cabeca = NULL;
    l->cauda = NULL;
    l->tamanho = 0;
    return l;
}
void inserir(Lista *l, Pessoa p, int posicao);

{
     //já está pronta, porém não achei necessário colocá-la
}

void remover(Lista* l, int registro)
{
     //já está pronta, porém não achei necessário colocá-la
}

void imprimeLista(Lista* l)
{
    //já está pronta, porém não achei necessário colocá-la
}

void destruirLista(Lista *l)
{
    //já está pronta, porém não achei necessário colocá-la
}

Comment: Você viu este `;` sobrando no `.c`? `void inserir(Lista *l, Pessoa p, int posicao);`. Foi só quando passou para cá? O programa compila? Como você chama para testar? Só chama o `CriaLista()`? E o `CriaNo()` E chamado também? Em que linhas ocorrem os erros?
Comment: Confere se estas a incluir o ficheiro .h certo. Chama-se "Pessoa.h" em maiúsculas?
Answer: Veja, o que está acontecendo é que você está definindo a palavra Pessoa como uma sequência vazia de caracteres para ser substituída pelo pré-procesador. Por causa do #define Pessoa, o que está sendo realmente compilado é:
typedef struct pessoa{
    char nome[25];
    char sobrenome[25];
    int registro;
};
typedef struct no{
    dados;
    struct no *prox;
}No;
typedef struct lista{
    No *cabeca;
    No *cauda;
    int tamanho;
}Lista;
No* criaNo( p);
Lista* criaLista();
void inserir(Lista *l, p, int posicao);
void remover(Lista* l, int registro); //pesquisa registro e remove a pessoa
void imprimeLista(Lista* l);
void destruirLista(Lista* l);

Veja que toda ocorrência da palavra Pessoa desapareceu, por causa do seu #define Pessoa (gerei esse código através do comando gcc -E -C -P pessoa.h). Se você tivesse usado #define Pessoa Animal, toda ocorrência de Pessoa seria substituída por Animal.
Acredito que o que você está tentando fazer com #define Pessoa é usar "include guards". Siga o link (em inglês) para mais informações uteis de como faze-lo. Em geral, tome cuidado para que as palavras que você usa não colidam com macros de pré-processador.
Não tem problema a struct e o seu typedef terem o mesmo nome. No seu lugar eu teria simplesmente feito:
typedef struct Pessoa {
  /*...*/
} Pessoa;

Além disso, trocaria o #ifndef/#define Pessoa para #ifndef/#define PESSOA_H
Answer: Minha solução para seu problema ficou da seguinte maneira (Pessoa.h):
#ifndef Pessoa
#define Pessoa

struct pessoa{
    char nome[25];
    char sobrenome[25];
    int registro;
};

typedef struct no{
    struct Pessoa dados;
    struct no *prox;
}No;

typedef struct lista{
    No *cabeca;
    No *cauda;
    int tamanho;
}Lista;

No* criaNo(struct Pessoa p);
Lista* criaLista();
void inserir(Lista *l, struct Pessoa p, int posicao);
void remover(Lista* l, int registro); //pesquisa registro e remove a pessoa
void imprimeLista(Lista* l);
void destruirLista(Lista* l);

#endif

Como pode ver removi o typedef da struct pessoa.
Answer: O problema era o conflito com seu #Define Pessoa...
vc pode alterar a diretiva e colocar

#ifndef __PESSOA_H__
#define __PESSOA_H__
   // ... aqui seu código usando typedef
#endif

Struct e lista encadeada


Proving a set is bounded.

Question: Let  $E = \{x \in\mathbb R^p : \sum_{i = p}^p X_i^2/\alpha_i^2 \leq 1\}$
Prove that $E$ is closed and bounded.
To prove that $E$ is closed I used the fact that the boundary of the set $E$ is equal to $\{x \in\mathbb R^p : \sum_{i = p}^p X_i^2/\alpha_i^2 = 1\}$ and the boundary is contained in the $E.$ So $E$ is closed.
However I do not know how to prove the fact that it is bounded.
Comment: Hint: If your notation means what I think it means, then notice that this is the equation of a filled in hyperellipsoid. This lies inside the ball of radius equal to the length of the semi major axis. Let $\alpha = max( \alpha_i )$, then $E \subset E'$ where $E' = \{x \in \mathbb{R}^p : \sum_{i=1}^p X_i^2/\alpha^2 \leq 1\}$ and so lies within a ball of radius $\alpha$ so is bounded.
Comment: Yes! Note the implication that $\sum_{i=1}^p X_i^2/\alpha_i^2 \leq 1 \implies \sum_{i=1}^p X_i^2/\alpha^2 \leq 1$ since increasing the denominator on each term ensures the sum is less than or equal to before. Or you could see this geometrically as the equation of a hyperellipsoid inside a hypersphere.
Comment: So if I choose the maximum{$\alpha_i$} then E is contained in the sum of the elements taking the maximum?
Comment: @nicomezi No that wouldn't work. Take the case $\frac{x^2}{2^2} + y^2 \leq 1$. This does not lie within the set $x^2 + y^2 \leq 1$. If we follow the logic of the math above, choosing a max $\alpha$ corresponds to dividing by a bigger number so each term is less than or equal to before, so the inequality still holds.
Comment: Note my edits to the question. In the expression $$ \{x \in\mathbb R^p : \sum_{i = p}^p X_i^2/\alpha_i^2 = 1\} $$ the $\{\text{curly braces}\}$ should be inside of MathJax, as should the expression $E={}.$ And I changed $R^p$ to $\mathbb R^p.$ Are you taking it to be conventional that the scalar components of a vector denoted by a lower-case $x$ are denoted by capital $X_i \text{ ?} \qquad$
Comment: @OsamaGhani Thank you. I thought that you couldn't put a ball inside an ellipsoid, but by placing the radius as the maximum semi-axis you guarantee it
Comment: Thank you @MichaelHardy, I will follow such format from now on. Yes, that is the convention I have followed.
Answer: To see that the set
$E = \left \{ x = (X_1, X_2, \ldots X_p) \in \Bbb R^p \mid \displaystyle \sum_1^p \dfrac{X_i^2}{\alpha_i^2} \le 1 \right \} \tag 1$
is bounded, let
$\mu = \max \{ \vert \alpha_i \vert, \; 1 \le i \le p \}; \tag 2$
then
$\dfrac{1}{\mu^2} \le \dfrac{1}{\vert \alpha_i \vert ^2} = \dfrac{1}{\alpha_i^2}, \; 1 \le i \le p, \tag 3$
whence
$\dfrac{X_i^2}{\mu^2} \le \dfrac{X_i^2}{ \vert \alpha_i \vert^2} = \dfrac{X_i^2}{\alpha_i^2}, \; 1 \le i \le p; \tag 4$
then for $x = (X_1, X_2, \ldots, X_p) \in E$ we have
$\displaystyle \sum_1^p \dfrac{X_i^2}{\mu^2} \le \sum_1^p \dfrac{X_i^2}{\alpha^2} \le 1, \tag 5$
and thus, upon multiplication by $\mu^2$,
$\displaystyle \sum_1^p X_i^2 \le \mu^2, \tag 6$
which shows that every $x \in E$ lies in the sphere of radius $\mu$ centered at the origin; thus $E$ is a bounded set.
As for $E$ being closed, the easiest approach here, I think, is to show that $\bar E$, the complement of $E$, is open; to see this, we use the fact that the function
$f(x) =  \displaystyle \sum_1^p \dfrac{X_i^2}{\alpha_i^2} \tag 7$
is continuous, which I think is quite evident; then clearly
$E = \{x \in \Bbb R^p \mid f(x) \le 1 \} = f^{-1}([0, 1]), \tag 8$
so
$\bar E = \{x \in \Bbb R^p \mid f(x) >  1 \} = f^{-1}((1, \infty)); \tag 9$
since the inverse image of an open set under a continuous mapping is open, we see that $\bar E$ is open in $\Bbb R^p$, whence $E$ is closed, being the complement of the open $\bar E$.
Answer: Let $\alpha = max(\alpha_i)$ then if E is as you previously described it, then let $E_2$ be the ball of radus equal to the length of the major semi-axis ( defined as $max(\alpha_i)$. Clearly E is a subest of $E_2$ so it is then bounded
Answer: Try to get a lower bound on $\sum\frac{x_i^2}{\alpha_i^2}$ involving the Euclidean norm of $x$. For example:
$$\sum\frac{x_i^2}{\alpha_i^2}\geq\min_i\left(\frac1{\alpha_i^2}\right)||x||_2^2$$

Proving a set is bounded.


Derivative of $\int \limits _x^{x^2} f(t) dt$ with respect to $x$

Question:
Suppose that $f$ is continuous on $\Bbb R$. Denote $$G(x) := \int \limits _x^{x^2} f(t) dt$$ Calculate $G'(x)$.
  Check your expression for $G'$ works for $f(t) \equiv 1$

I've started with $G'(x) = 2xf({x^2}) - f(x)$ from differentiating the integral, but I'm not certain of where to go from here.
Comment: You forgot about the Chain Rule.
Comment: That is, what is $\int_{x}^{x^2} 1\,dt$?
Comment: Thanks for pointing out; it was a transcription error.
Comment: So, what is $G(x)$ when $f(x)\equiv 1$?
Comment: After the edit, I'm not quite sure I see what the OP is asking or where (s)he is stuck.
Comment: @ClementC. Sorry, I wasn't sure what end result I should be looking for. I now have an equality for $G'(x) = 2xf({x^2}) - f(x) = 2x - 1$. This satisfies the question, right?
Comment: Yes, IMO. You computed the general expression for $G^\prime$ in terms of $f$. You instantatied it (and verified) for the specific case of $f=1$. That is all that is asked.
Comment: Well, no, when $f(x)=1$, compute $G(x)$ exactly, then compute $G'(x)$ from there, then show that it agrees with $G'(x)=2xf(x^2)-f(x)$. @henbimsworth
Answer: Let $$F(x) = \int_a^x f(t) dt$$
$$G(x) = F(x^2)-F(x)$$
$$G'(x) = 2xf(x^2)-f(x)$$
If $f(x)=1, G(x) = \int_x^{x^2} f(x)dx = x^2-x$
So $G'(x) = 2x-1 = 2xf(x^2)-f(x)$
Comment: Sorry, I misread
Comment: @ThomasAndrews, it's edited


MongoDB find all not in this array

Question: I'm trying to find all users except for a few, like this:
// get special user IDs
var special = db.special.find({}, { _id: 1 }).toArray();

// get all users except for the special ones
var users = db.users.find({_id: {$nin: special}});

This doesn't work because the array that I'm passing to $nin is not and array of ObjectId but an array of { _id: ObjectId() }
Variable special looks like this after the first query:
[ { _id: ObjectId(###) }, { _id: ObjectId(###) } ]

But $nin in the second query needs this:
[ ObjectId(###), ObjectId(###) ]

How can I get just the ObjectId() in an array from the first query so that I can use them in the second query?
Or, is there a better way of achieving what I'm trying to do?
Comment: Possible duplicate of [Find users who has not invited any user](http://stackoverflow.com/questions/40626075/find-users-who-has-not-invited-any-user)
Answer: Use the cursor.map() method returned by the find() function to transform the list of { _id: ObjectId(###) } documents to an array of ObjectId's as in the following
var special = db.special.find({}, { _id: 1 }).map(function(doc){
    return doc._id;
});

Another approach you can consider is using the $lookup operator in the aggregation framework to do a "left outer join" on the special collection and filtering the documents on the new "joined" array field. The filter should match on documents whose array field is empty.
The following example demonstrates this:
db.users.aggregate([
    {
        "$lookup": {
            "from": "special",
            "localField": "_id",
            "foreignField": "_id",
            "as": "specialUsers" // <-- this will produce an arry of "joined" docs
        }
    },
    { "$match": { "specialUsers.0": { "$exists": false } } } // <-- match on empty array
])

Comment: @17xande you don't even need arrow function. how about `let special = db.special.distinct('_id')`?
Comment: Turns out you can even use arrow functions - .map(doc => doc._id)
Comment: @felix Thanks for noticing the typo
Comment: @17xande Indeed, since with MongoDB 3.2, the javascript engine used for both the mongo shell and for server-side javascript in mongod changed from V8 to SpiderMonkey thus it has support for features like arrow-functions, destructuring assignment, for-of loops, and generators
Comment: @Styvane Interesting approach. Wouldn't that introduce extra overhead on a large set of documents since it would have to double check for unique values? In this case the values would all be unique since they're IDs, but I assume it would still do that check anyway?
Comment: @17xande [`_id` are always unique](https://docs.mongodb.com/v3.2/reference/glossary/#term-id).

MongoDB find all not in this array


Probability that a book with $200$ pages has $3$ misprints at most using Poisson approximation

Question: A publisher assumes that when printing a typical book, the probability for a misprint on a page is $1.25$%.
I'm trying to find out these two things:

What is the probability that on a book with $200$ pages three misprints are made at most?
How can one calculate the above using the Poisson limit theorem?

I think the probability that each misprint appears on a given page is $p = \frac{1}{n}$.
Exactly three would be $\binom{m}{3}p^3(1-p)^{m-3}$.
$$\binom{200}{3}(\frac{1}{200})^3 (1-\frac{1}{200})^{200-3} = 0.0612 = 6,12 \text{%}$$
Is that correct?
I know that the poisson limit theorem is defined like this:
$$\lim_{n \to \infty} \binom{n}{k}p^k_n(1-p_n)^{n-k} = e^{-\lambda} \frac{\lambda^k}{k!}$$
where $p_n$ is a sequence of real numbers in $[0,1]$ so that the sequence $np_n$ converges to a finite limit $\lambda$.
I tried
$$P(X \leq 3) = \frac{e^{-1}1^0}{0!} + \frac{e^{-1}1^1}{1!} + \frac{e^{-1}1^2}{2!} + \frac{e^{-1}1^3}{3!}$$
but this doesn't give the answer as above.
Any help is appreciated!
Comment: Nothing to do with `stochastic-calculus`.
Answer: This might be a useful approach to consider, based on my reading of the information:
The probability of a page containing a misprint is given as 1.25%.  I interpret this to imply $p=0.0125$.
To determing the probability of having exactly 3 misprinted pages out of 200, using the binomial distribution, one then has:
$$
P(k=3)=\binom{200}{3} p^{3}(1-p)^{\left(200-3\right)}
$$
$$
\binom{200}{3} = \frac{200!}{3!(200-3)!} = \frac{200 \times 199 \times 198}{6}=1313400
$$
$$
P(k=3)=\binom{200}{3} p^{3}(1-p)^{\left(200-3\right)} = 1313400 \times 0.0125^{3} \times (1-0.0125)^{197} = 0.215246
$$
Comparing to the Poisson distribution,
$$
P(k=3)=\frac{\lambda^{k}e^{-\lambda}}{k!}
$$
let $\lambda=pn= 0.0125 \times 200=2.5$, we have
$$
P(k=3)=\frac{2.5^{3}e^{-2.5}}{6}=0.2137630
$$
To compute the "at most 3", I believe it requires adding the contributions of $k=0,k=1,k=2$ to the one for $k=3$.
I hope this helps.
Comment: Thank you for the clarification!! It helped me a lot


Multi-dimentional packed parameter declaration using function

Question: Recently I am thinking pre-calculating all necessary parameters using simple mathematical equations before instantiating logic units in generate struct. In the case where I need to have a 2-D parameter, it's easy if the 2-D array is a set of fixed values, such as
parameter para_1[1:0][2:0] = '{2{3{0}}};.
But what I want is a function that dictates the values, such that complicated equations can be implemented inside the function before assigning the return values to the parameter.
Ideally I want something as follows:
function func01 [1:0][1:0] (input int test);
  int index;
  for (index=0; index<=2; index++) begin
    func01[index] = index + $floor(index/2) + $mod(index, 2) + test;
  end
endfunction

parameter test1 = 1;
parameter logic test2 [1:0][1:0] = func01(test1);

But ModelSim complains about the first line of code straightaway - ** Error: (vlog-13069) near "[": syntax error, unexpected '[', expecting ';' or '('.
Ultimately the idea is to have a block that calculates all parameters/constants at elaboration time, so that these can be used in generate block for instantiation, also at elaboration time.
Hope it makes sense, and thanks a lot in advance.
Best,
Taihai
Answer: First, if you want packed arrays, the dimension ranges goes to the left of the array name. And I suggest using an explicit data type.
parameter bit [1:0][2:0] para_1 = '{2{3{0}}};.

Then, the return type of function declaration comes before the function name.
function bit [1:0][1:0] func01  (input int test);

BTW if you want the return type of a function to have an unpacked dimension, you must use a typedef, which is a good practice in any case.
typedef bit [1:0] myParam_t [2:0];
parameter myParam_t para_1 = '{default:0};
function myParam_t func01  (input int test);

Comment: Thanks a lot for this @dave_59. The title and the content was meant to do with unpacked arrays, not packed. Sorry. And your solution seems to be what I am after on the `typedef` side. However, ModelSim doesn't like system function (e.g. $floor) in function block `System functions may not be used in a constant function.`. Is there any get-around?
Comment: You will need to use the SystemVerilog equivalent operator (`%` for mod) or write a replacement equation (`let floor(val) = int'(val) > val ? int'(val) -1 : int'(val);` for floor)


Guitar pedal blocks sound when I engage

Question: i don't know if this is the right place to ask, but it's music related, so i'll give it ago.
I recently got into guitar, and i have just aquired an caline cp-68 distortion/delay pedal. I plugged the output into my Fender mustang I V.2 amp and connected the pedal to a 9 volt battery.
Plugged my guitar into the input and started playing. Everything seemed fine, until i enganged the distortion effect, the all sound stopped. I turned some of the knobs and still no sound. So i disenganged distortion and the sound came back.
Then i tried enganging the delay and the sound stopped again!
I've had the knobs on many different settings, and checked the volume on my amp, but i get no sound when i engange. Googeling doesn't bring any answers either.
Comment: "... and connected the pedal to a [decidedly unpleasant to lick?] 9 volt battery."
Answer: With the pedal "off" your signal is routed past the effect, which is why that works.
With the pedal "on" the signal is routed into the effect so any problem with the effect will become noticeable. The problem is that over the internet we cannot see what is wrong with your pedal. It could be a fault with the effect, or possibly a cable, but I would first check the battery:
Are you getting 9 volts, and is it connected the right way round? This is easy to check, and cheap to sort out.
Check all jack connectors are seated fully - sometimes they can cause issues if not fully in. And are they connected the right way? In and Out the right way round?
Answer: One possibility is the battery. I bought a handful of battery connectors to use for mini pedals that don't have room for a battery inside. Unfortunately, many cheap battery adapters have the wrong polarity since they're intended for Arduino or other electronic gadgets that are center-positive. So make sure the battery is connected with the correct center-negative polarity (for most pedals).
Answer: Once in a while a person misunderstands how to connect a new pedal. Just to make certain it's hooked up correctly, the instrument plugs into the input connector, and the output connects to the input of the amplifier or to the input of the next in line foot pedal effect. If things are plugged in backwards, the effect will not pass the signal when the effect is switched in. Also, double check the battery, if it has lost it's charge, the effect won't work. If these two items check out okay, you should have a qualified technician take a look at it.
Well, I just looked online, and I noticed the pedal calls for a reversed polarity power supply and it needs to be purchased separately, this leads me to think there could be a problem with the way you are connecting the battery. You probably need to double check that connection also. I hope this helps you.
Answer: Set both "Gain" and  "Level" to 12 o' clock and then engage the distortion. If you hear something when it's not engaged but nothing when it's engaged, it could mean any or a combination of the following...

Dead Battery - Replace battery
Battery to plug cable issue - try another cable
Pedal electronics issue - RMA

If you do hear something, Gain will control how distorted the output signal will be, Level will control how loud the output signal will be.

Guitar pedal blocks sound when I engage


Is it possible to find $x^2$ in terms of $a$ in $x^4 \cosh (\pi x)-\left(x^2-1\right)^4 \sinh (3 x+a)-x^2=0$?

Question: I have this equation:
$$x^4 \cosh (\pi  x)-\left(x^2-1\right)^4 \sinh (3 x+a)-x^2=0$$
where $0<a<\infty$ and $0<x<\infty$. Is it possible to apply some change of variable or something to find $x^2$ in terms of $a$?
Comment: Mathematica can't do it, so it almost certainly doesn't suffice to use even slightly obscure functions like [Lambert W](https://en.wikipedia.org/wiki/Lambert_W_function), and is likely to be highly difficult if a solution can be written down with named functions at all.
Answer: There is no possible closed form solution but we can do a few things
Consider the implicit equation$$x^4 \cosh (\pi  x)-\left(x^2-1\right)^4 \sinh (3 x+a)-x^2=0\tag 1$$
Fist, let $x^2=t$ to get
$$t^2 \cosh \left(\pi\sqrt{t}\right)-(t-1)^4 \sinh \left(3 \sqrt{t}+a\right)-t=0\tag 2$$
From $(2)$, we have
$$a=\sinh ^{-1}\left(\frac{t \left(t \cosh \left(\pi
   \sqrt{t}\right)-1\right)}{(t-1)^4}\right)-3 \sqrt{t}\tag 3$$ which gives the relation between $a$ and $x^2$.
The problem is that $a$ can be positive only if $0.440506 \leq t \leq 2.76039$ and, in this domain, $a$ varies between $0$ and $\infty$. Because of the vertical asymptote, for a given value of $a$, there are two solutions in $t$.
I give you below a table
$$\left(
\begin{array}{cc}
  t & a \\
 0.45 & 0.15708 \\
 0.50 & 0.94034 \\
 0.55 & 1.68159 \\
 0.60 & 2.41815 \\
 0.65 & 3.17995 \\
 0.70 & 3.99655 \\
 0.75 & 4.90465 \\
 0.80 & 5.95923 \\
 0.85 & 7.25830 \\
 0.90 & 9.01713 \\
 0.95 & 11.9171 \\
 1.00 & \infty \\
 1.05 & 12.1481 \\
 1.10 & 9.48116 \\
 1.15 & 7.95937 \\
 1.20 & 6.90374 \\
 1.25 & 6.10181 \\
 1.30 & 5.45912 \\
 1.35 & 4.92546 \\
 1.40 & 4.47092 \\
 1.45 & 4.07630 \\
 1.50 & 3.72855 \\
 1.55 & 3.41839 \\
 1.60 & 3.13899 \\
 1.65 & 2.88522 \\
 1.70 & 2.65309 \\
 1.75 & 2.43945 \\
 1.80 & 2.24179 \\
 1.85 & 2.05805 \\
 1.90 & 1.88655 \\
 1.95 & 1.72588 \\
 2.00 & 1.57485 \\
 2.05 & 1.43247 \\
 2.10 & 1.29786 \\
 2.15 & 1.17029 \\
 2.20 & 1.04911 \\
 2.25 & 0.93376 \\
 2.30 & 0.82375 \\
 2.35 & 0.71864 \\
 2.40 & 0.61805 \\
 2.45 & 0.52164 \\
 2.50 & 0.42909 \\
 2.55 & 0.34014 \\
 2.60 & 0.25453 \\
 2.65 & 0.17204 \\
 2.70 & 0.09247 \\
 2.75 & 0.01564
\end{array}
\right)$$ So, for a given value of $a$, you can pick an estimate of $t$ and safely use Newton method.
Let us try for $a=5$; the iterates will be
$$\left(
\begin{array}{cc}
 n & t_n \\
 0 & 0.75000000 \\
 1 & 0.75480447 \\
 2 & 0.75488029 \\
 3 & 0.75488031
\end{array}
\right)$$
$$\left(
\begin{array}{cc}
n & t_n \\
 0 & 1.35000000 \\
 1 & 1.34282664 \\
 2 & 1.34248914 \\
 3 & 1.34248842
\end{array}
\right)$$


Valor da div sendo enviada dinamicamente para página php

Question: Tenho um simples jogo que ao final gera uma pontuação.
A pontuação aparece desta forma:

0

Eu gostaria de no momento que essa div é chamada que essa pontuação fosse enviada também para a página processa.php, usando um form por exemplo.

Mais detalhes: o que eu preciso mesmo é salvar esse valor no banco de dados juntamente com o nome do usuário da página, pensei em enviar para uma página "processa.php" pq lá eu conseguiria desenvolver isso.
Answer: Você não precisa de um formulário para mandar este valor para o back-end, para isto você pode usar Ajax para conhecer sobre ele pode ver mais na documentação aqui.

1 - Se você já tem o valor que quer passar para o back-end, e este valor não está em um input, mas sim, em forma de texto, você pode pegar este valor através do método jQuery text(), saiba mais aqui.
2 - Aí é só montar o Ajax, enviando o valor através de uma requisição para uma url que receba e trate este valor.

$(function() {

  $('#envio').on('click', function() {
    let pts = $('#cScore').text();

    $.ajax({
      method: "POST",
      url: "processa.php",
      data: pts
    })
    .done(function(pts) {
      setTimeout(function(){
        alert( "Pontuação: " + pts );
      },2000);
    })
    .fail(function() {
      alert("Não foi enviado mas o valor é: " + pts);
    })
  });

})
#cScore {
  display: inline-block;
  background-color: #999;
  color: #FFF;
  padding: 10px;
}

  Valor total da pontuação:

100

<button id="envio">Enviar pontuação</button>

OBS: O meu exemplo vai retornar o FAIL, pelo motivo de que a url não foi encontrada.
Comment: Amigo, muito agradecido é exatamente o que eu precisava, fiz algumas simples adaptações para o meu código e já está funcionando. Grande abraço !
Comment: Ótimo cara, sucesso aí!
Comment: Se de alguma forma a resposta lhe ajudou a sanar suas dúvidas, considere aceitá-la como resposta clicando neste ícone ✔.
Answer: 0

var escore = $("#cScore").val();

aí so enviar esse "escore" para onde quiser
https://jsfiddle.net/lucasguarasp/4schxv9t/
Comment: `val()` é só para elementos de entrada e não para pegar textos. Pode saber mais aqui https://api.jquery.com/val/#val.


Kernel PCA (in R)

Question: I am attempting to use the kernel PCA features in kernlab but am having trouble understanding the output.  In particular, it's unclear what scale the results are in when I try to project the original data unto the resulting eigenvectors. Here is an example:
require(kernlab)
x = data.frame(a=1:10, b=10:1, c=sample(1:10,10), d=sample(1:10,10))
x = as.data.frame(lapply(x, scale, scale=F))
kpc = kpca(~., data=x, kernel="polydot", kpar=list(scale=1, offset=0, degree=2), features=1)

Printing x and the data from x projected unto the eigenvectors shows:
print(x)
      a    b    c    d
# 1  -4.5  4.5  1.5 -2.5
# 2  -3.5  3.5 -4.5 -3.5
# 3  -2.5  2.5 -1.5 -4.5
# 4  -1.5  1.5  0.5 -1.5
# 5  -0.5  0.5 -0.5 -0.5
# 6   0.5 -0.5 -2.5  4.5
# 7   1.5 -1.5  3.5  1.5
# 8   2.5 -2.5  2.5  3.5
# 9   3.5 -3.5  4.5  2.5
#10   4.5 -4.5 -3.5  0.5

print(rotated(kpc))
         [,1]
 #1    68.18682
 #2  -109.41619
 #3   -24.34769
 #4    30.26417
 #5    24.81883
 #6    41.32570
 #7   -20.17489
 #8   -37.57738
 #9   -93.93368
#10   120.85431

I'm having a tough time understanding the scale of this result.  Does rotated not scale the projection? In particular, the eigenvectors that PCA returns should be length 1. We don't know the eigenvectors in feature space, however, so well we can return is the projection of our data in that feature space using the kernel trick.  The results below don't seem to be on the correct scale, however.
Answer: What you get from rotated() is indeed a projection of the original data into 1 eigenvector, so a 10x1 vector.
Also rotate() does not rescale to 0-1. The scale depends solely on the kernel you pick.

Kernel PCA (in R)


How to debug page caching?

Question: I've got a page which returns X-Drupal-Dynamic-Cache: UNCACHEABLE, I've got a suspicion that this is related to a view that is embedded in the page. Though, this made me wonder; is there any way to see what invalidated actually the page cache?
Answer: The X-Drupal-Cache-Tags header should help with this.  Here's how to enable it from this doc:

You can debug cacheable responses (responses that implement this
  interface, which may be cached by Page Cache or Dynamic Page Cache) by
  setting the http.response.debug_cacheability_headers container
  parameter to true, in your services.yml. Followed by a container
  rebuild, which is necessary when changing a container parameter.
That will cause Drupal to send X-Drupal-Cache-Tags and
  X-Drupal-Cache-Contexts headers.
Comment: What the heck does "a container rebuild" mean?
Comment: A full cache clear of the Drupal site.
Comment: Thanks.  I'm completely baffled as to why they didn't use that extremely-well-understood terminology.  I don't think it's just me, either -- a web search for "container rebuild" turned up https://api.drupal.org/api/drupal/core!lib!Drupal!Core!DrupalKernel.php/class/DrupalKernel/ and a bunch of completely irrelevant stuff about docker.  AFAICS this terminology isn't being used anywhere outside of very niche discussions of the deep internals of Drupal, so I've no idea why they'd expect readers to know that.
Answer: As suggested in the answer from CG Monroe, enabling the header will show you what contexts you have, a user or session cache context can for example disable caching as well as a max-age 0.
Tracking down exactly where they are coming from can be tricky, I usually debug on the merge methods of the Cache class with a breakpoint set on having the problematic context/age. Certain filters/sorts or so (e.g. a random sort) can cause this, but so can certain block conditions (there is actually a known issue with that, see https://www.drupal.org/project/drupal/issues/2521956).
Comment: Thanks, I got to the point that I managed to find the `user` context that has been set. This makes the `DynamicPageCacheSubscriber->shouldCacheResponse()` say that this page is not cacheable. I'm still not sure where this context is being set. When I use `if(in_array("user", $a))` in the merge method of `Cache` I get tons of hits... Not sure why and how.
Comment: Yes, that is always a bit tricky. Usually it is the first hit, because then it often gets merged and merged again with other things many times. From that first call, check the parents and parent structures, which is only really doable with a real debugger and not just some inline debugging code. What we need is something that exposes cache tags and contexts on each render array element similar to twig debug. I think Wim once started with some ideas in https://www.drupal.org/project/renderviz. As you can see "More" unfortunatley never came, but maybe that there is already helpful?
Comment: Renderviz is definitely a useful tool! Thanks for that one.
Comment: I also found that placing a breakpoint in the `Cache::mergeContexts` method helps, but make sure that you first disable render caching in your local settings override file. Otherwise the real source of what added the context to begin with can be obscured.

How to debug page caching?


Jupyter Notebook not including THREE.js

Question: I have the following jupyter notebook cell, with fourd.js and r89dev.three.min.js in a js folder in the same directory as the notebook:
%%html
<!doctype html>

        <title>FourD.js Testbed</title>

It worked the first time I tried it, but now I get an error that THREE is not defined. That means it's loading the fourd.js library, just not the three.js library. What could I be missing?
The error I get directly in the notebook is the following:
Javascript error adding output!
ReferenceError: THREE is not defined
See your browser Javascript console for more details.

but I can't find a corresponding error message about three js not loading in the javascript console.
Answer: TL;DR: remove the // three.js - http://github.com/mrdoob/three.js comment from the beginning of xxx.three.min.js
I can not tell where it goes wrong, but you are seeing an interference between JavaScript strict mode prologue and comments.
If you try the following cell:
%%html

, it produces the following output (tested with Chrome, Firefox and IE):

a is set to a
b is set to b
ReferenceError: bsdfg is not defined
c is set to c
ReferenceError: csdfg is not defined
Checking things:
a is a
b is b
c is nope: ReferenceError: c is not defined

Where the "x set to x" messages show that all a-b-c blocks run fine, the two ReferenceErrors in the middle show that both b and c are running in strict mode, which is also expected.
The unexpected thing is that c is not set at the end, producing the third ReferenceError.
I can not explain how the comments matter for Jupyter, but they do. three.min.js starts with a comment line, and then it behaves like c, remaining undefined. fourd.js starts with "use strict";, and the starting comment comes only after that, and it works.
It seems to be a Jupyter-only thing, as the following snippet works fine even when embedded here:

(The two expected ReferenceError-s show up as empty {}-s, but they are there, and all a-b-c are set properly at the end)
Comment: BTW, if someone without a Jupyter installation wants to try, https://jupyter.org/try is a place for that. Start the Python one, press the ```[+]``` button to add a cell, paste the content, and use Ctrl+Enter to evaluate it.

Jupyter Notebook not including THREE.js


Chaos Theory Question

Question: I'm wondering if there is a general formula or approach for chaos theory? Or, if not, are there any books of papers that I can reference for learning about Chaos Theory?
Answer: If I recall correctly, then the first paper that introduced the word "chaos" was here: http://faculty.washington.edu/joelzy/LiYorke_period3.pdf, entitled "Period Three Implies Chaos."
However, the general notion went back a bit earlier, I believe with regard to weather and natural phenomena. Regardless, the paper linked above might be a nice starting point.
Comment: Thank you very much for your input. I've been reading a book on the history of math, and a part about Henri Poincare came along, with his analysis of three body movement, and after a while this study was stated as wrong to Henri. But it actually showed how incomprehensible movement becomes based on initial points and further motion. Just seemed crazy to me, so I would like to look into what is referred to as Chaos Theory that Henri Poincare helped develop. Cheers for sharing though!
Answer: You may enjoy these books:

Celestial Encounters:The Origins of Chaos and Stability by Diacu and Holmes
Does God Play Dice? The New Mathematics of Chaos by Ian Stewart

Chaos Theory Question


Washboard as Instrument

Question: I know that some washboards are fabricated from the outset to be musical instruments.
Are they significantly better than using just any old antique washboard I might happen to find around?
I'm asking as a complete amateur who's just looking to screw around with a garage band full of other complete amateurs.
Answer: They only exist because it's harder to find 'any old antique washboard' anywhere. If you can find a real washboard, you get bonus points for authenticity.

Washboard as Instrument


google-api-client-java eclipse build path and google app engine

Question: I am trying to follow the instructions here:
http://android-developers.blogspot.ca/2013/01/verifying-back-end-calls-from-android.html
I have decided to download the google-api-java-client library and see if I can instantiate the code on the bottom half of the page referenced above. I have imported libraries in eclipse in my app engine project so that eclipse doesn't complain about anything BUT when I try this:
<code>    GoogleIdToken token = GoogleIdToken.parse(mJFactory, tokenString);
</code>
eclipse complains with red underlining on 'GoogleIdToken.parse()' and this text

The project was not built since its build path is incomplete. Cannot find the class file for com.google.api.client.auth.jsontoken.JsonWebSignature. Fix the build path then try building this project

and

The type com.google.api.client.auth.jsontoken.JsonWebSignature cannot be resolved. It is indirectly referenced from required .class files

I have gone to this site and have followed the instructions as closely as I can, but the error remains.
http://code.google.com/p/google-api-java-client/wiki/Setup#Download_Library_with_Dependencies
can anyone tell me how to get rid of this error?
Answer: see this link:
http://code.google.com/p/google-api-java-client/
The jars with version 1.12.0-beta were not working for me, (as described above) but 1.13.2-beta was released and seems to work fine.
BTW, I was willing to try anything, including different versions of eclipse and wiping my eclipse workspace metadata. I even tried older versions of the google api library, which actually worked. I was going to go with 1.9, but I found out the last one (1.13) had some useful options that I wanted to take advantage of. 1.13.2-beta got rid of the eclipse errors for me.


Can't bind data to src attribute of img tag in a jhipster - angular 2 project

Question: I've changed from raw-loader to html-loader as the issue: https://github.com/jhipster/generator-jhipster/issues/5333
then it works if I code as below:

{{imgSrc}} here

When I bind data to src as below, it doesn't work.
this.imgSrc = "../../content/images/lotto-euro1.png";

{{imgSrc}} here

or

{{imgSrc}} here

Many thanks for any help.
Comment: `[src]="imgSrc"` should work.. any error in console.?
Comment: inspect as below:  but the image can't display. I think this is issue in config webpack, but I don't know how to fix
Answer: Try to change src={{imgSrc}} to src="{{imgSrc}}" in the first case or [src] to [attr.src] in the second case. If it doesn't work, give us an html code of the img.
Comment: @CongThanh did you find a solution?


partial() substituting functions in python

Question: I have the code below, which works for me. My question is generally speaking why does it work? How does the partial() function know that the f in difference_quotient() is a function. In partial() it gets substituted for x*x which would mean return(x*x(x+h)-x*x(x))/h. But this would change the output beeing wrong.
from functools import partial
def difference_quotient(f, x, h):
    return(f(x+h)-f(x))/h
def square(x):
    return x*x

derivative_estimate1 = partial(difference_quotient, square, h=0.00001)

print(derivative_estimate1(5))

Answer: So partial is a class which generates a new function with some arguments pre-filled out (in other words, you don't need to provide them).  The first argument you pass topartial is the function you will be running, namely difference_quotient in your case.  Then, the square function is passed in as the actual "first" argument to difference_quotient and h is specified via a keyword.  When you then run derivative_estimate1, it runs difference_quotient(square, 5, h=0.00001) where the 5 is passed in from your new call.
For positional arguments, it will fill in from left-to-right, but since you specified h=0.00001, it filled h instead of x, meaning when you call the function again, the only argument you can provide is x.
If you try only passing in difference_quotient to partial like so:
derivative_estimate1 = partial(difference_quotient)
and then run it like this:
print(derivative_estimate1(5))
It will complain because you didn't pass enough arguments.
Edit:
To better directly answer your question about Python knowing it's a function:
Python doesn't know anything, inherently, about it's variables.  It only knows that you intend to use whatever f is as a function.
If I made the call like this:
derivative_estimate1 = partial(difference_quotient, 5, h=0.00001)
print(derivative_estimate1(5))
I get an error where Python says it tried to call a function on a number.
TypeError: 'int' object is not callable
There's no "magic" Python does to "know" its a function.  It just says "Hey, you are trying to call this argument you passed in, so it must be a function."

In partial() it gets substituted for x*x

This is not really correct.  square is passed in as a function, and then you just call that function in your code.
I hope that clears things up for you.
Comment: I see, that is what I was thinking! thank you for clarifying! The question I still have is how does `f`get replaced as it's is replaced by the function `x*x` but `difference_quotient(f, x, h)` itself has an `x`. Is it just how python works, it recognizes the `f`with the open parantheses as a function?

I hope I made my question more clear :s
Comment: Well, that's sort of what I was trying to get at.  It doesn't actually know at all.  If you passed your arguments in a different order it wouldn't work.  Python doesn't actually know at all, it's just the fact that you are trying to call it that it works.

If you did `derivative_estimate1 = partial(difference_quotient, 2, 3)` it would fail once you called it because Python has no idea the types of any variables until you try using them.  So unless you did a type check, you could easily pass an integer for `f`.  I'll ammend my answer.
Comment: @SebastianOrtmann If my answer helped you, would you accept it as the answer?

Happy to know you got it figured it out though :)


Chords construction and formula

Question: im very much new, i've been reading some music theory books for general and specific to guitars.
Now what i do not understand is the following

how a Chord is constructed?
how does a formula became to be in constructing a chord? like, in triads, why i do i use specifically 1-3-5 notes in a major scale? in 7th, why do i only use 4 notes (1-3-5-7). Yes, there are variants in using 1-3-5 and 1-3-5-7, each with its own sharps and flats. However, what i do not understand is why do i need to only use specifically those notes (1-3-5 | 1-3-5-7) in a scale? why not use all 7 or why do i not use 1-2-5?

Thanks for any inputs. again im  still a newbie
Answer: One of the fundamental ways of thinking about chords involves "stacking thirds". From a scale perspective this means taking every other note in the scale. To build a CMaj7 chord, start with a C Major scale, or more specifically, start with the C Ionian mode, and take every other note: C-E-G-B. You can continue into the next octave to get the chord extensions (9th, 11th, and 13th): C-E-G-B-D-F-A. That chord is a CMaj13.
You can build a G7 chord in the same way, but starting from the 5th degree of the C Major scale, i.e. the G Mixolydian mode. G-B-D-F. To get the chord extensions, continue into the next octave: G-B-D-F-A-C-E. That is a G13, and contains the 9th, 11th, and 13th. Note that a chord symbol with a 9, 11, or 13 implicitly contains the lower extensions.
Yet, those implicit extensions may be left out in practice. For example, it is especially common on guitar to see 13th chords spelled with only the root, 3rd, 7th, and 13th. A G13 spelled this way is G-B-F-E, and a common shape for this is:
 %3/1.X/X.3/2.4/3.5/4.X/X[G13]

In jazz we often play chord fragments instead of full chords. This has a lot of implications; it allows more space for soloists when you are comping, it allows more freedom when you are playing solo and chord melody pieces, it can provide nice ambiguities when multiple chords may be implied, and sometimes it can provide a nice texture. To do this, it is often best to think of chords as the notes that you want to include rather than a big collection of notes from a scale. You might need a C9 chord; you could play C-E-Bb-D-G:
 %X/X.3/2.2/1.3/3.3/3.3/3[C9]

This is a common shape for C9 that includes all of the notes, but the 5th is not too important to the sound of the chord. The 3rd establishes whether the chord is major or minor, the 7th establishes whether the chord is a major or dominant 7th chord, and the 9th is an extension. In some ways the 9th is the most important note in a 9th chord, so in some cases you might just play the root and the 9th, or add the 7th if you want, or the 3rd and the 7th. If you want a more open sound on a C9 you could try:
 %X/X.3/2.X/X.3/3.3/4.X/X

This chord contains only the root, 7th, and 9th of a C9. With no 3rd, it is ambiguous: it could be a C9, or it could be a Cm9. Here is a very ambiguous chord that I sometimes use in place of a C7(b9):
 %X/X.3/2.X/X.5/4.2/1.X/X

This isn't even really a chord by itself, containing only the root (doubled) and the b9. But it is an effective sound to use at times.
Summing up, learn the basics of how chords are constructed, i.e. by stacking 3rds (know that you can also stack 4ths or 5ths for other chord types). Learn which notes are important in chords, and build the chords that you need. There is a correct way to spell a C7(b9) chord in theory (C-E-G-Bb-Db), and while there are incorrect ways, there is no one correct way to spell C7(b9) in practice.
Comment: What are those chord descriptions? I've never seen them before.
Comment: Nevermind, they just came out different on my phone
Answer: In tonal music (major/minor key music) the chords are called tertian meaning built of thirds.
As you already know the triad is two thirds, the seventh chord is 3 thirds.

...why not use all 7?

You can. 1 3 5 7 9 11 13 that would be a thirteenth chord. How common thirteenth chord are will depend on style. Not common for something like Haydn versus more common in modern jazz.

...why do i not use 1-2-5?

You could have such a combination of notes, like C D G. But, as the chord system is tertian - again, meaning based on thirds - we would give special consideration to that group of tones. It doesn't match a group of notes by thirds and typically it may be labelled a suspension where the C is 'suspended' until it moves down to B thus creating the group B D G which is tertian chord. So the suspension is not regarded as the proper chord. The group of tones the suspension resolves into is considered the proper chord.
The is a such thing as quartal harmony where chords are built of fourths. In that system 1-2-5 is a proper chord. Actual quartal harmony is found in modern composition styles and in some jazz.
When identifying chords you do need to know whether the harmonic style is tertian or quartal.
Answer: I think you can find details "how a Chord is constructed" in other questions in this website, but it seems like you already know the basics. So your main question seems to be "why are chords constructed the way they are".
This is a fair and maybe profound question. I can't give you a lot of details, but the reason is merely historical. Western harmony is based on thirds. So you stack some thirds and then you have chords! Of course there are also physical reasons why these notes sound nice together, but you don't see 7th chords in traditional arabian or japanese music, do you? Their music evolved in a different way.
Of course you can use 1-2-5, or all seven notes, or whatever you want! Feel free to construct chords without being stuck to formulas. Chances are, you will find that the chords that sound "right" and more familiar are third based chords, because that's what we've been used to hear all our lives, that's how western music has evolved over time.
To open your mind a little bit, you can take a look for example at Set Theory. I have already composed something based on set theory, and you can't even imagine the cool stuff that can come up when you are not stuck to traditional functional harmony!
So, if you are looking for details on chord construction, take a look at the other answers. If you are looking for the reasons why chords are stacks of thirds, look into western music history. If you are looking for alternative ways to construct chords, set theory may be a starting point, but there is a lot more stuff out there!
Answer: Well the simplest answer is you're not forced to build chords by stacking thirds. You are free to do anything. Music theory is only a description of existing (western in this case) practice of music making. And you basically study that practice following recipes like: build chords by stacking thirds.
That being said, chords built this way make the most of existing western music from classical to pop to jazz. And even if we play 1-2-7 we might 'hear' it as reduced form of dominant chord as we tend to aurally refer to established forms, harmonies etc.
So it's a bit like - you take first karate lessons and ask: why do I need to kick this way and not another? The old and wise karate master will probably respond: well you can do it your way, but it will work much better if you spend next 10 years figuring out why we all kick this way and why it works.
Answer: When constructing a chord, you want the notes to sound nice along with one another. Mathematically, if you look at those notes, 1-3-5, they fit along what's called an overtone series. Take an A chord for example. Your base note, A, had a pitch of around 440 Hz (depending on your preference). The notes C# and E are produced as overtones. If you want, you can read more up on that, but it gets very complicated very fast.
There are 4 types of triads, and 4 types of 7th chords. For triads, you have Major, Minor, Diminished, and augmented. Naturally, the overtones play along the major scale, so when you make the 3rd minor (in a minor chord), it doesn't sound pretty, at first. Because they play along another overtone series, much much more desecrate than the base Major chord, the resulting notes can be interpreted as an alternate "feeling" such as sad. The same goes for diminished and augmented chords.
Basically, you are playing notes that work well with others, in an order that they will sound well. For example, if you play a 7th chord such as Cmaj7, the notes you would play are C,E,G, and B. If you play B and C right next to each other, it sounds terrible. That is because the frequencies are so close to one another, they just don't work well. But when you put space in between them, they work with the overtones, and that beautiful sound of a Major 7th chord is created.
This might have been the most confusing thing you have ever read because I don't think I explained it correctly, so if you have any questions don't hesitate to ask!

Chords construction and formula


Question about how to read the notation in this song (Spinning song)

Question: What does the two ties mean in this context?

At the first tie am I supposed to hold down the C while playing the part marked with red and first let go of the C when I reach where the blue circle is?

Then there's this part i don't get at all. Wouldn't it sound completely the same without the tie?

Any help would be greatly appreciated. Thanks in advance!
Answer: Those aren't ties.  They're phrasing marks.  In the first case, it IS kind of confusing, since the arc goes to the same note.
Anyway, don't worry about it too much.  The rests pretty much force you to group the notes properly.
Answer: Tie and phrase marks look remarkably similar. The difference is usually that tie marks tie together notes of the same pitch, often across barlines,(as it may seem here), while phrase marks will inevitably have a number of notes under them, with the start and finish notes being different.
Here, in the eight bars shown, the 3rd/4th and 7th/8th are definitely slurs, or phrase marks. However, I can see your dilemma in bars 1/2 and 5/6.Could be either. However, notes tied across a barline must be consecutive, with no other notes in between, and the 1st C is separated from the 2nd (bar 2) by two semiquavers, so it could only last a beat and a half, before the semis are played, thus making the next C a separately sounded note. But since the same timing and shape of all four are so similar, it seems more probable that bars 1/2 and 5/6 are also phrase marks. So, I'd be playing the Cs in 2 and 6 again, rather than holding them across the barlines.
So, in conclusion, there is not a single tie in the excerpt, only slur marks or phrase marks.
Be interesting to dig out any other publications of this music, to see what other engravers have done.
Comment: @Tim - I thought the first one's first C not being a half note (i.e. doesn't take up the full measure) is enough reason that the first one cannot be a tie.
Comment: @Tim  Your edit has made things worse.  The fact that the 'tie' is across a barline is irrelevant.  And 'consecutive' doesn't mean what you seem to think it does!
Comment: Ties can exist anywhere.  I disagree that "usually across bar lines" is valid.  A tie indicates (on any instrument, not just piano) that you do not re-attack the note; further one expects a slurred passage to have an additional curve indicating a tie within the passage.
Comment: There's no way the first one could realistically be a tie.
Comment: @LaurencePayne - If you wrote your reasons why, it could be an answer.
Comment: @Dekkadeci - true - the fact that the two Cs have something in between means they cannot be tied. Reflected in the edit. Thanks.
Comment: @LaurencePayne - 'following one another without interruption'. I thought tied notes had to do that. I save up some of my bad days, but this is one that got away!


Drupal Coding - Menus - hook_menu is not generating menus

Question: While working on the layout of a new custom menu, I discovered that the hook_menu process is not working on my D7.12 local site.  As a test I enabled the Menu_example module and found that it will not generate menu items in the navigation menu, although it did a week or two ago.  So far I have reinstalled all Drupal 7.12 files and confirmed that the module file hook_menus are being read (using dsm).  I am at a loss as to what else can be preventing the menu links from being installed.
Does anyone have any similar experiences or suggestions on how to track this problem down to its source?
EDIT:
This code does not add a menu item in an empty menu called "Stuff":
function material_menu_menu (){
  $items['stuff/existing'] = array(
    'title' => '020000 Existing',
    'page callback' => 'material_view' ,
    'page arguments' => array ('sum' , '020000 '),
    'type' => MENU_NORMAL_ITEM,
    'menu_name' => 'Stuff',
    'access callback' => TRUE,
    'weight' => '2 ');
  return $items;
}

Comment: I did have return $items but forgot to add it in this text.  I'll check on case sensitivity, but that does not explain why the menu_example module is not working now.  I had it enabled in the navigation menu when I was preparing to work on this menu, but when I re-enabled it, it no longer shows up.
Comment: Yeah I didn't think that'd fix it but it was worth a shot :) The place to start debugging is in [`_menu_navigation_links_rebuild()`](http://api.drupal.org/api/drupal/includes%21menu.inc/function/_menu_navigation_links_rebuild/7) which builds up the menu links...it gets passed the menu router items built up from [`menu_router_build()`](http://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_router_build/7) (which is where `hook_menu()` is called from). A bit of temporary debug code in that first function would be the best way to go I think
Comment: I think the `menu_name` would normally be case sensitive so it should be `'stuff'` rather than `'Stuff'` to match up with the menu's machine name. Also your code above doesn't `return $items;`...could either of these be the problem?
Comment: I changed the case without a change in the problem.  I have also flushed caches.  I sure do love these Drupal engimas!!!  :)
Comment: OK, some progress!  I added dsm's to both drupal functions and found that the menu item was being included.  Curiously, the menu_example menu finally showed up in the navigation menu.  I have no Idea why it took so many iterations of toggling the module on and off to finally get it to appear (at least 5 cycles).  I parts of drupal code cached so that whatever may have been causing the omission of the menu was not readdressed until I altered the code in the core module?
Comment: The 'stuff' menu item is also working, although I had also added some content in the page callback which had been empty before, so that may have changed things. However, while the menu item responds to its path in the URL (stuff/existing), it does not appear in the list of links for the menu in the admin/structure/menus/stuff page.  I was under the impression that that is where MENU_NORMAL_ITEMs were supposed to appear.  Can you confirm that?
Comment: @Clive  Please plug in an answer so I can give you credit.
Answer: The place to start debugging is in _menu_navigation_links_rebuild() which builds up the menu links...it gets passed the menu router items built up from menu_router_build() (which is where hook_menu() is called from). A bit of temporary debug code in that first function would be the best way to go I think.
To address your other question, I've just added a menu item to a module in exactly the way you've done and it's come up in the UI as expected. It sounds like you have something pretty unusual happening with your menus!


How to expand $\sqrt{x^6+1}$ using Maclaurin's series

Question: The expansion would be
$\sum_{n=0}^\infty$$\frac{1}{2}\choose n $$x^{6n}$
How to evaluate binomial coefficient with rational numbers?
If $\frac{1}{2}\choose n $=$2n\choose n $$\times \frac{(-1)^{n+1}}{2^{2n}(2n-1)}$ what would be the expression for binomial coefficient if rational number is $\frac{3}{2}$ instead of $\frac{1}{2}$?
This is one example of Macclaurin expansion for the above expression:
$$1+\frac{1}{2x^6}+r(\frac{1}{x^{11}})$$
Can someone show the steps for expanding the expression, and how to generate remain?
Comment: @Walter That should be the formula, and it is defined.
Comment: I'm not sure that $\frac{1}{2}\choose n $ is even defined? Why don't you use the formula for a [Maclaurin series](http://mathworld.wolfram.com/MaclaurinSeries.html)?
Comment: You're right, I didn't know this: http://math.stackexchange.com/a/340141/241637
Comment: You can also use the Hypergeometric function representation $(1-z)^{-a}={}_2F_1(a;1;1;z)$
Answer: The generalised binomial coefficient $\,\dbinom{\tfrac12}n$ is simply:
$$\frac{\cfrac12\Bigl(\cfrac12-1\Bigr)\Bigl(\cfrac12-2\Bigr)\dots\Bigl(\cfrac12-n+1\Bigr)}{n\,!}.$$
Answer: If you want an alternative representation, one can simply recall that
$$\frac{d^n(1+x)^{1/2}}{dx^n}=\frac{(-1)^{n+1}(2n-3)!!}{2^n}(1+x)^{-(2n-1)/2}$$
for $n\ge 2$, where $(2n-3)!!=1\cdot3\cdot5\cdots (2n-3)$ is the double factorical.  Then, we have
$$(1+x^6)^{1/2}=1+\frac{x^6}{2}+\sum_{n=2}^{\infty}\frac{(-1)^{n+1}(2n-3)!!}{2^nn!}x^{6n}\tag 1$$
Note that we can write the double factorial in terms of single factorials as
$$\begin{align}
(2n-3)!!&=\frac{(2n)!}{(2n)(2n-1)(2n-2)(2n-4)\cdots 2}\\\\
&=\frac{(2n)!}{(2n-1)2^nn!} \tag 2
\end{align}$$
Substituting $(2)$ into $(1)$ gives the expansion
$$\begin{align}
(1+x^6)^{1/2}&=1+\frac{x^6}{2}+\sum_{n=2}^{\infty}\frac{(-1)^{n+1}(2n)!}{4^n(2n-1)(n!)^2}x^{6n}\\\\
&=\sum_{n=0}^{\infty}\frac{(-1)^{n+1}(2n)!}{4^n(2n-1)(n!)^2}x^{6n}
\end{align}$$

NOTE:
Another way of writing the generalized binomial coefficient for $\binom{1/2}{n}$ is thus
$$\binom{1/2}{n}=\frac{(-1)^{n+1}(2n)!}{4^n(2n-1)(n!)^2}$$
Answer: When $n$ and $m$ are positive integers, the binomial coefficient $\binom{n}{m}$ is defined as:
$$ \binom{n}{m}=\frac{n!}{m!(n-m)!}\tag{1}$$
hence by replacing $a!$ with $\Gamma(a+1)$ it is natural to consider the extended definition:
$$\binom{n}{m}=\frac{\Gamma(n+1)}{\Gamma(m+1)\,\Gamma(n-m+1)}\tag{2}$$
from which it follows that:
$$\binom{\frac{1}{2}}{n}=\frac{\Gamma(3/2)}{n!\Gamma(3/2-n)}=\frac{\frac{1}{2}\cdot\left(-\frac{1}{2}\right)\cdot\ldots\cdot\left(\frac{3}{2}-n\right)}{n!}=\frac{1}{4^n}\binom{2n}{n}\frac{(-1)^{n+1}}{2n-1}\tag{3}$$
as you stated. Since:
$$ \frac{\binom{n+1}{m}}{\binom{n}{m}}=\frac{n+1}{n+1-m}\tag{4}$$
it follows that:
$$ \binom{\frac{3}{2}}{n}=\frac{\frac{3}{2}}{\frac{3}{2}-n}\binom{\frac{1}{2}}{n}=\frac{3}{4^n}\binom{2n}{n}\frac{(-1)^n}{(2n-1)(2n-3)}.\tag{5}$$


I can not cd "LaunchAgents" on macbook

Question: After installing mongdb on my macbook-pro, it tells me:

If this is your first install,
  automatically load on login with:
cp /usr/local/Cellar/mongodb/1.6.3-x86_64/org.mongodb.mongod.plist ~/Library/LaunchAgents
launchctl load -w ~/Library/LaunchAgents/org.mongodb.mongod.plist

If this is an upgrade and you already
  have the org.mongodb.mongod.plist
  loaded:
launchctl unload -w ~/Library/LaunchAgents/org.mongodb.mongod.plist
cp /usr/local/Cellar/mongodb/1.6.3-x86_64/org.mongodb.mongod.plist ~/Library/LaunchAgents
launchctl load -w ~/Library/LaunchAgents/org.mongodb.mongod.plist

Or start it manually:
mongod run --config /usr/local/Cellar/mongodb/1.6.3-x86_64/mongod.conf

But after I copy org.mongodb.mongod.plist to ~/Library/LaunchAgents, it tells me:
launchctl load -w ~/Library/LaunchAgents/org.mongodb.mongod.plist
launchctl: Couldn't stat("/Users/why/Library/LaunchAgents/org.mongodb.mongod.plist"):
Not a directory

And also I can not cd "~/Library/LaunchAgents", but I can ls the directory!
~/Library/LaunchAgents is a strange directory on mac.
Answer: Did you make sure that you created the ~/Library/LaunchAgents directory first? You may have just ended up copying /usr/local/Cellar/mongodb/1.6.3-x86_64/org.mongodb.mongod.plist to a file called ~/Library/LaunchAgents
Try ls -la ~/Library/LaunchAgents and see what the output is. It should look like:
[why@why ~]$ ls -la ~/Library/LaunchAgents
total 40
drwxr-xr-x   7 why  why   238 Jan 11 09:47 .
drwx------+ 68 why  why  2312 Sep 28 19:39 ..
-rw-r--r--   1 why  why   543 Jan 11 09:47 org.mongodb.mongod.plist

If instead you see:
[why@why ~]$ ls -la ~/Library/LaunchAgents
-rw-r--r--  1 why  why  543 Jan 11 09:47 /Users/why/Library/LaunchAgents

Then you copied the MongoDB plist to a file called LaunchAgents. Here's how to remedy that:
rm ~/Library/LaunchAgents
mkdir -p ~/Library/LaunchAgents
cp /usr/local/Cellar/mongodb/1.6.3-x86_64/org.mongodb.mongod.plist ~/Library/LaunchAgents
launchctl load -w ~/Library/LaunchAgents/org.mongodb.mongod.plist

Comment: Good idea.  I usually append a / if I want to be sure of copying to a directory - i.e. `copy file dir/` then if `dir` doesn't exist, it wont copy `file` to a file called called `dir`

I can not cd "LaunchAgents" on macbook


Test if a variable is a list or tuple

Question: In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection)
Is isinstance() as evil as suggested here? http://www.canonical.org/~kragen/isinstance/
Update: the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / data-structure of lists of lists of lists of strings etc. which I'm exploring with a recursive algorithm and I need to know when I've hit the "leaf" nodes.
Comment: Broadly dismissing type-checking as evil is a bit facile. It's part of the language. If it is so evil, someone should write a PEP to remove it.
Comment: The "XXX is evil" is badly-conceived, misleading shorthand for "the way you're asking to do XXX suggests you don't understand when it should actually be used, and you almost certainly want something else".  That's most likely the case here.
Comment: So you're saying that some type checking is needed, but despite that, it's useless, worthless and a bad idea.  Sorry, that just doesn't make sense.
Comment: @Adam Crossland: "It's part of the language." Just like division by zero.  It's avoidable.  In this case, without additional information, it's probably completely needless.  Most type checking in Python is needless.  Since not *all* is needless, some type checking needs to be present.  But that doesn't mean it's helpful, valuable, or even a good idea.
Comment: I didn't broadly dismiss it as evil. I wrote a short essay about when it's evil and when it's justifiable. That essay may be many things — right, wrong, clear, vague, enjoyable, boring — but one thing it is not is a broad dismissal of the technique.
Comment: Please do note that since PEP 3119 isinstance has become more correct. Thanks to the Abstract Base Classes isinstance is now the most correct way to decide fail-fast whether a class will support things like general collection protocols!
Comment: Also, oftentimes it is better to have fail-fast for things such as deferred method calls; it becomes very hard to debug why a deferred method call fails later on. In python 3 there is no "callable(x)"; the correct way to check if a given object is callable without calling it is to do isinstance(obj, collections.abc.Callable)
Comment: What do you want to have as your behavior if you get some other kind of iterable collection (like a set or a string, for instance)?
Comment: As I have explained in one of the answer's comment, sometimes it is necessary to know for sure some container is ordered, and this may only be possible by type checking (or may be in some cases, `getattr(obj, '__getitem__')`, but this is ugly). When the ordering of the elements in a container object does matter, an algorithm that does not check for this could potentially generate different results on different runs! I don't believe type-checking to be evil, because it could be essential.
Answer: if type(x) is list:
    print 'a list'
elif type(x) is tuple:
    print 'a tuple'
else:
    print 'neither a tuple or a list'

Comment: `type(x) in [list,tuple]` is shorter.
Comment: In Python 2.7.5: `type([]) is list` returns `True`
Comment: Does not seem to work :  type([]) ==> list;   type([]) is list ===> False
Comment: if x and type(x) is list: to avoid the [] mismatch
Answer: Go ahead and use isinstance if you need it.  It is somewhat evil, as it excludes custom sequences, iterators, and other things that you might actually need.  However, sometimes you need to behave differently if someone, for instance, passes a string.  My preference there would be to explicitly check for str or unicode like so:
import types
isinstance(var, types.StringTypes)

N.B. Don't mistake types.StringType for types.StringTypes.  The latter incorporates str and unicode objects.
The types module is considered by many to be obsolete in favor of just checking directly against the object's type, so if you'd rather not use the above, you can alternatively check explicitly against str and unicode, like this:
isinstance(var, (str, unicode)):

Edit:
Better still is:
isinstance(var, basestring)

End edit
After either of these, you can fall back to behaving as if you're getting a normal sequence, letting non-sequences raise appropriate exceptions.
See the thing that's "evil" about type checking is not that you might want to behave differently for a certain type of object, it's that you artificially restrict your function from doing the right thing with unexpected object types that would otherwise do the right thing.  If you have a final fallback that is not type-checked, you remove this restriction.  It should be noted that too much type checking is a code smell that indicates that you might want to do some refactoring, but that doesn't necessarily mean you should avoid it from the getgo.
Comment: The types module is a bit of a historical artifact. As mentioned on http://docs.python.org/dev/library/types.html#module-types if you really must check for the `str` type you should just use that directly, instead of using `types.StringType` which is just an alias for it.

But I do not think this answer answers the question as asked, because that was about "a collection". Unless you're using a python new enough to have the `abc` module that's not something you can use `isinstance` to check for, and even then I would recommend avoiding the check if at all possible.
Comment: `assert isinstance(u'abc', str) == False`.  I agree that it is better to check against the type directly, rather than using the `types` module, but `types.StringTypes` does something that `str` doesn't: it returns True for `str` and `unicode` objects.  I'll edit my response to offer a double check as an alternative.
Comment: I realize I didn't answer the question of checking for collections directly, but the actual question asked was "Is `isinstance` evil?"  And I gave a counter example which (1) is a non-evil use of `isinstance`, because having a fallback means it doesn't break ducktyping, and (2) is a good solution for a very common motivation people have for wanting to check if something is a `list` or `tuple` (i.e. to disambiguate them from strings).
Comment: I agree, with the caveat that often it's useful for custom types to behave like strings, too. But Python's OO only goes so far...
Comment: Does `class Foo(str): pass` do what you want?
Comment: Alas, this does not work on python 3.2, as types module does not contain StringType or StringTypes at all.
Comment: @AnttiHaapala That's why I offer the other version, which in python 3 would translate to `isinstance(foo, (str, bytes))`.
Comment: Anyway, your suggestion is good. However I detest that when I am creating methods that need to accept single objects or composite collections and act as if the former were a collection of 1, always having to check separately if my "collection" happens to be a str, unicode or bytes. Not a nice feature from python - "string as a immutable collection of characters" is just not so useful as BDFL might have imagined in the first place ;)
Answer: There's nothing wrong with using isinstance as long as it's not redundant. If a variable should only be a list/tuple then document the interface and just use it as such. Otherwise a check is perfectly reasonable:
if isinstance(a, collections.abc.Iterable):
    # use as a container
else:
    # not a container!

This type of check does have some good use-cases, such as with the standard string startswith / endswith methods (although to be accurate these are implemented in C in CPython using an explicit check to see if it's a tuple - there's more than one way to solve this problem, as mentioned in the article you link to).
An explicit check is often better than trying to use the object as a container and handling the exception - that can cause all sorts of problems with code being run partially or unnecessarily.
Comment: This is a nice way to check if a variable is iterable.  However, it probably won't work for the purposes of this question.  Be advised that a string is iterable too and would probably create a false positive.
Comment: Looks like for 2.x, it was available under [`collections.Iterable`](https://docs.python.org/2.7/library/collections.html#collections.Iterable), but it's been moved to the abstract base class (abc), so now it's called [`collections.abc.Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable)
Comment: A `set` object is also an iterable, which means that while you can surely pop elements from it, but it does not guarantee a certain order, which is a very dangerous thing for certain algorithms. In the cases when ordering of the elements does matter, an algorithm using this snippet could potentially generate different results on different runs!
Answer: Document the argument as needing to be a sequence, and use it as a sequence. Don't check the type.
Answer: On Python 2.8 type(list) is list returns false
I would suggest comparing the type in this horrible way:
if type(a) == type([]) :
  print "variable a is a list"

(well at least on my system, using anaconda on Mac OS X Yosemite)
Comment: Did you mean Python 2.7.8?  https://www.python.org/dev/peps/pep-0404/#official-pronouncement
Comment: `type(list) is list` returns `False` because `type(list)` is `type`, not `list`.  `type(list()) is list` or with any other *instance* of a list will return `True`.
Comment: Does type(a) is list also evaluates to false ?
Comment: Hello, I'm curious: Why do you consider your example "horrible"?
Answer: I recommend the only pythonic way:
if isinstance(x, (list, tuple))): pass

Comment: 13 years after the original question was published, this answer is the most straightforward way to accomplish this in Python3.
Comment: This alternative works with a `tuple` of types, not with a `list` of them.
Comment: Works also for `dict`. This should be the accepted answer
Answer: >>> l = []
>>> l.__class__.__name__ in ('list', 'tuple')
True

Answer: How about: hasattr(a, "__iter__") ?
It tells if the object returned can be iterated over as a generator.  By default, tuples and lists can, but not the string types.
Comment: Also results True for strings (at least on Python 3).
Comment: This is wrong answer. Since type 'str' has the method '__iter__' also. @SzieberthAdam was right. The type 'set' also is iterable, but is not orderable.
Comment: If you continue, any custom type may have `__iter__` for some reason...
Comment: Also dicts have ``__iter__``.
Answer: Python uses "Duck typing", i.e. if a variable kwaks like a duck, it must be a duck. In your case, you probably want it to be iterable, or you want to access the item at a certain index. You should just do this: i.e. use the object in for var: or var[idx] inside a try block, and if you get an exception it wasn't a duck...
Comment: The problem with this is if `var` is a string iteration will occur with probably unexpected results.
Comment: Despite the fact stated by Brian M. Hunt, his is quite a pythonic solution, in terms of asking for forgiveness rather than permission.
Answer: Another easy way to find out if a variable is either list or tuple or generally check variable type would be :
def islist(obj):
    if ("list" in str(type(obj))):
        return True
    else:
        return False

Answer: If you just need to know if you can use the foo[123] notation with the variable, you can check for the existence of a __getitem__ attribute (which is what python calls when you access by index) with hasattr(foo, '__getitem__')
Answer: Has to be more complex test if you really want to handle just about anything as function argument.
type(a) != type('') and hasattr(a, "__iter__")

Although, usually it's enough to just spell out that a function expects iterable  and then check only type(a) != type('').
Also it may happen that for a string you have a simple processing path or you are going to be nice and do a split etc., so you don't want to yell at strings and if someone sends you something weird, just let him have an exception.
Answer: In principle, I agree with Ignacio, above, but you can also use type to check if something is a tuple or a list.
>>> a = (1,)
>>> type(a)
(type 'tuple')
>>> a = [1]
>>> type(a)
(type 'list')

Answer: Another way is to use isinstance with typing.
from typing import List, Tuple
>> isinstance([1,2], Tuple)
False
>> isinstance([1,2], List)
True

Answer: Not the most elegant, but I do (for Python 3):
if hasattr(instance, '__iter__') and not isinstance(instance, (str, bytes)):
    ...

This allows other iterables (like Django querysets) but excludes strings and bytestrings.  I typically use this in functions that accept either a single object ID or a list of object IDs.  Sometimes the object IDs can be strings and I don't want to iterate over those character by character. :)
Answer: You know... I may be doing this the stupid way, but I do this:
try:
    len(thing)
except:
    # not a list

Like, if I can know the length of it, it gotta be more than one thing.
Edit: Just realized it won't work if the non-list item is a string (since a string is essentially a list of characters).
Comment: That's not going to separate a list or other collection from a string, though. Strings support len()
Comment: The typechecker may get a bit mad with this, though.
Comment: Just realized it. Works nice for numbers and such, though.

Test if a variable is a list or tuple


Flamenco - How to find band mates that appreciate it and in a new town?

Question: I moved into a regional town in Australia, that is mostly surrounded by Blues, Rock, Pop or Top-40 musicians.
The closest answer I found here is this one, which has some good suggestions that apply to almost any new environment. Thank you.
However, I feel my situation is somewhat special.
I perform flamenco guitar, and out here in outback Australia - flamenco is mostly akin to "flamingos" - the bird! That's about as much as they know of it! The Gipsy Kings is another. I do play GK music, but only because most people recognise those songs - Bamboleo, Djobi Djoba, etc. And it's "easy" to dance to, and easier to play of course.
Sorry, but aside from some blues, I dislike the other genres. They are too common and fraught with people that think they can perform them, and worse - think they can sing.
I am not a snob, but I have been performing for over 20 years as a solo artist mostly, and I know music - from "that music". About the only people that appreciate flamenco are middle-aged retirees that also appreciate jazz, world music, and classical. I might as well play at retirement villagers (which I've done btw).
However, I want to try and form a flamenco group, with cajonero (cajon player), cante jondo singers (flamenco style), and maybe a bass player. YouTube "Paco de Lucia" and you'll know what I mean.
I know looking for Spanish or Latin people in this town is one option, which I've done, but unfortunately there is only ONE Spanish girl that also happens to dance flamenco, but for some reason she's not into it anymore and has resorted to partying, drinking, or dancing out at clubs for all I know.
So any tips on how I can convince Australians to join me!? Yeah - almost impossible.
Answer: No matter what the style of music, in this day an age it's getting harder to find people who want to get together and play.  The emphasis is so much less on performance and so much more on recording.  Being in a similar situation in that I've recently begun playing after a long layoff I've found that the best way to find people is to make yourself visible in music stores, teaching areas and try to introduce yourself to every musician you can find regardless of style.  Also, attend as many  live music events as you can regardless of style.
The more you expose yourself to the people who do actually play, the better your odds are of meeting someone.  You are in a very specialized area and it won't be easy but persistence pays off.
Comment: Correct! The more people you know, the more chances you get. Like the old saying, "It's not what you know, it's who you know."
Answer: The times I wanted to form a band, I just called up a few friends and said, "Let's form a band." It always worked. Of course, I was always forming a Western Swing dance band, so it was pretty easy. We did play a large range of music though (almost as many types as a ballroom orchestra.)
Comment: Yeah but the issue I am having is the lack of interest in this area for my style of music. I guess I'll just keep advertising and hopefully someone will be interested