To access request parameter in socket.on function

Question: I'am beginner of node.js,Sorry if I went wrong.
To get the parameter passed in URL like localhost:3000?id=man&fm=gilli I used
<code>   app.get('/',function(req, res){
     var now = req.query.id;

     res.sendfile(__dirname + '/index.html');

   });
</code>
My doubt is I want to access fm in socket.on function,for that I have tried like this
<code>            io.sockets.on('connection',function(socket){

                socket.nickname = req.query.fm;   //here I accessed it
            users[socket.nickname] = socket;

        });
</code>
But it getting error that:
<code>        req is not defined.
</code>
A condition here is we should not store fm parameter in global variable,Means we have to directly access the parameter passed in url in io.socket function.
i.e:In the below code fm should not be accessed like id parameter.
My total code is:
<code>    var express = require('express'),
    app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
mongoose = require('mongoose'),
    users = {},
now,
other;

    server.listen(3000);

        app.get('/',function(req, res){
             now = req.query.id;

             res.sendfile(__dirname + '/index.html');

        });

       io.sockets.on('connection',function(socket){

              socket.nickname = now; // parameter id stored here using a global variable

               users[socket.nickname] = socket;

socket.on('send message',function(data, callback){
    var msg = data;

         var name = req.query.fm;    //here I got error
         var msg = msg;
         if(name in users){

                 }else{
         callback('Error enter a valid user.');
         }

  });

});
</code>
Answer: You need to implement an authorization.

In Express, when a socket connects, we don't know which session it belongs to by default, meaning we can't do anything private with that connection.

LearnBoost / socket.io
Authorizing and handshaking with Socket.IO
A blog post with an implementation
Another blog post with an implementation


How to implement thresholded softmax in Keras?

Question: I would like to implement a threshold after the final softmax layer in a Keras-built classification problem so that class assignments with probability below some threshold alpha are disregarded (i.e. assigned to neither class). Would you be able to show me how to do that?
Thank you :)
Answer: Since this is going to be used only in prediction, not in training (i.e. in the back-propagation algorithm), a typical and non-invasive way would be to predict the class probabilities via predict_proba method and use them in your custom decisions. Once you obtain the predicted probabilities, you can define other rules of higher order complexity.


Ramification of the field extension $\mathbb{Q}_p(\zeta_{p^2},p^{1/p})$

Question: I am interested in the extension of local fields $\mathbb{Q}_p(\zeta_{p^2},p^{1/p})/\mathbb{Q}_p$. Is it totally ramified?
Here are the partial results that I have:

It is a field extension of degree $p^2(p-1)$. To see that, note that it suffices to show $p^{1/p} \not \in \mathbb{Q}_p(\zeta_{p^2})$. Indeed, otherwise $\mathbb{Q}_p(p^{1/p}) \subset \mathbb{Q}_p(\zeta_{p^2})$, thus $\mathbb{Q}_p(p^{1/p})/\mathbb{Q}_p$ is an abelian extension, hence contains its conjugate $\zeta_p \cdot p^{1/p}$, hence also contains $\zeta_p$, which is of degree $p-1$ a contradiction.

It's Galois group is an explicite group of order $p^{2}(p-1)$, its element its uniquely determined by its action on $\zeta_{p^2}$ and $p^{1/p}$.

Its ramification index is at least $p(p-1)$, indeed, $\mathbb{Q}_p(\zeta_{p^2})/\mathbb{Q}_p)$ is a totally ramified extension of degree $p(p-1)$

But I can not figure out whether it has chance to have an unramified subextension.
Comment: I have an argument that the extension is still totally ramified, but it uses higher ramification theory, and can't possibly be the easiest proof available. Very likely someone slicker than me can give a better; if you don't get one in several days, come back to me.
Answer: So you're taking a $p$-th root of $p$ in $K=\mathbb{Q}_p(\zeta_{p^2})$, a local field that contains all the $p$-th roots of unity. Let $L=K(p^{1/p})$, it has degree $p$ over $K$.
As $K$ is totally ramified over $\mathbb{Q}_p$, $L$ is totally ramified over $\mathbb{Q}_p$ iff $L/K$ is totally ramified. Suppose (for the sake of contradiction) that it is false.
Then $L/K$ is unramified of degree $p$, and thus contained in a cyclotomic extension. Therefore $L/\mathbb{Q}_p$ is contained in a cyclotomic extension, and again we find a contradiction as $\mathbb{Q}_p(p^{1/p})$ is not Galois.
Comment: Cool answer! And it generalized to $\mathbb{Q}_p(\zeta_{p^n},p^{1/p})/\mathbb{Q}_p$ for any $n$!


Contador Click JavaScript Jquery

Question: Estou aplicando atributos e nomes de imagens via Jquery através de um array de imagens e nomes.
A imagem abaixo ilustra as imagens do array carregadas.

Quando eu clico exibo o nome da imagem contido no array.
Abaixo a imagem ilustra o que ocorre quando é realizado o evento click, os nomes são exibidos embaixo das imagens, no caso ai só duas imagens foram clicadas.

Tenho que contabilizar os clicks também. Porém não sei como realizar esse mesmo evento no código abaixo:
Meu código html esta assim:

     onde vai o contador

E esta é o meu jQuery com evento click.
 const catsImages = ['cat01.jpg', 'cat02.jpg', 'cat03.jpg', 'cat04.jpg', 'cat05.jpg'];
    const catsName = ['Cat KiKI', 'Cat Edi', 'Cat Didi', 'Cat Kely', 'Cat Vivi'];

    let image = [...catsImages];
    let name = [...catsName];

    console.log(image);
    console.log(name);

    let count = 0;//Variavel contador

    $.each($('.catImag img'), function(index) {
        $(this).attr({
            src: image[index],
            alt: name[index]
        });
    }); //Update Cat cria os atributos para receber a imagem

    $.each($('figure'), function(index, el) {

        $(this).one('click', function(event) {
            /* Act on the event */
            $(this).append('
' + name[index] + '
');
        });

    });// update click name, exibe o nome do cat clicado

Comment: Não entendi o uso desta linha: `let $span = $('img').append('' + count + '');`... vc quer fazer um append dentro de uma imagem? Uma imagem é um elemento fechado e não aceita append. Poderia explicar melhor?
Comment: Essa linha eu esqueci de tirar era um teste que eu estava realizando. Ignore ela.
Comment: Removi a resposta. Tem que ajustar a pergunta com o código correto. Noa comentários vc está tirando e adicionando códigos. Tem é que editar a pergunta com o que vc quer e o código correto.
Comment: ok vou reformular a pergunta aqui.
Answer: Man tenta algo assim:
``

``
E esta é o meu jQuery com evento click.
var imageObject = [
{
src: 'cat01.jpg',
alt: 'Cat 01',
count: 0,
},
{
src: 'cat02.jpg',
alt: 'Cat 02',
count: 0,
},
{
src: 'cat03.jpg',
alt: 'Cat 03',
count: 0,
},
];
$('.catImag img').each(function(i, el) {
$(this).attr(
{
'src': imageObject[i].src,
'alt': imageObject[i].alt,
'data-count': imageObject[i].count
}
);
$(this).after('' + imageObject[i].alt + '');
$(this).after('');
})
$('.catImag ').click(function(){
var countIni = $(this).children('img').attr('data-count');

$(this).children('span').text(countIni = parseInt(countIni, 10) + 1);
$(this).children('img').attr('data-count',countIni)

console.log($(this).children('span'));

})

Comment: Hernani, eu entendi era melhor criar um array de objetos mesmo. retirei apenas a linha ``$(this).after('' + imageObject[i].alt + '');`` porque o nome não deve ser exibido antes do click. Somente no click. Obrigado mano. Você salvou o dia, o ano quero dizer. ;)
Comment: Eu mantive esta parte do código porque o nome é exibido após o click.

``$.each($('figure'), function(index, el) {

        $(this).one('click', function(event) {
            / Act on the event /
            $(this).append('' + image[index].alt+ '');
        });

    });``
Comment: Então vc poderia colocar isso dentro do metodo que faz a contagem pq ele vai ser executado quando clicar do mesmo jeito e não precisaria rodar um $.each. Quando você escuta um evento o jquery te passa o elemento através do $(this), então vc nao precisa de um $each pra escutar evento..
Comment: Ok. Obrigado mano.

Contador Click JavaScript Jquery


Singularities in Projective Space

Question: I'm trying to compute singularities and their type for the following equation in $\mathbb{P}^1$.
$$P(X,Y) = ax^3 + bx^2y + cxy^2 + dy^3$$
$a$, $b$, $c$ and $d$ are nonzero. If we consider the partials:

$d/dx = 3ax^2 + 2bxy + cy^2$
$d/dy = bx^2 + 2cxy + 3dy^2$

We see that the only possible singularity is at $[1:1]$ provided that $c = -3a - 2b$ and $d = 2a+b$. Furthermore, a quick look at the second derivatives

$d^2/dx^2 = 6ax + 2by$
$d^2/dy^2 = 2cx + 6dy = -(6a + 4b)x + (12a + 6b)y$

shows that the second derivatives at $[1:1]$ are only $0$ if $b = -3a$. If this is the case, our basic curve becomes
$$P(X,Y) = a(x-y)^3$$
and so it seems like we have a non-ordinary triple root at $[1:1]$ Is this correct?
 Furthermore, from here, I'm unsure of how precisely to work out what type of singularity we have if $b \neq -3a$. Our curve becomes
$$P(X,Y) = ax^3 + bx^2y- (3a + 2b)xy^2 + (2a + b)y^3$$
but since our singularity is at $[1:1]$, we can't use the same trick as in
Singular points of algebraic curve, multiplicity, ordinary?. How do I proceed?
Comment: Then that's not a curve, that's a collection of points - you should change that, too.
Comment: You have an issue: you say you're working with a projective plane curve, but all your coordinates are length 2 (like $[1:1]$), not length 3 like they ought to be.
Comment: Oops. Nomenclature mistake. The curve should be in $\mathbb{P}^1$.
Answer: Your effort has serious problems. It is not the case that the only singularities can be at $[1:1]$! For instance, for any point $[a:b]\in\Bbb P^1$, we can arrange to have singularities there: consider $(bx-ay)^3$.
The thing that's really going to help you out here is that $V(ax^3+bx^2y+cxy^2+dy^3)$ is three points counted with multiplicity. This is the same as saying that $f=ax^3+bx^2y+cxy^2+dy^3$ factors in to irreducibles in the following way:

It doesn't. This corresponds to a smooth point defined over a cubic extension of $k$.
An irreducible quadratic term and a linear term. This corresponds to the union of a smooth point over $k$ and a smooth point over a quadratic extension of $k$.
A product of three distinct linear terms. This corresponds to a union of three distinct smooth points.
A product of a linear term and the square of a different linear term. This corresponds to a smooth point and a fat point (not smooth!).
The cube of a linear term. This corresponds to a single fat point which isn't smooth.

What's going on in your question is that your argument with the partial derivatives has lead you astray. Your calculation of the partials is correct, but the math that follows after them is not.

Singularities in Projective Space


Error: Expression must be a modifiable lvalue using strings

Question: I am trying to create a function that counts the number of times a specific character is used in a string.The portion that is giving me the error is:
<code>s[i] = tolower(s[i]);
</code>
Code:
<code>#include <iostream>
#include <string>
using namespace std;

unsigned howMany(char c, const string & s);
string changeCase(const string & s);

int main() {
    char z;
    string name;
    cout << "Enter char and string: ";
    cin >> z;
    getline(cin, name, '\n');
    cout << howMany(z, name) << endl;
    cout << changeCase(name) << endl;
}

unsigned howMany(char c, const string & s) {
    unsigned count = 0;
    for (unsigned i = 0; i < s.size(); i++)
    {
        if (c == s[i]) { count++; }

            if (isupper(s[i])){ s[i] = tolower(s[i]);
            count++;
        }
    }
    return count;
}
</code>
Answer: You declared s as const.  You can't change it.


Combinatorics Path - Graph problem

Question: A $3 \times 3 \times 3$ cake cube is made of $1 \times 1 \times 1$ little cake cubes.
A rat eats one of the top corner little cubes. After eating any little cube , the rat can go on to eat any adjacent little cube.
Can the rat eat through all cake cubes finishing last with the center cube ?
Comment: Hint: The "obvious" graph is bipartite, has an odd number of vertices, and the corner and the center are in different parts.
Answer: Alternately colour the cubes black and white so that the rat starts at a white cube. There are $14$ white cubes and $13$ black cubes, so any path through all cubes must end at a white cube. But the centre cube is black by the colouring, so the rat cannnot eat all cubes and end up at the centre.

Combinatorics Path - Graph problem


Como usar o Cascade Delete entre duas tabelas?

Question: Tenho 2 tabelas:
produtos
id
nome
...
produtos_fotos
id
id_produto
foto
No PHP irei fazer um DELETE no Produto, e por consequência quero que automaticamente delete TODAS as fotos do produto deletado, claro que apague também o registro na tabela.

No caso, primeiro devo mexer com Cascade (SQL), depois no PHP para deletar os arquivos, certo ?
Answer: Quando você coloca na sua FK on DELETE CASCADE quando você deletar a tabela o efeito será cascata, ou seja se deletar o Produto suas fotos serão deletadas automaticamente e você não precisa deletar no PHP pois isso é automático no banco. Porém o cascade deverá ser utilizado com cautela, se você ainda precisar de alguma informação da tabela utilize SET NULL e ao MAPEAR O FK deixe com NULL.


gedit: symbol lookup error: /usr/lib/x86_64-linux-gnu/libgdk-3.so.0: undefined symbol: cairo_surface_set_device_scale

Question: This is my error
gedit: symbol lookup error: /usr/lib/x86_64-linux-gnu/libgdk-3.so.0: undefined symbol: cairo_surface_set_device_scale

I want to start the gedit in my account.
but using sudo, it's running.
I don't know why..?
My OS is Ubuntu 14.04 LTS,
I set up anaconda2.7, Opencv2.4.12, cuDNN v4, CUDA 7.5, Caffe.
and my PASS is
export PATH="/home/myAccount/anaconda2/bin:$PATH";
export PATH=/usr/local/cuda/bin/:$PATH;
export PATH=/usr/local/:$PATH;
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:/lib/x86_64-linux-gnu:/home/myAccount/anaconda2/lib:$LD_LIBRARY_PATH;
export PYTHONPATH=/home/myAccount/caffe/python:$PYTHONPATH;

also, i added sudoers "myAccount ALL=(ALL:ALL) ALL"
Help me~~~.
How can I run the gedit in my account??
Comment: first take a look at here http://stackoverflow.com/help/how-to-ask
Comment: I'm so foolish.

Because i forgot to add a myAccount in /etc/hosts.
Sorry.
Answer: The problems seems to be in the .../anaconda2/lib part in LD_LIBRARY_PATH. Resetting that should work.
LD_LIBRARYPATH= gedit


NSData is returning 0 bytes

Question: I am trying to do a simple POST request. However the results seem different in POSTMAN plugin in chrome and in iOS simulator.
Here is the snapshot from POSTMAN:

As you can see, I get the JSON data in retun.
Here is my code to do the POST request:
    NSError *error;
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:kPostURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];

    NSString *params =[[NSString alloc] initWithFormat:@"fname=%@&lname=%@&email=%@&password=%@&switchid=%d&didflag=%@",fname,lname,email,pass,switchid,flag];

    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSLog(@"response is %@",response);
        NSLog(@"erros is %@",error);

        NSMutableDictionary * innerJson = [NSJSONSerialization
                                           JSONObjectWithData:data options:kNilOptions error:&error
                                           ];
        NSLog(@"JSON data is %@",innerJson);

    }];

    [postDataTask resume];

And when I try to print the values in debugger, I get
JSON as null and NSData as 0 bytes. But I get the status code as 200 which is a success.
HEre is the response I get:
      { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Length" = 0;
    "Content-Type" = "text/html";
    Date = "Thu, 25 Feb 2016 02:04:02 GMT";
    "Keep-Alive" = "timeout=5";
    Server = "Apache/2.4.12";
    "X-Powered-By" = "PHP/5.5.30";
} }

Why do I get NSData as 0 bytes ?
Answer: in the request in chrome you have the parameters as URL params. in the ObjC version you are adding the params as part of the post.
instead of adding the the params as part of the body:
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

add it as part of the query:
NSURL *url = [NSURL URLWithString:[kPostURL stringByAppendingFormat:@"?%@", params]];

NSData is returning 0 bytes


Importing modules from relative path to absolute

Question: I am trying to run a program which it specification say for python 2.6 I am running it with python 2.6.6, so it should work but I found that the importation fails see this question, and this sample:
from rnaspace.dao.storage_configuration_reader import storage_configuration_reader

This is due to a version change (I doubt) or of some of the environment on the original server? A solution is in the question cited, but I there is another way to solve this problem that it doesn't involve to change each file with this kind of importation?
Answer: Your import statement assumes python knows where the 'rnaspace' package is. Maybe you need to add the path to the package rnaspace in your include path?
    import sys

    pathToRnaspace = "/path/to/the/rnaspace/package"
    sys.path.append(pathToRnaspace)

    from rnaspace.core.putative_rna import putative_rna

Comment: I don't see how you can avoid that, I'm afraid. Each file would need to import the packages it uses. I'd love to know if there is a way, if I'm wrong!
Comment: Works but this implies that I must do it for each file of the program to work well...


If fugue voices are in different keys how come they don't clash?

Question: I was reading how a fugue plays simultaneous voices in different keys (?) I was wondering how they don't clash with each other. Or to put it in another way, what keys can you play together such that they don't clash. For example, I can't play a C major scale with a C# major scale it would clash. So do fugues have rules as to which scales you can play simultaneously?
Edit: I may have been wrong in my assumption. Looks like all voices modulate to a new key. My bad. But it's possible to have a treble clef and a bass clef not sharing same signature / key.
Comment: Could you reference where you're reading from, or which fugue(s) specifically? "So do fugues have rules as to which scales you can play simultaneously?" Depends on who's writing the fugue, and when. Bach would say "Yes." Bartok would say "No."
Comment: "I've never seen a situation before where two scales are played simultaneously in modern music." -- [See _polytonality_](https://en.wikipedia.org/wiki/Polytonality)
Comment: @LSM07 https://en.wikipedia.org/wiki/Fugue#Exposition I understand that it says that the dominant of the tonic is being played. but still I thought that if I play, for example, a C major scale and a G major scale simultaneously they'd clash. I've never seen a situation before where two scales are played simultaneously in modern music.
Comment: There are some notable pieces of music that do include two voices in different keys; this created a *cross-relation*, if I remember my terminology correctly.
Comment: The conclusion of Bach's fugue BWV 542 certainly sounds like two keys are being played simultaneously, can anyone elucidate?
Comment: @songololo that should probably be a different question.
Answer: The subject of a fugue is first stated alone, then a second voice is added which re-states it at a different pitch (typically a 5th higher).  If this 'answer' is literally transposed it's called a 'real' answer.  If it's modified to remain in the tonic key it's a 'tonal' answer.
But the initial statement and the answer aren't played simultaneously!   To over-simplify, it's just as if a song has a bar of C chord then one of G.
Comment: LOOK at some fugues.  Source first, then analysis.
Comment: You mean in series?  Tandem IS parallel.  Fine.  But LOOK at some fugues to see how it DOES work before complaining that It CAN'T work!  This is your old problem of studying the theory rather than the music.
Comment: Only when it's a bicycle!  Otherwise I think it generally just means 'together'. At best, it's ambiguous.  https://www.collinsdictionary.com/dictionary/english/in-tandem
Comment: @LaurencePayne -- apparently tandem can mean one before the other for horses, too, but this is a spatial meaning. Here we are talking about a temporal meaning, i.e., one statement comes before the other _in time_. I have never heard anyone use "tandem" to mean sequentially in time (as OP is using it), but always to mean together in time (as you are using it). Even for horses and bicyclists, I think that the point is that they are working together, not one after the other.
Comment: I didn't know it was in tandem, I thought it was parallel. I'm simply asking a question.
Comment: tandem means one after the other.
Answer: The wikpedia reference given by the OP in a comment says nothing about "playing voices in two keys simultaneously".
But the assertion that

I can't play a C major scale with a C# major scale it would clash

is not true in any case. The following example doesn't "clash," by any reasonable definition of the word. Every interval is (enharmonically, if not notationally) either a major or a minor third.

Theorists have invented "rules" for writing fugues, but their main purpose has been in marking student examinations, not composing music. One well-known rule book is the so-called "fugue d'école" which was written in the 19th century at the Conservatoire in Paris by Cherubini.
However, it's amusing that about three quarters of the fugues in Bach's "Well Tempered Clavier" would have failed the Paris Conservatoire's composition examinations. Of the eight so-called "essentials" in Cherubini's marking scheme, many of Bach's fugues only contain two or three, which is hardly a passing grade!
In fact, a fugue doesn't have to be in a "key" at all. Here is an example of one which is not. Note: the duration is about 60 minutes - somewhat longer than Bach's fugues. Don't be fooled by the slow start - things start to get more exciting after the first 10 minutes or so...
Of course some people (and perhaps the OP) might not consider that fugue by Sorabji to be "music" at all - but not everybody shares that opinion.
Answer: Again, it needs consonance and in order to create a fugue, you have to make the different voicings interlace with each other so that they can all state the subject without clashing.
Answer: I don't think it makes sense to talk about a piece being in two keys simultaneously. A human hears a piece of music as one experience, not two independent ones that can be superimposed if the listener wants to.
That said, people have written music in two keys at the same time. They call it bitonal music or polytonality. But this is a theoretical device. Many theorists reject this idea as it isn't sensible and has no explanatory power. Why? Because it is very hard perceive it as two different things heard at the same time. Even if they are different instruments in different registers.
But yes, you can take a piece of music, for example a piano piece, and just change the key signature of the bass clef only and play it. But it doesn't make a lot of sense to do it and it will almost certainly sound very bad.
And yes, a C# played in a piece in C major does clash. Just because it can be done and just because you can even make it sound good, that doesn't mean it doesn't clash. Many intervals are dissonant as well, and we use them. We need things that are dissonant and things that clash to make music interesting. Both saying that you are never allowed to play C# in C or saying that nothing is eve dissonant or clashes, because it can be done if you want is misguided. Music theory explains why something sounds a certain way. And playing a C# over a C chord rather than a C certainly clashes. And the theory explains why.
Comment: The OP is asking specifically about fugues.
Comment: The OP was confused. See the edit. The question was restated ignoring the issue about themes in fugues being stated in different transpositions.
Comment: What? You *can* listen to music as if it's multiple independent experiences that can be superimposed on top of each other. Just listen to a mashup that involves two or more different audio tracks on top of each other (e.g. a mashup of different versions of the same video game character's boss theme) or a karaoke version of a song, then the original song. Occasionally, you run into music that plays an accompaniment track first, then the accompaniment with its melody on top.


Looking for in depth material on a formal propositional calculus using only the NAND connective

Question: I am looking for secondary literature on a formal propositional calculus which has the NAND connective as its sole connective.
I am coming upon many pages which briefly state that Nicod had shown that propositional logic could be done with 1 axiom using only the NAND connective, and one inference rule. These are given, but then that is it.
There are some books which go into it a bit, but kind of only on the surface and not as much as I'm looking for.
None of these pages actually go into this proof at all, or how the axiom and inference rule were found. Nor do they go into any theorems about the system.
I am looking into the history of the NAND/NOR connectives and would like to explore a system which uses only one of those, but I am having trouble finding decent material. Of course, there is the paper written by Nicod himself and the earlier one by Sheffer, but I am wondering if there are any explanatory papers/websites that go into more detail and explanation.
Thanks
Comment: You can see Emil Leon Post, *Introduction to a general theory of elementary propositions* (1921), into: Jean van Heijenoort (editor), [From Frege to Gödel: A Source Book in Mathematical Logic](https://books.google.it/books?id=v4tBTBlU05sC&pg=PA264) (1967), page 264-on.
Answer: Nicod's paper actually didn't prove his axiom complete.  Thomas Scharle wrote a paper which provides a proof of completeness with some discussion of the history of this problem.  Scharle's paper also has relevance for exploring a system with only a NOR connective, a single rule of inference, and a (relatively short) single axiom.  It's all in Polish notation, with D standing for NAND, S for NOR, K for conjunction, N for negation, C for implication, and A for disjunction.
Comment: Ok cool, thanks
Comment: I think I found a (non-critical) mistake in that paper. Page 5 line 2 should be "30, p/s, q/Dpp, r/p, t/Dpp = D24, t/s D31 - 31".


How can I hide the authoring information?

Question: Normally I would just click manage display and disable authoring information from showing, but with layout builder enabled, I don't have this option. I only have the Manage Layout option, which doesn't contain any way to disable the authoring information.
Answer: Try to disable this information in content type settings.


Laravel Moltin Cart call in custom repository

Question: I installed Moltin Cart on Laravel 4.2 and configured it as documentation suggests. Everything work perfect when I'm calling it from controller. Like Cart::insert() etc.
Problem is when I try to call same code in custom repository. I have this repository/namespace:
namespace MyApp\Repositories;

use MyApp\Interfaces\CartInterface;

class CartRepository implements CartInterface

...

So when i call Cart::insert in some of my functions inside this CartRepository class I got errors like "Class 'MyApp\Repositories\Cart' not found". I tried many variations of USE after namespace but nothing work. I got new error like

"Non-static method Moltin\Cart\Cart::insert() should not be called
  statically, assuming $this from incompatible context"

or similar.
Answer: How it usually be with programmers I find answer just after I put question. Before that I wandered around 1-2h.
So, solution is to put

use Cart;

I tried everything but that. :)


Como apontar links para raiz do site sem usar o .htaccess

Question: Como faço para apontar o diretório raiz sem precisar que eu coloque o index.php nos links e sem utilizar o .htaccess ?
Exemplo:

No exemplo acima, o logotipo que aparece em todas as páginas tem o link apontando para a página principal e eu queria apontar sem ter que chamar o index.php no link, tem alguma forma de fazer isso sem ter que utilizar o .htaccess ?
Comment: Já tentou usar o `$_SERVER['DOCUMENT_ROOT']`?
Comment: @TaffarelXavier Não, mas essa variável global é dependente do Apache não é ? Ela não é tão recomendada para certas coisas, eu poderia usar ela no caso de apontamento de links ?
Comment: Segundo esta resposta, sim: https://stackoverflow.com/questions/13394924/php-serverdocument-root
Comment: Machado, qual a fonte? Porque, segundo o site oficial, há comentários com expressivos votos com o uso dela: https://www.php.net/manual/pt_BR/reserved.variables.server.php#112425
Answer: Traduzido PHP $ _SERVER ['DOCUMENT_ROOT']:
Nesse tipo de cenário, é sempre melhor criar um arquivo config.php e salvá-lo no diretório raiz. No arquivo de configuração, você define alguns parâmetros.
Chame esse arquivo de configuração em todas as páginas. Seu arquivo de configuração pode ser semelhante ao abaixo.
define('APP_NAME','nome-do-projeto'); //dentro da pasta htdocs (xamp) ou da www (wamp)
define('HTTP_SERVER', 'http://localhost/');
define('SITE_NAME', 'http://localhost/');
define('DOCUMENT_ROOT',$_SERVER['DOCUMENT_ROOT'].APP_NAME);

Você também pode definir seu diretório para imagens, css, etc. que você acha que serão usadas em vários lugares.
Então, você pode chamar desta forma:
<a href="<?php echo HTTP_SERVER.'index.php';?>" class="nav-brand"><img src="<?php echo HTTP_SERVER.'logo.png';?>" alt="Logo" />

Comment: Tu podes colocar sempre no topo dos arquivos `php` ou você pode usar um `autoload`.
Comment: Como eu carrego depois esse arquivo de configuração nas páginas ?
Comment: Usa include ou require.
Comment: E qual o método ideal de incluir esse arquivo de configuração, usando `include`, `require`, `include_once` ou `require_once` ? E você pode me dar um exemplo de onde colocar isso ?
Comment: Há diferenças entre elas, mas, basicamente, todas fazem a mesma coisa. Tu podes usar include. Mas você pode dar uma olhada, aqui mesmo, a diferença entre elas.
Comment: Consegui colocando o include no topo chamando o arquivo php conforme você informou e deu certinho, muito obrigado!
Comment: Nos links fiz da seguinte forma: ``. Como estou utilizando o EasyPHP para desenvolver um projeto, ele está sendo reproduzido a partir do Pendrive, então no painel eu criei um projeto para poder rodar diretamente do Pendrive e não da raiz.


What does this operator mean?

Question: I came accross this clock:

It features only the numbers 1, 2 and 3 in that order to get all of the numbers. However I have absolutely no idea what the notation is for number 5. If anyone cannot see the image it is basically $12_3$.
Just to clarify the answer to $12_3$ should be 5.
Answer: It is one of the common notations for numeral systems in different bases. In this case it is the ternary system. See, $12_3=1\cdot3^1+2\cdot3^0=5$.

What does this operator mean?


How to fill document header from jqgrid data

Question: ASP .NET MVC2 page contains order header data (order number, customer, order data etc):
<form id='_form' class='form-fields' action='' onsubmit='SaveDocument();return false;'>
<input id='Number' name='Number' />

<select id='PaymentTerm' name='PaymentTerm'>
<option value=''></option><option value='0'>Cash</option>
<option value='10'>10 days</option>
</select>

</form>

and order rows presented in jqgrid.
I'm looking for a way to fill order headcer data from json date from controller like
like jqgrid fills data.
To minimize request maybe it is best to return header data in jqgrid data request.
For this additional parameter documentId is passed to controller.
GetData returns document header as name value pairs in document object.
How to assign those values to form elements in browser in jqgrid loadcomplete or other place ?
public JsonResult GetData(int page, int rows, string filters,
          int documentId )

{
    var query = ...;
    var totalRecords = query.Count();

    var documentHeader = new FormCollection();
    // In production code those values are read from database:
    documentHeader.Add("Number", 123);  // form contains input type='text' name='Number' element
    documentHeader.Add("PaymentTerm", "10"); // form contains select name='PaymentTerm' element
    ...

    return Json(new {
        total = page+1,
        page=page,
        document = documentHeader,
        rows = (from item in query
                select {
                    id = item.Id.ToString(),
                    cell = new[] {
                        item.ProductCode,
                        item.ProductName,
                        item.Quantity,
                        item.Price
                    }
                 }).ToList()
    },
    JsonRequestBehavior.AllowGet);
}

Answer: If I understand correct your question you can use beforeProcessing or loadComplete callbacks to fill the form data based on the response from the server. The first data parameter of both callbacks (beforeProcessing or loadComplete) will contains all the data returned from the server. So you have access to document property of data and it has the same format as on the server.
I am not sure why you use document of the type FormCollection. It seems to me the most native to use anonymous type of data:
return Json(new {
    total = page + 1,
    page = page,
    document = new {
        number = 123,
        paymentTerm = 10
    },
    rows = (...)
},
JsonRequestBehavior.AllowGet);

but the exact type of document is probably not so important.
Inside of beforeProcessing or loadComplete you can just use the corresponding properties of data.document in the same format. For example
beforeProcessing: function (data) {
    var hearderData = data.document;
    if (hearderData) {
        if (hearderData.number) {
            $("#Number").val(hearderData.number);
        }
        if (hearderData.paymentTerm) {
            $("#PaymentTerm").val(hearderData.paymentTerm);
        }
    }
}

Comment: Thank you. Document header data is defined in database table dynamically at runtime, it depends which fields are important for specific company, sql select column list is built at runtime. So fixed names cannot used.


Erro no código de java

Question: Estou começando a aprender programação em java, e o seguinte aconteceu:
ERRO!!!!!
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Player cannot be resolved to a type
Player cannot be resolved to a type

at oo/oo.main.main(main.java:5)

package oo;

public class jogador {
    public void startplayer() {
        System.out.println("Player started");
    }
}

package oo;

public class inimigo {
    public void startenemy() {
        System.out.println("Enemy started");
    }
}

package oo;

public class main {
    public static void main (String[] args) {
        Player player = new Player();
        player.startplayer();
    }

}

Answer: Seja bem-vindo a nossa comunidade!
O erro mencionado é que basicamente sua classe "Player" não existe, portanto não é possível criar uma instância, veja:
Player player = new Player();

Então, renomeie a classe jogador para Player e faça o teste. Lembre-se, também se essa classe estiver em um arquivo separado. O nome do arquivo deverá ser Player.java e não jogador.java
public class Player

ao invés de
public class jogador

Answer: seu código tem alguns problemas, vou explicar sobre o erro e os demais problemas que vejo.

no método main você está tentando instanciar um Player, essa classe não existe, a que você escreveu se chama jogador.

as boas práticas recomendam o nome de classes CamelCase e começando com letra maiúscula. Também nessa ideia de nomes e para evitar problemas como esse que você está tendo, evite usar idiomas misturados no seu código.

Erro no código de java


Select statement returning no rows

Question: I was asked to write an MYSQL code that returns data from specific dates (2003-2005 December only)from my database. I, however, cannot figure out why I am getting no data returned. The code I am using is below. I tried to use the BETWEEN clause but I still get no data returned. Any help is greatly appreciated.
select
paymentDate, amount, discounted
From
payments
where
paymentDate >= 2003-12-01 and paymentDate <= 2003-12-31
and paymentDate >= 2004-12-01 and paymentDate <= 2004-12-31
and paymentDate >= 2005-12-01 and paymentDate <= 2005-12-31
Order by paymentDate;

Comment: I suspect the date field may have a different format. I would suggest selecting a single row with only the `paymentDate` to confirm the format.
Comment: Additionally to @MattCan 's suggestion. Try to put date in quotes like this paymentDate >= '2003-12-01'.
Comment: 2003-12-01 = 1990. Perhaps you're thinking of '2003-12-01'
Answer: Because the paymentDate may not be simultaneously in December of each of those years.
Instead connect each of the December conditional statements with or.
Also I included ANSI syntax for the dates, i.e. date '2003-12-01'
where
(paymentDate >= date '2003-12-01' and paymentDate <= date '2003-12-31'
 or paymentDate >= date '2004-12-01' and paymentDate <= date '2004-12-31'
 or paymentDate >= date '2005-12-01' and paymentDate <= date '2005-12-31')

Comment: Thanks for the help Vorsprung durch Technik but it is still returning no data. I am also certain that the table does contain data for December in all of those years.
Comment: You're welcome. I made an edit to my answer. Would you try that out?
Comment: Yes, success! That was the issue. Funny thing is I tried that but I think I had the DATE in the wrong place. Thank you for your help.

Select statement returning no rows


Data in C# to JSON

Question: I have a list of Departments and would like to show them inside a treeview. Im using C#, ASP.NET. I found this cool control called Treed http://bl.ocks.org/mbostock/raw/4339083/dd87a364df6d921740af7e5badef247665918919/ however it requires a JSON file.
What would be the best possible way to achieve this kind of JSON structure from ASP.net?
http://bl.ocks.org/mbostock/raw/4063550/flare.json
Currently I store this data as a DataTable. If there's a solution through any other collection please do advice as Im open to anything at this point.
Many Thanks for your help.
Comment: possible duplicate of [how to convert datatable to json in C#](http://stackoverflow.com/questions/17398019/how-to-convert-datatable-to-json-in-c-sharp)
Comment: Did you *try* searching for [data table conversions to json](http://stackoverflow.com/questions/2312982/from-datatable-in-c-sharp-net-to-json)?
Answer: First off, there are a couple of built-in serializers. You can use WCF DataContracts and the DataContractJsonSerializer to produce JSON data designed for consumption by your service endpoints. If your application uses a lot of WCF in its service architecture anyway, this serializer should be easy enough to incorporate.
There is also a JavaScriptSerializer class in System.Web.Script.Serialization; it has a less aspect-oriented customization scheme, requiring you to define a custom converter class if the serializer can't understand your class (or its default behavior isn't what you want), but given you control both the production and consumption of this JSON data and so you can theoretically adapt the client-side scripting to deal with the default behavior, overall this is probably the simplest way to turn an object into JSON.
Lastly, there's a third-party library, JSON.NET, available at http://www.newtonsoft.com/json. It's pretty good; I've used it in a few projects for JSON results of AJAX-y ScriptMethods. It has attributes you can use to make small customizations to serialization behavior, without the full weight of WCF DataContracts.
Answer: Have you considered this example:
<code>Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
//   "Name": "Apple",
//   "Expiry": "2008-12-28T00:00:00",
//   "Sizes": [
//     "Small"
//   ]
// }
</code>
Here are some links to consider:
This link lets you generate c# classes with JSON:
http://json2csharp.com/
This link supports classes to JSON
http://www.json.net

Data in C# to JSON


proof regularity of graph

Question: I have the following question:
Suppose Γ is a non-complete graph, with every pair of joined vertices having exactly one common neighbor and every pair of non-joined vertices having exactly 2 common neighbors. My professor proved in class that such a graph is regular by proving that any two non-joined vertices have the same number of neighbors. My question is: do we not also need to prove any two joined vertices have the same number of neighbors and that these two numbers (for joined and non joined) are the same?
Thanks in advance.
Answer: Let $\Gamma_2$ be the graph with the same vertex set as $\Gamma$, but with two vertices in $\Gamma_2$ adjacent if and only if they are at distance two in $\Gamma$. Your professor's argument is valid provided $\Gamma_2$ is connected. But if $\Gamma_2$ is not connected then $\Gamma$ must be bipartite and, since it contains triangles, it is not bipartite.
To see my first claim, if $a$ and $b$ are vertices at distance two and $c$ is at distance two from $b$, then $a$ and $c$ must have the same valency, and so it follows that vertices in the same component of $\Gamma_2$ have the same valency in $\Gamma$. For the second claim, the key is that any two vertices that lie on an
odd cycle must have the same valency.
Comment: Here Γ2 is just the complement of Γ?
Answer: If any two non-joined vertices have the same number of neighbors, take a,b to be non joined vertices of Γ. Then there is a neighbor of b that is not connected to a: Since a and b have precisely two common neighbors and b must have exactly one common neighbor with each of them (call them c1 and c2). note: a cant be connected to either c1 or c2 cause then it has 3 common neighbors with b. So then a and c1,c2 have the same valency. So then b and c1,c2 have the same valency. But b and c1,c2 are connected.

proof regularity of graph


Analytic function on the unit semicircle that sends reals to reals and the arc to the arc must be rational.

Question:
Given a function $f$ that is analytic in the unit semicircle such that $f$ is real and continuous on the diameter of the semicircle, and such that  $|f(z)|=1$ on the arc of the semicircle, prove that $f$ is a rational function.

This is an exercises from an old Complex Analysis Qualifying Exam at my university.
Comment: Are you comfortable with the reflection principle?
Comment: @DanielFischer, I am now. So $f$ extends to an analytic function on the unit disc.
Answer: Reflection in the diameter gives an analytic function $f_1$ on the unit disk with $\lvert f_1(z)\rvert = 1$ for all $z$ with $\lvert z\rvert = 1$. Then reflection in the unit circle -
$$f_2(z) = \begin{cases} f_1(z) &, \lvert z\rvert \leqslant 1 \\ \dfrac{1}{\overline{f_1(1/\overline{z})}} &, \lvert z\rvert > 1\end{cases}$$
gives an entire meromorphic function $f_2$. Since $f_2$ is either analytic at $\infty$ (if $f_1(0) \neq 0$) or has a pole at $\infty$ (if $f_1(0) = 0$), it follows that $f_2$ is actually meromorphic on the sphere $\mathbb{C} \cup \{\infty\}$, hence rational.


Equivalence of correlation formulas?

Question: Is this correlation $$r=\frac{\sum_{i=1}^nx_iy_i-\overline y\sum_{i=1}^nx_i}{\sqrt{(\sum x_i^2-\overline x\sum_{i=1}^nx_i)(\sum y_i^2-\overline y\sum_{i=1}^ny_i)}}$$ equivalent to the correlation of Mathematica
??
I new with this topics and I have a bunch of data and I need to compute the correlation, so I was just trying to find some software  to make evertyhing easier.
Comment: with n=2 in the r formula
Comment: Your formula is standard. Not familiar with regression in Mathematica. For someone who is, it might be helpful if you explained $a$ amd $b.$
Answer: Comment: Suggest you investigate R statistical software.
Available without cost from r-project.org. Lots of blogs, etc. online to offer help.
Don't
try to learn 'everything' at once. Learn how to use R for each new topic as
the need arises.
Brief demo:
x = rnorm(20, 100, 15);  e = rnorm(20, 0, 5);  y = x + e
cor(x,y)
[1] 0.9268968
summary(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  69.60   94.03  102.70  104.20  114.80  135.50
sd(x)
[1] 15.83722

plot(x, y, pch=19)

hist(x, col="skyblue2", label=T, ylim=c(0,8))
rug(x)

Equivalence of correlation formulas?


TrueCrypt to protect Windows server and web application

Question: As an additional layer of security on a windows server (stored on-site) I am
considering to use TrueCrypt.
However my concern is if my webapp will still work as expected? I dont want anyone
to access the machine but still have the webapp working as normal over the LAN.
Thanks
Answer: I think for any large-scale application that has to deal with high load, this would be a bad idea, but if it's small, this is a fine solution to encryption your data and running your web app off the mounted TrueCrypt drive.
Comment: the app itself will be used in a small office with 4 client PCs.its not large scale. Would encrypting the C drive or partition on the server still allow the webapp to be hosted over the LAN/data to be read/written to the database on the server etc?
Comment: Yes, TrueCrypt makes this seamless.
Answer: The the way TrueCrypt and similar full disk encryption applications work hides the encryption layer from the operating system/applications etc. There is a slight performance hit, as every disk access requires an encrypt or decrypt, but for a low load application it will just work.
The slight caveat would be around unattended reboots - I am guessing you only use this server when you are on site, but if you needed to use it remotely, and a power cut had caused it to power down, you would need a physical presence to get it started up again.
Comment: the server will be used when i am offsite. so that may be an issue if im not around and the box shuts down unexpectedly. Could I, encrypt a partition or even folder and give access to a user to start stop the services?
Comment: @Santiago - if you are just encrypting a partition or folder, then yes, you will be able to do that. Not quite as secure as full disk encryption, but more practical in this set of circumstances.


Why does the limit of this sum of powers of logarithms equal the Gamma function?

Question: Playing around with a proof of a generalized Hardy-Littlewood Tauberian theorem (I'll state the theorem at the end of this question), I ran into the following proposition:

Let $$F_n(\alpha) = \frac{1}{n}\sum_{k=1}^{n-1} \bigg(\log\frac{n}{k}\bigg)^\alpha.$$ Then $\lim_{n\to\infty} F_n(\alpha) = \Gamma(\alpha+1)$.

I have a proof in the case $\alpha\geq 0$, which is the case I'm interested in. I'll add it as an answer in a moment. But I want to post this as a question because it's interesting, and in case others come up with different proofs and might like to add their answers.

For posterity, here's the generalized Hardy-Littlewood Tauberian theorem. Suppose $\mu$ is a measure on $[0,\infty)$ whose cumulative distribution $D_\mu(x) = \mu([0,x])$ is of bounded variation. Let $\omega(s) = \int_0^\infty e^{-x s}d\mu(x)$ be its Laplace transform. Then:
$$D_\mu(x)\sim x^\alpha\ \mbox{ as $x\to\infty$ if and only if  }\ \omega(s)\sim s^{-\alpha}\ \mbox{ as $s\to 0$}.$$
I was playing with the proof in Ch 8 of the second volume of Taylor's book Partial Differential Equations.
Comment: It's the same trick from calculus where you look at a Riemann sum and make it into an integral, except they did a small change of variables first. You can actually do this without any big machines at all.
Answer: First, notice that in fact
$$F_n(\alpha) = \frac{1}{n}\sum_{k=1}^n \log(n/k)^\alpha,$$
as the last term is equal to zero.
Define $f(t) = -\log(t)^\alpha$. We may reinterpret $F_n$ as a Riemann sum for $f$ over $[0,1]$ for the partition $t_k = k/n$, where $k$ ranges over $1,\ldots,n$. Then
$$ F(\alpha) = \lim_{n\to\infty} F_n(\alpha) = \int_0^1 f(t)\ dt = \int_0^1 (-\log t)^\alpha\ dt $$
Now we exploit the fact that the logarithm is monotone: we perform a substitution. Let $s = -\log t$, so that $t = e^{-s}$ and $ds = -dt/t$. Therefore $dt = -e^{-s}ds$. The limits of integration $0$ and $1$ become $\infty$ and $0$, respectively. The minus sign in $ds$ reverses the limits, and voila!
$$ F(\alpha) = \int_0^\infty s^\alpha e^{-s}\ ds = \Gamma(\alpha+1).$$
Comment: this is a good question as was your solution. FYI, you can skip the last step and go directly to the gamma function. Euler originally defined the gamma function as a factorial via an infinite product and then with the integral, $n! = \int_{0}^{1} (-\ln(t))^{n} \mathrm{d}t$ for $n \in \mathbb{Z}^{+}$. Of course your analysis recovers the more conventional integral form.


sqlx installation fails due to mismatched types

Question: I'm installing sqlx on Ubuntu 18.04:
cargo install --git https://github.com/launchbadge/sqlx sqlx-cli

I get the error
 error[E0308]: mismatched types
 --> sqlx-cli/src/opt.rs:8:20
  |
8 |     #[clap(short = "D", long)]
  |                    ^^^ expected `char`, found `&str`

$ rustc --explain E0308

    Expected type did not match the received type.

    Erroneous code example:

    ```
    let x: i32 = "I am not a number!";
    //     ~~~   ~~~~~~~~~~~~~~~~~~~~
    //      |             |
    //      |    initializing expression;
    //      |    compiler infers type `&str`
    //      |
    //    type `i32` assigned to variable `x`
    ```

    This error occurs when the compiler is unable to infer the concrete type of a
    variable. It can occur in several cases, the most common being a mismatch
    between two types: the type the author explicitly assigned, and the type the
    compiler inferred.

$ rustc --version
    rustc 1.47.0 (18bf6b4f0 2020-10-07)

$ cargo --version
    cargo 1.47.0 (f3c7e066a 2020-08-28)

The full logs
How can I solve the error and complete the installation?
GitHub issue
Comment: Then this is a bug in `sqlx-cli`, you will need to file a bug with them and/or use a [released version](https://crates.io/crates/sqlx-cli) with `cargo install sqlx-cli`.
Comment: `"D"` defines a _string_ which just happens to contain a single character. Short options in Clap are `char`, which is defined with simple quotes: `'D'`.
Comment: this error is the output of "cargo install --git https://github.com/launchbadge/sqlx sqlx-cli" not of my application, I'm not sure how am I supposed to complete that installation
Comment: I've already linked the github issue in my question (bottom), I'm looking for a workaround to get me going while the issue is being addressed
Comment: apparently I'm not the only one experiencing the issue
https://github.com/launchbadge/sqlx/issues/730#issuecomment-707733077
Answer: running
cargo install -f --git https://github.com/launchbadge/sqlx sqlx-cli

instead of
cargo install --git https://github.com/launchbadge/sqlx sqlx-cli

fixes the issue
source


When can a manifold be curvature free?

Question: Recall that in a Riemannian manifold (or pseudo Riemannian) there is always the unique Levi-Civita connexion that annuls the torsion.
There are also manifolds (not needfully Riemannian) which are curvature free, thus the deviation from Euclideanhood is encoded wholly in the torsion tensor.
Question 1: Are there known sufficient, or necessary, or both necessary and sufficient conditions conditions for a curvature-free connexion (weaken assumptions to e.g. a Finsler manifold if need be) to be defined?
Question 2: Are there known sufficient, or necessary, or both necessary and sufficient conditions conditions that rule out a curvature-free connexion?
Question 3: Now, one thing that is bending my mind is: what happens to the holonomy group if we can have a curvature-free connexion? Obviously the holonomy group is trivial for a curvature free manifold. This seems to imply to me that somehow all connexions for that manifold must be curvature free, because there is no way to "continuously deform" a Lie group from the trivial group to a nontrivial one. Is this right? If not, how does the holonmy group "jump" from being trivial to something nontrivial?
Answer: I think this pretty much answers your questions 1 and 2.
As for question 3, I am not sure I understand what's troubling you. First of all, note that you can't necessarily always find a "continuous deformation" between two given connections. More to the point, sure, if you start with a flat connection and you deform it so that it's no longer flat, the holonomy group will "instantaneously" become non trivial. Said differently, the flat connections are special points in the space of connections  where the holonomy group collapses.
Comment: It seems from the MO discussion that this is not a trivial question. WRT to question 3, granted: there isn't always a cts deformation but can you give an example of where there is a cts deformation and where the holonomy group "collapses"? It's not altogether clear that it does, but not unreasonable either.
Comment: Yes, your questions 1 and 2 seem difficult (much easier if we were talking about Riemannian connections). For question 3, I'll try to think of an "explicit" example but computing the holonomy is difficult in general. But let me say this: take the Euclidean metric on the plane for instance, then under a generic deformation of the metric, the holonomy will be $SO(2)$.
Comment: wonderful, clear example, Seub, thanks muchly. Getting an actual example might be a bit harder: I guess I've piqued your curiousity now. Let me know if you come up with anything and I'll ask a question you can write up an answer to. Interesting about Milnor proving "flat" not possible for surfaces of Euler characteristic $\chi\neq 0$: not unexpected, but really nice that the abstract definition of curvature corresponds to intuition.
Answer: It is false that a flat Levi-Civita connection on a manifold necessarily has zero holonomy group. The theorem of Bieberbach - I think - is that the holonomy group must be finite.
For instance,the flat Klein bottle has holonomy Z2.
Here is a 3 dimensional flat orientable Riemannian manifold with holonomy group,Z4.
Take the quotient of R^3 with the standard flat metric by the group of isometries generated by the standard lattice( vectors all of whose coordinates are integers) together with the isometry (x,y,z) -> (x +1/4, z,-y)
It is probably true that any finite group can be the holonomy group of a flat Riemannian manifold.
The classifying theorem is that any compact flat Riemannian manifold without boundary is the quotient of R^n by a torsion free group that satisfies an exact sequence
o -> L -> G ->G/L -> 1
where L is a full lattice and G/L is a finite group. G/L is isomorphic to the holonomy group of the quotient flat manifold. The converse is also true. Any such group is the fundamental group of a flat Riemannian manifold.
There are flat Riemannian manifolds in every dimension as can be seen by taking the Cartesian product of the Klein bottle with flat tori.
I believe that there is no known method for identifying all of the flat manifolds. There may be classifications in low dimensions such as dimension 3 or 4. In dimension 2 the only ones are the flat torus and the flat Klein bottle.
The overwhelming difficulty in classification is that there is no way to classify the inequivalent integral representations of finite groups. Even very small groups - with only several exceptions such as Z2- have infinitely many inequivalent Z representations. This comes up because the quotient group G/L acts on the lattice,L, by conjugation (since the lattice is a normal subgroup of G) and this action is an integral representation. I say this just to illustrate that the condition of a flat Levi - Civita connection is extremely complex.
Even though the Pontryagin classes and Euler class of a flat Riemannian manifold must be zero - by Chern-Weil theory - the Stiefel- Whitney classes do not.For instance the first Stiefel-Whitney class of the Klein bottle is not zero. I would be surprised if there is a theorem restricting the possible Stiefel Whitney classes except that the top class must be zero.
Finally I would point out that the Moebius band made out of a piece of paper is a flat manifold with boundary and its holonomy group is Z2.
Comment: Great answer: I wasn't aware that a flat Levi-Civita connexion isn't altogether "anholonomic", but the finite holonomy group is an interesting "almost anholonomic" idea that I haven't yet thought about. Wonderful examples, many thanks. And your comment re difficulty in classification is pretty clear: you're talking the Novikov-Boone theorem or something like this, right?
Comment: The proof that there are infinitely many inequivalent Z representations of almost all finite groups I think is due to someone named Jones. I have no idea how the proof goes.
Comment: Also even if you have a Z representation in hand it still may be difficult to find all of the torsion free group extensions of the lattice by the finite group. This is a problem in group cohomology theory.

When can a manifold be curvature free?


When playing from a fake book, how strict should I be about the root note?

Question: I'm learning about playing from a fake book on piano.  A lot of the stuff I've read emphasizes voice leading and picking inversions so that your chords don't jump around too much (for example, a C triad in root position followed by a G in first inversion.)  However a lot of pieces use slash chords which explicitly state a root note or chords like a C6 which imply a C in the root since any inversion would become an Am7.  Does this mean the chords that do not specify a root need to have the root in the bass, or am I free to chose whatever inversion I want for those?
For example, this piece has both chords that specify a root and those that don't:
https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.pinterest.com%2Fpin%2F543176405053551459%2F&psig=AOvVaw2gjwMr4zj6YXncwhvBYyy8&ust=1654108987453000&source=images&cd=vfe&ved=0CAwQjRxqFwoTCLjP76WyivgCFQAAAAAdAAAAABAR
Answer: It depends on what you are trying to do.
If you're playing jazz from a fake book then you're free to do whatever you want with the music, the printed chords are only a recommendation (although for some standards particular voicings are part of the recognizable sound of the song). If you have a bass player, they are going to take care of the root notes. Otherwise it's up to you to decide whether it's important to make the roots clear. If you are trying to pick chord inversions to keep the hand in one place then it's obviously going be to more difficult.
If you are playing the melody with harmonies in the right hand and a bass line and/or accompaniment in the left then you have more possibilities to get the roots right.
Comment: Also, slash chords, or chords with specified bottom note, are highly-recommended voicings... you can play whatever you want, but for many jazz standards (etc.) part of the recognizable sound involves choice of voicings at critical junctures.
Comment: @paulgarrett I agree, and I've added those points to the answer.
Comment: @paulgarrett Out of curiosity, could you give some examples where a particular voicing is expected?
Comment: @Javier, ah, it happens so often that nothing springs to mind. I do recall in some Rogers-and-Hart tunes, and some Beatles tunes, that just "doing the usual" with the chord symbol missed the iconic sound. That is, when I initially ignored the slash chord or bass indication, it didn't sound _bad_, but it didn't sound like the original, at all. (This on piano...) The effect may be stronger in tunes that are not really so pianistic... but some Brahms, and some stride piano, have a similar feature.
Comment: Just a clarification, "slash chords" may be a recommended voicing, i.e. a chord inversion, normally to provide voice leading for the the bass. But they may also be an essential part of a harmony which would be altogether different without the bass indication. A relatively recurrent example is the so called IV/V chord, e.g. F/G in the tonality of C. F/G is a G dominant chord (with the 3rd and the 5th degrees omitted) that resolves into the chord of C. If you remove the G from the bass, you get an F chord, with an altogether different harmonic function.
Answer:
I'm learning about playing from a fake book on piano.

A jazz player with a lot of experience can improvise accompaniment. They might read a lead sheet and use it as just rough guide.
If you can't do that, if your just learning about jazz harmony and accompaniment, I would think you want to stick to the lead sheet and develop an understanding of how whoever wrote the lead sheet handled the harmony. But keep in mind, just about every different lead sheet you find of jazz tunes will have different harmonizations.
Sticking to the lead sheet shouldn't be misunderstood as "there is only one way to play the song." It really means get several lead sheets and stick to them to learn about jazz harmony.

...However a lot of pieces use slash chords which explicitly state a root note... Does this mean the chords that do not specify a root need to have the root in the bass...

To read the lead sheet properly the chords are given in root position unless there is a slash, in which case the slash determines the bass tone, technically not the chord root.
A good lead sheet will use slashes when particular bass lines are important to the song or a particular harmonization of a song.
Again, if you're learning, I think you want to embrace playing slash chords and the particular bass lines they create according to the lead sheet, to develop an understanding of how important a melodic bass line can be in harmonization.

...A lot of the stuff I've read emphasizes voice leading and picking inversions so that your chords don't jump around too much...

Yes, but on solo piano I think you want to distinguish between the bass line which will be given by chord symbols and slash notation and the rest of the voicing of the chord played above that bass.
The bass may move by a lot of jumps of fourths and fifths, other times the bass will move by steps. While the bass may have lots of jumps, the voicing of the rest of the chord above the bass will often move with all smooth step-wise voice leading, or at least move by the smallest distance. The details will depend on the accompaniment pattern. You might do something like this...

...where the bass is leaping as given in the chord symbols moving by all roots, but the upper voices of the chord move by smooth steps. That very typical of smooth voice leading: leaps in the bass and smooth steps in the upper voices.
If the lead sheet has slash chords, the bass won't leap, and so all of the voices could get a smooth step-wise treatment, like this...

I think you should also keep in mind that the left hand accompaniment doesn't always need to have the chord symbol completely voiced if the melody proper contributes some of the chord tones. Using the same basic pattern as above, but with a bit of rhythmic variation, you might have something like this...
Comment: Ah, yes, among other effects that sort of jumping bass emulates an oom-pah effect from the low brass in a marching band, etc. Also for folk-dance music like polkas. For me, it often makes more sense to think of a measure (for example) as a slow arpeggio in the bass, slow enough to fit a dance rhythm.
Comment: If you don't just bang on the notes, you can play those patterns subtly. Think of stuff like Chopin mazurkas. Arpeggiating the upper notes is another way to soften it. There are lots of figuration options. The point was to illustrate bass, slash chords notation, and voice leading.
Answer: When a 'slash bass' is not written, root position is assumed.
If you're playing solo piano, be guided (if not completely controlled - after all, this IS jazz!) by the notated inversions.  In a tune in C major, C (bass note C) has a quite different flavour to C/E (bass note E).   And F is a quite different chord to F/G - those slash notes can indicate more than just a simple inversion.
Remember, this is all about the BASS note.  Maybe you're playing it with your left hand, maybe there's a bass player in which case he takes responsibility for the basic inversion (and you keep out of his way!)   It's got nothing to do with whether you choose a close or open voicing in the upper (probably right hand) structure.
Follow the notation, obey the notation, hear how a specified bass note affects the harmony.   Then, if you like, play something else if you think it sounds better.  Like I said, this IS jazz :-)
Answer: Bass handles roots. If you're playing alone then while you can imply harmony you may also want to occasionally reference chord roots to help the listener


How to change "New content" text in entity connect autocomplete edit/add buttons?

Question: using entityreference autocomplete widget (field-widget-entityreference-autocomplete) with entity connect I have the buttons "New content" and "Edit content".
How can I just rename them in "New" and "Edit" respectively ?
These are coded in the value field of the input, hence I can't change them just with CSS..
I think I could do it on a form specific way using hook_form_alter, but I would like to apply it to any form where the widget appear.
I tried already hook_field_widget_form_alter(&$element, &$form_state, $context) but then I got lost, I am not sure it's the right place..
Comment: Entityreference doesn't offer content creation and modification by default, did you install entityconnect too?
Comment: @ben, yes.. I just edited the question to make it clear.. thank you
Answer: In a form alter you can access those two buttons with something like:
$field_name = "field_test";
$form[$field_name][LANGUAGE_NONE][0]["add_entityconnect__".$field_name."_0_"]["#value"] = t("New");
$form[$field_name][LANGUAGE_NONE][0]["edit_entityconnect__".$field_name."_0_"]["#value"] = t("Edit");

Adapt the name, language and cardinality of the field accordingly.
You can use a basic hook_form_alter to affect all forms. The widget creation code is in entityconnect.form.inc and it can't be altered (no hooks, no variables).


Laravel Dingo API - Only log 500 error, never send error details via api?

Question: I made the below controller to demonstrate the issue of handling 500 errors I am having with dingo api in laravel. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).
The methodgetUser() returns a 500 error intentionally due to the typo firsgt()
class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}

This is what the client sees:

In my controllers, I handle errors manually by returning a success/error json response from within the controllers, but if an error occurs that I did not expect, the api returns it and it has too much details for the client to see. Instead, these unexpected errors should bubble up to some sort of handler to return a generic error occurred response. In Laravel, setting APP_DEBUG = false in .env works for laravel (but not for dingo api), this has no effect and the full error is returned to the client. Looking for a safety net for errors that slip through the cracks.
How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?
Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'
Comment: Is it different if your env is set to production?
Comment: Nope, the real error is still returned when env is set to production
Answer: You should check your dingo config and set these two parameters to false.
APP_DEBUG=false
API_DEBUG=false

If you still encounter the issue, just as suggested in the comment ensure you are in production.
Finally if you are still having the same issues (which by now normally should not exist after setting those fields to false) then you might be interested in checking this issue (date back since 2015).
The fix from one of the comment says (verbatim):
app(\Dingo\Api\Exception\Handler::class)->register(function (\Exception $exception) {
    if (!env('API_DEBUG') && !$exception instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
        // Whatever other handling you want goes here..

        // Mimic the normal API response with a different message
        return \Response::make([
            'message'     => 'Internal server error',
            'status_code' => 500,
        ], 500);
    }
});

Beware that I didnt test this myself.
Answer: If you haven't already done yet, publish dingo config file
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

Then, open config/api.php and edit the errorFormat value to whatever message you want.
Replace :message with a generic message
Comment: I really wanted this to work, but when I fill out `:message` with 'Error occurred' it shows correctly exactly what I am looking for, but unfortunately it overwrites `message` that I set in custom error handling in controllers like this `return $this->response->array(['error' => true, 'message' => 'Duplicate entry, try again.'])->setStatusCode(300);` I never see duplicate entry error if I hard code `Error Occurred` as `:message`. Shouldn't the duplicate entry error overwrite the `Error Occurred` and `Error Occurred` overwrite errors we want transformed for the client?


How do I create a dictionary with keys from a list and values separate empty lists?

Question: Building from How do I create a dictionary with keys from a list and values defaulting to (say) zero?
and especially this answer:
How do I create a dictionary with keys from a list and values separate empty lists?
(Where, later on, I'll be able to append elements)
Answer: Use dictionary comprehension,
{item: [] for item in my_list}

You are simply iterating the list and creating a new list for every key.
Alternatively, you can think about using collections.defaultdict, like this
from collections import defaultdict
d = defaultdict(list)
for item in my_list:
    d[item].append(whatever_value)

Here, the function object which we pass to defaultdict is the main thing. It will be called to get a value if the key doesn't exist in the dictionary.
Comment: Thanks a lot, you answered beyond my narrow question, addressing the complete problem!
Answer: This is simple and easy implementation , It is self explaining , we iterate over all the elements in the list and create a unique entry in the dictionary for each value and initialize it with an empty list
sample_list = [2,5,4,6,7]
sample_dict = {}
for i in sample_list:
    sample_dict[i] = []

Answer: By normal method:
>>> l = ["a", "b", "c"]
>>> d = {}
>>> for i in l:
...   d[i] = []
...
>>> d
{'a': [], 'c': [], 'b': []}
>>>

By using collections module
>>> l = ["a", "b", "c"]
>>> import collections
>>> d = collections.defaultdict(list)
>>> for i in l:
...   d[i]
...
[]
[]
[]
>>> d
defaultdict(<type 'list'>, {'a': [], 'c': [], 'b': []})


How many Premier League teams will play in the 17-18 Champions League?

Question: If Manchester United wins the Europa League, and Leicester City wins the Champions League (everything is possible), and both do not fall into the top 4 in the Premier League, then how many Premier League teams will play in the 2017-2018 Champions League?
Comment: Possible duplicate of https://sports.stackexchange.com/q/26087/3671
Answer: No more than five clubs can enter the UEFA Champions League from one national association.

Regarding the top three associations (currently Spain, Germany and
  England): if two clubs from one of these countries win the UEFA
  Champions League and UEFA Europa League, and neither finish their
  domestic league in a position that qualifies them for the UEFA
  Champions League, the following will happen:
– The club that won the UEFA Champions League will go straight into
  the group stage.
– The UEFA Europa League winners will go into the UEFA Champions
  League play-offs.
– The club that had qualified for a UEFA Champions League play-off
  spot via their domestic league competition (i.e. finished fourth)
  transfer to the UEFA Europa League.

Reference: Uefa
Comment: it is annoyance  to fourth team
Comment: Yeah, you have to  finish in top 3 to secure a place in UCL.


Could not check value within two column using MySQL query

Question: I am facing one issue. I need to check value which should present within two column values using PHP and MySQL. I am explaining my table below.

    id      zip_from               zip_to

     1        751001                751030

db_postcode:
$post_code='751010';
$sql="select * from db_postcode where zip_from >='".$post_code."' and zip_to='".$post_code."'";
$sqlpin=mysqli_query($conn,$sql);
if (mysqli_num_rows($sqlpin) > 0) {
    $data=array("status"=>"Success","msg"=>"Product is available for this postcode");
}else{
    $data=array("status"=>"Failed","msg"=>"Product is not available for this postcode");
}
echo json_encode($data);

Here I am getting the message {"status":"Failed","msg":"Product is not available for this postcode"}  which is wrong because code 751010 is present within 751001-751030. Here I need to check the user given value should be present within that two column.
Comment: You have `zip_to = `, but i think you need `zip_to <=`.
Comment: Can you share the exact column definitions? Is `zip_from` a `INT` column? And why do you think that this is related to PHP?
Comment: @NicoHaase : both column is `varchar`.
Comment: @Cynical : No as per you also not working.
Comment: Mind the SQL injection
Comment: As @Cynical writes - Right now you are checking for a postnumber that is above 751001 but excactly 751030. meaning that only 751030 will work
Comment: also - since it is varchars, I am not sure that you can use it as pure numbers? why are they not intergers? if sql considers them as strings, can you use a numeric value to check it?
Comment: I guess you can since `'BALL' < 'water'` will return true
Comment: You have to cast the column and then compare the values like here https://stackoverflow.com/a/19654296/7296317
Answer: Your compare is written the wrong way around, what you want is to check that $post_code is between zip_from and zip_to:
$sql="select * from db_postcode where '$post_code' between zip_from and zip_to";

Note that this will only work if all zip_from, zip_to and $post_code values are the same length, otherwise you will run into issues that in a string compare, 2 > 100000. If they are not the same length, you should cast them to integer to compare them.
Answer: Well, Your query would should be this:
$sql="select * from db_postcode where ".$post_code." BETWEEN zip_from and zip_to";

Comment: I have already tried this but same issue. Let me to remind you both column has datatype varchar.
Comment: Please explain **why** it should be like this and which exact changes were needed


click on element with same class

Question: I know it might sound stupid but for some reason I`m having some weird problem.
so, I have a code in js which generate a table with a buttons I gave all buttons same class.
when I try to click on them and use jquery function to console.log something nothing happens.
$.each(data,function(i, d){
    $('#myTable tbody').append(`

            ${d.Date}
            ${d.Name}
            ${d.Score}
            <button class='graphXY' data=${d.id}>View</button>

`);
});

its inside ajax and the table generates good and each button gets class and data good.
now when I try to do
$(".graphXY").click(function(){
    console.log("hit");
})

basically nothing happens and for some reason I cant find the reason.
Comment: You need to attach the click function to an element that existed on DOM load - something like `$(#myTable').on('click', '.graphXY', function() {...`
Comment: You need to perform `event delegation`. Look that up. This has been answered thousands of times.
Comment: Tnx alot @IsmailFarooq
Answer: The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist.
It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().
$("#myTable").on("click", ".graphXY", function(){
    console.log("hit");
})

click on element with same class


iOS vs Android Location tracking with precision and battery consumption

Question: I tried an Android device with GPS module OFF. I was driving in a car and horizontal accuracy was from 50-300m which is accuracy that is OK with me. (triangulation + wi-fi)
I am trying to build an iPhone application which uses as little battery as possible (application will be on the hole day).
Thats why I would not like to use GPS. Will hundredMeters accuracy use GPS or it works with triangulation?
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;

I also wonder how much is distanceFilter important to battery consumption? Is there a huge difference if it is set to 300m or 1000m?
Answer:
I am trying to build an iPhone application which uses as little battery as possible (application will be on the [whole] day).

Then you should be leveraging the Significant-Change Location Service if at all possible, as this is the most power efficient method of getting long-term location data in your application.  This is also the most effective way to get location update into your app while it is in the background (something you might have taken for granted on Android).
Also from the iOS Core Location docs:

Use lower-resolution values for the desired accuracy unless doing so would impair your app. ...remember that specifying a value of kCLLocationAccuracyThreeKilometers does not prevent the location service from returning better data. Most of the time, Core Location can return location data with an accuracy within a hundred meters or so using Wi-FI and cellular signals.

It is likely based on this that the constant kCLLocationAccuracyHundredMeters does not typically require the GPS to be turned on, but you might reduce your requested accuracy to ensure the GPS if left off, and iOS will likely still deliver to you data that is accurate within the range you prefer.

I also wonder how much is distanceFilter important to battery consumption?

This filter is involved more in how often updates are actually delivered to your app, the accuracy deals more with the hardware that will be required to get the fix.  A filter will reduce how often radios are turned on, but this is a larger power saving tool when GPS is involved.  If you are using the Significant-Change service, however, this part of the question is irrelevant.


If $\alpha$ is an increasing function of bounded variation, why can't it have uncountable number of discontinuities?

Question: In book 《A Course in Abstract Analysis》,there is a proposition stated:
If $\alpha:[a,b] \to \mathbb{R}$ is an increasing function of bounded variation, it can't have uncountable number of discontinuities
the author argues as follow:
If $\alpha$ is discontinous at the points ${c_n}$, then the sum of the jumps $\Sigma_n[\alpha(c_n+)-\alpha(c_n-)]$ is at most $\alpha(b)-\alpha(a)$.If it has uncountable number of discontinuities, then we can find an $\varepsilon >0$ and an infinite sequence of discontinuities ${c_n}$ such that $\alpha(c_n+)-\alpha(c_n-)\geq \varepsilon$ (Why?) . In the light of what we just pointed out, this would imply that $\alpha(b)-\alpha(a)=\infty$ which is nonsense.
I know that a increasing function should only have countable discontinuities for these discontinuity points should bijectively correspond to a subset of $\mathbb{Q}$ which is obvious countable. But I really can't grasp why "If it has uncountable number of discontinuities, then we can find an $\varepsilon >0$ and an infinite sequence of discontinuities ${c_n}$ such that $\alpha(c_n+)-\alpha(c_n-)\geq \varepsilon$ ". Why there should be an $\varepsilon >0$ ? Any help and hints will be appreciated!
Best regards!
Comment: Look at the lengths of the jumps and the set of accumulation points of those lengths. If the only accumulation point of the lengths were $0$, then the set of lengths of jumps would be countable. Therefore, some positive number is an accumulation points of the lengths of the jumps. Take $\epsilon>0$ smaller than that positive accumulation point.
Comment: Ultimately, this is because $0$ has a countable [neighborhood basis](https://en.wikipedia.org/wiki/Neighbourhood_system#Neighbourhood_basis). For example, $(-1/n,1/n)$.
Comment: Does this answer your question? [How to show that a set of discontinuous points of an increasing function is at most countable](https://math.stackexchange.com/questions/84870/how-to-show-that-a-set-of-discontinuous-points-of-an-increasing-function-is-at-m)
Comment: [A function of bounded variation can be expressed as a difference of two increasing functions](https://math.stackexchange.com/q/141338/977780)
Comment: @SouravGhosh Thanks! My question actually lies in why there should always be an $\varepsilon > 0$,which has already been answered below!
Answer: This is an odd statement to make, because all increasing functions are of bounded variation on a closed interval $[a,b].$
But the crux of the step you are having a problem with is:
Theorem: Let $C$ be an uncountable set, and $f:C\to\mathbb R^+$ be any function. Then there exists an $n$ such that for infinitely many $c\in C,$ $f(c)>\frac1n.$
Proof: If it is not true, let  $$C_{n}=\left\{c\in C\mid \frac{1}{n}<f(c)\right\}$$ Each $C_n$ must be finite. But then $C=\bigcup_{n=1}^{\infty} C_n$ is the countable union of finite sets, so it must be countable.

You only need an infinite set in this proof, but there actually must be an $n$ such that $\{c\in C\mid f(c)>1/n\}$ is uncountable, since the countable union of countable sets is countable.

There is nothing magic about $\frac1n$ in this proof - we could have taken any sequence $\epsilon_n$ of positive reals such that $\liminf_{n\to\infty} \epsilon_n=0.$ It just happens that $\frac1n$ is simple.

You can generalize the book's proof for any function of bounded variation, but rather than left- and right- limits, you take:
$$f_+(x)=\limsup_{x'\to x} f(x')\\f_-(x)=\liminf_{x'\to x} f(x').$$
When $f$ is increasing, you can show these are the right and left limits, respectively. We can use the bounded variation property to show $f_+,f_-$ always take finite values, and we easily get $f_+(x)\geq f_-(x)$ with equality at exactly the points of continuity of $x.$
Then we can show, if $f_v(x)=f_{+}(x)-f_{-}(x)$ then for any finite subset $a\leq c_1<\cdots<c_k\leq b$ that $\sum f_v(c_i)$ is less than or equal to the total variance. That takes a little work, but it is not hard.
But it is much easier to prove:

Every function of bounded variation is the difference on monotonic increasing functions, and
All increasing functions have at most countably many discontinuities.
Comment: Okay, edited to answer the real question. @Medo
Comment: A monotonic function can have at most countable many discontinuities. So do we even need bounded variation if $\alpha$ is increasing. The question should be edited.
Comment: Nice answer. Especially the remark that such sets would be uncountable and not just infinite. +1


Why json output so small?

Question: This output should be way longer than it is in here.
I start with a GET request, I parse a JSON list and extract the id, which I then call on the second function, that will give me a second ID which then I will use to call on the 3rd function. But, I am only getting one entry whereas I should be getting way more entries.
The code is the following:
from requests.auth import HTTPBasicAuth
import requests
import json
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def countries():
    data = requests.get("https://localhost:8543/api/netim/v1/countries/", verify=False, auth=HTTPBasicAuth("admin", "admin"))
    rep = data.json()
    return [elem.get("id","") for elem in rep['items']]

def regions():
    for c in countries():
        url = requests.get("https://localhost:8543/api/netim/v1/countries/{}/regions".format(c), verify=False, auth=HTTPBasicAuth("admin", "admin"))
        response = url.json()
        return [cid.get("id","") for cid in response['items']]

def city():
    for r in regions():
        api = requests.get("https://localhost:8543/api/netim/v1/regions/{}/cities".format(r), verify=False, auth=HTTPBasicAuth("admin", "admin"))
        resolt = api.json()
        return(json.dumps([{"name":r.get("name",""),"id":r.get("id", "")} for r in resolt['items']], indent=4))
city()

print(city())

The output is the following :
[
    {
        "name": "Herat",
        "id": "AF~HER~Herat"
    }
]

I should have a huge list, so I am not sure what am I missing?
Comment: you `return` in the first iteration of the loop
Comment: Only the first item returned by `countries()` actually gets processed in `regions()`: you get the response for that one, and then `return`, thus ending the function.  Likewise, `city()` only processes the first item from `regions()`, and then returns.
Comment: Sounds more like a server side issue than a client side one
Comment: @Macattack Thank, i am not sure i understand ? I am not a big programmer so could you clarify please ?
Comment: @jasonharper Thanks Jason, but if i print the result of hte second function i do indeed get all the regions from all the countries. so why isnt the function passing all the id's to the third one ?
Answer: You need to go through all the iterations of your loop and collect the results, then jsonify the and return them.
data = []
for r in regions():
    api = requests.get("https://localhost:8543/api/netim/v1/regions/{}/cities".format(r), verify=False, auth=HTTPBasicAuth("admin", "admin"))
    resolt = api.json()
    data.extend([{"name":r.get("name",""),"id":r.get("id", "")} for r in resolt['items']])
return json.dumps(data, indent=4)

This would be a fix for city() but you have the same problem in all your functions. return immediately exits the function and does not do anything else, effectively all your for loops are doing 1 iteration.
I'll update my example here to give you a better idea what's occurring.
Your functions are basically this:
def test_fn():
    for i in [1,2,3,4]:
        return i
# output:
1
# We never see 2 or 3 or 4 because we return before looping on them.

What you want:
def test_fn():
    results = []
    for i in [1,2,3,4]:
        results.append(i)
    return results
# output
[1,2,3,4]

It seems like you understand that the for loop is going to take some action once for each element in the list. What you're not understanding is that return ends the function NOW. No more for loop, no more actions, and in your code, you immediately return inside the for loop, stopping any further action.
Comment: @AlexandreAmaralBednell i added more examples, let me know if you don't understand
Comment: Thanks, i understand, but how can i store the above fuctions? i am not sure i understand how to just sore the values i am looking for ?

Why json output so small?


If $y''+p(x)y'+q(x)y=0$ and two solutions have null second-derivative, then the coefficients are both zero

Question: I have the following differential equation:
$$ y'' + p(x) y' + q(x) y = 0, \quad x\in(a,b) $$
such that $y_1$ and $y_2$ are both linearly independent solutions and $p$ and $q$ are continuous. I would like to prove that if $y_i''(x_0) = 0$, $i=1,2$ for some $x_0=0$, then necessarily, $p(x_0)=q(x_0) = 0$. However, I'm dealing with some issues. First, the fact that $y_i(x_0)''= 0$ means that
$$ p(x_0)[y_2'(x_0)-y_1'(x_0)] + q(x_0)[y_2(x_0)-y_1(x_0)] = 0 $$
and $y_3 = y_2-y_1 \neq 0$ also satisfies, for $x\in(a,b)$:
$$ y_3'' + p(x) y_3' + q(x) y_3 = 0 $$
If I suppose that $p(x_0)=0\neq q(x_0)$, $y_2(x_0) = y_1(x_0)$, which is possible, and also if $p(x_0)\neq 0 = q(x_0)$ or if $p(x_0)\neq 0\neq q(x_0)$, so I'm a little bit lost since I can't find out the behaviour of the solution around $x_0$. I would appreciate some hint. Thanks
Answer: You can use the Wronskian. Let's consider the following matrix :
$$S(x)=\begin{pmatrix} y_1(x) & y_2(x) \\ y'_1(x) & y'_2(x) \end{pmatrix}$$
Define the Wronskian $W(x)=\det S(x)=y_1(x)y'_2(x)-y_2(x)y'_1(x)$. Then, you have :
$$\begin{array}{rcl}
W'(x) & = & y_1(x)y''_2(x)+y'_1(x)y'_2(x)-y_2(x)y''_1(x)-y'_2(x)y'_1(x) \\
      & = & y_1(x)y''_2(x) - y_2(x)y''_1(x) \\
      & = & -y_1(x)\left(p(x)y'_2(x)+q(x)y_2(x)\right)+y_2(x)\left(p(x)y'_1(x)+q(x)y_1(x)\right) \\
      & = & p(x) \left(y_2(x)y'_1(x)-y_1(x)y'_2(x)\right)
\end{array}$$
So, in the end, you have :
$$W'(x)=-p(x)W(x)$$
This differential equation is solved by $W(x)=W(x_1) \exp \left( \int_{x_1}^x p(y) \text{d}y \right)$, for any $x_1$.
Now the linear independance of $y_1$ and $y_2$ means that there exists $x_1$ such that $W(x_1)\neq 0$. Thus, considering the expression of $W$, we have $W(x) \neq 0$, for all $x$.
Now to conclude, define $V(x)=\left( q(x) \; \; p(x) \right)$ and observe that the differential equation can be written :
$$V(x)S(x)=-\left( y''_1(x) \; \; y''_2(x) \right)$$
Thus, you have $V(x_0)S(x_0)=0$. Yet, $W(x_0)=\det S(x_0)\neq 0$ so $S(x_0)$ is invertible, which means that $V(x_0)=0$. QED


Why is $W_n(k)$ the unique flat lifting of a perfect field $k$ over $\mathbf{Z}/p^n$?

Question: Let $k$ be a perfect field of characteristic $p>0$ and denote by $W_n(k)$ the ring of Witt vectors over $k$ of length $n$. In their article on the decomposition of the de Rham complex, Deligne and Illusie claim that $W_n(k)$ is the unique flat lifting of $k$ over $\mathbf{Z}/p^n$ (1.3). I know how to justify that $W_n(k)$ satisfies these properties, but it is not clear to me why it should be (up to isomorphism) the only one satisfying them. Translating this into commutative algebra, we need to prove that if $A$ is a flat $\mathbf{Z}/p^n$-algebra such that its reduction modulo $p$ is isomorphic to $k$, then we have $A \cong W_n(k)$. Could someone shed a light on this?
Answer: $\def\ZZ{\mathbb{Z}}$You can almost find a detailed proof in Rabinoff's notes on Witt vectors. Specifically, Rabinoff proves that, if $k$ is a perfect field of char $p$, then there is a unique $\ZZ_p$-algebra $R$ such that $R$ is complete and Hausdorff in the $p$-adic topology, $p$ is not a zero divisor and $R/pR \cong k$. I will sketch how to adapt this to work with $\ZZ/p^n$ rather than the $p$-adics. This is "folklore" that lots of people knew before Rabinoff, but he is the best reference I know for it.
Let $A$ and $B$ be two $\ZZ/p^n$ algebras, which are flat over $\ZZ/p^n$ and have $A/pA \cong B/pB \cong k$. For $x \in k$, choose a sequence $a_0$, $a_1$, $a_2$, … of elements of $A$ with $a_i^{p^i} \equiv x \bmod pA$; such a sequence exists since $k$ is perfect. Then $a_i^{p^i}$ is eventually constant modulo $p^n$. (Proof: We have $a_{i} \equiv a_{i+1}^p \bmod p A$, so $a_i^{p^i} \equiv a_{i+1}^{p^{i+1}} \bmod p^{i+1} A$ by Rabinoff's Lemma 1.4.) Define $\alpha(x)$ to be the eventual limit of $a_i^{p^i}$ in $A$, and similarly define $\beta(x)$ to be the analogous limit in $B$. These are the analogues of Teichmuller lifts in our setting.
Then $\{ \alpha(x) \}_{x \in k}$ are a set of representatives for $A/pA$, and $p^n=0$ in $A$, so any element of $A$ can be written as $\sum_{i=0}^{n-1} \alpha(x_i) p^{i}$ for some sequence $x_i$. Flatness shows that this expression is unique. So we have a bijection $A \longleftrightarrow k^n$ by $\sum_{i=0}^{n-1} \alpha(x_i) p^{i} \longleftrightarrow (x_0, x_1, \ldots, x_{n-1})$. We similarly have a bijection $k^n \longleftrightarrow B$. We need to show that the composite is an isomorphism of rings. I.e. we need to show that
$$\sum_{i=0}^{n-1} \alpha(x_i) p^i + \sum_{i=0}^{n-1} \alpha(y_i) p^i = \sum_{i=0}^{n-1} \alpha(s_i) p^i \ \Longleftrightarrow \ \sum_{i=0}^{n-1} \beta(x_i) p^i + \sum_{i=0}^{n-1} \beta(y_i) p^i = \sum_{i=0}^{n-1} \beta(s_i) p^i$$
and
$$\left( \sum_{i=0}^{n-1} \alpha(x_i) p^i \right) \left( \sum_{i=0}^{n-1} \alpha(y_i) p^i \right) = \sum_{i=0}^{n-1} \alpha(z_i) p^i \ \Longleftrightarrow \ \left( \sum_{i=0}^{n-1} \beta(x_i) p^i \right) \left( \sum_{i=0}^{n-1} \beta(y_i) p^i \right) = \sum_{i=0}^{n-1} \beta(z_i) p^i$$
The point is that both of sides of the equivalence these are equivalent to $s_i$ (respectively $z_i$) being given by certain universal polynomials in the $x_i$ and $y_i$; see Theorem 1.5 in Rabinoff.
Comment: Thank you very, very much for this well-thought-out answer. I was already aware of Rabinoff's notes and of your [recommendation](http://sbseminar.wordpress.com/2009/05/06/rabinoff-on-witt-vectors/) about them, but, due to my lack of time, I opted to just read (some parts of) Serre's local fields. Sometime in the future I'll try to read them. Please give me some time to understand your explanation before accepting your answer.
Comment: Am I missing something obvious or is it possible to prove the same result stated in my initial post assuming only that $k$ is a *perfect domain*? Also, is there some kind of structure theorem for such rings?
Comment: Assuming that perfect domain means integral domain where $p=0$ and $x \mapsto x^p$ is bijective, I think you are right. I can't think of any interesting examples that aren't fields, though.
Comment: Thanks for the attention. Since there are other kind of rings called perfect, I should've made that clear. But you guessed it right. By perfect domain I meant an integral domain of characteristic $p>0$ such that the Frobenius endomorphism is an automorphism.


Rails Generate Model - Changing Model Name after DB:migrate

Question: I created a model using:
rails generate model SavingsItem
I then ran rake db:migrate.
Now, I want to rename the model to SavingsProduct
I did a rake db:rollback and then went directly into my migration file and change the model name and table name. However, when I run rake db:migrate again, it creates the right table name in my database, but creates savings_item.rb still.
Why does this happen?
Here is my migration file:
class CreateSavingsProducts < ActiveRecord::Migration
  def change
    create_table :savings_products do |t|
      t.string :name, :limit => 50
      t.string :description, :limit => 200
      t.decimal :price, :precision => 10, :scale => 2
      t.string :buy_url, :limit => 200
      t.string :image_url, :limit => 200
      t.integer :image_width, :limit => 11
      t.integer :image_height, :limit => 11
      t.timestamps
    end
  end
end

Answer: I'm not sure if there's a way to rename a model but you can simply use destroy to get rid off a mistakenly named model. like this: rails destroy model model_name
destroy deletes all files automatically generated by generate command.
Answer:
when I run rake db:migrate again, it creates the right table name in
  my database, but creates savings_item.rb

Migrations only alter the database; they don't create or alter any files (except schema.rb). Generators are what create and alter files, including migration files.
If you already have the model generated, you can simply change its name manually. Change class SavingsItem to class SavingsProduct and rename the file from savings_item.rb to savings_product.rb.
Comment: No, you missed the point, running the migration will not create any files. When you generate the model it creates multiple files, one of which is the migration - so it's the generate model command that you ran that is to blame, not the migration. Just make sure you modify the files before you push it to whatever means you're using to collaborate, and you won't have to worry.
Comment: How do I alter my generator? I did that as a quick fix, but if I'm collaborating with others, this means everyone who runs the migration would have to do this as well.
Comment: (Note: the above comment is assuming you haven't explicitly written File IO commands in the migration that would affect the file system/create files, of course.)