The type initializer threw an exception for assemblies in 64 bit OS

Question: I am using Sage Assemblies in my Visual Studio 2008 project. But when the project is deployed in a 64 bit OS, it crashes with type initializer exception. I tried setting the Copy Local = false so that assemblies from the target PC's GAC would be used.
For the record, I also navigated to the GAC directory of the target PC and the Processor Architecture = x86 for the assemblies for which I am getting exception. Also running corsflag shows the assemblies are 32 bit.
Does that the mean the assemblies have to be MSIL or x64 to work in 64 bit OS?
Answer: So, I got my answers and it is not required for assemblies to be x64 or MSIL to work on 64 bit OSs. All I had to do was build my setup project against the architecture of the assemblies which was 32 bit.


Identifying the residue field of $\overline{\mathbb{Q}}_p$ with $\overline{\mathbb{F}}_p$

Question: Could anyone epxlain to me how to identify the residue field of $\overline{\mathbb{Q}}_p$ with $\overline{\mathbb{F}}_p$ ? I am basically trying to go from a $p$-adic galois representation of $G_\mathbb{Q}$ to a representation of the type Serre uses...so my ultimate goal is to obtain a representation
$$
\rho: \operatorname{Gal}(\overline{\mathbb{Q}}/\mathbb{Q}) \rightarrow \operatorname{GL}_2(\overline{\mathbb{F}}_p)
$$
from a more natural one like $\rho: \operatorname{Gal}(\overline{\mathbb{Q}}/\mathbb{Q}) \rightarrow \operatorname{GL}_2(\mathbb{Q}_p)$.
I was initially looking for an argument involving choosing a lattice in $V = \overline{\mathbb{Q}}_p^2$, but since then I read (and understood the proof that) the residue field of $\overline{\mathbb{Q}}_p$ is an algebraic closure of $\mathbb{F}_p$. Would that be an easier way to solve my problem?
Thank you very much !
Comment: @user62423: Dear user, You may want to learn about the theory of unramified extensions in more detail.  For every finite extension $k$ of $\mathbb F_p$, there is a corresponding uniquely determined unramified extension of $\mathbb Q_p$ with residue field $k$ (whose ring of integers is often denoted $W(k)$, and called the ring of Witt vectors of $k$).  This idea/construction is fundamental in the theory of $p$-adic Galois representations for lots of different reasons, so it's good to get it straight.  Best wishes,
Comment: I didn't understand, residue field of $\overline{\mathbb{Q}}_p$with respect to what? Recall this field is not complete with respect to the $p$-adic valuation.
Comment: @ViniciusM. For the residue field we take the valuation subring modulo its unique maximal ideal. Why would completeness be necessary?
Comment: @anon you're right, I misunderstood the concepts. tks
Comment: Ultimately I would like to understand how to get a representation $\rho:G_\mathbb{Q} \rightarrow \operatorname{GL}_2(\overline{\mathbb{F}}_p)$. If I am correct that identifying those two fields will help me then yes :) However if you have a clever way to construct $\rho:G_\mathbb{Q} \rightarrow \operatorname{GL}_2(\overline{\mathbb{F}}_p)$ I would be extremely happy!
Comment: Dear user, Keenan has answered your question below, but I'm curious --- which statement were you unsure about: that the residue field fills out all of $\overline{\mathbb F}_p,$ or that it might be bigger?  Regards,
Comment: @MattE Well intuitively I would have been unsure whether the residue field fills out $\overline{\mathbb{F}}_p$. I see how the residue field of $\overline{\mathbb{Q}}_p$ is an algebraic extension of $\mathbb{F}_p$ but it turns out that the other "implication" is not so much harder.
Answer: The residue field of $\overline{\mathbf{Q}}_p$ is algebraically closed because every monic polynomial over the ring of integers $\overline{\mathbf{Z}}_p$ of $\overline{\mathbf{Q}}_p$ has a root in $\overline{\mathbf{Z}}_p$, and it is algebraic over $\mathbf{F}_p$ because every element in the ring of integers over $\overline{\mathbf{Z}}_p$ is integral over $\mathbf{Z}_p$. So the residue field of $\overline{\mathbf{Q}}_p$ is an algebraic closure of $\mathbf{F}_p$. It doesn't completely make sense to say that you want to "identify" the residue field with $\overline{\mathbf{F}}_p$, because there isn't really one algebraic closure of $\mathbf{F}_p$; any two are isomorphic, but non-canonically.
Regarding how to take a Galois representation and reduce it modulo $p$, you have to prove that $G_\mathbf{Q}$ preserves an $\overline{\mathbf{Z}}_p$-lattice in a finite-dimensional $\overline{\mathbf{Q}}_p$-vector space on which it acts continuously. This is easier to see I guess for a representation on a finite-dimensional vector space $V$ over a finite extension $L$ of $\mathbf{Q}_p$. Start with any $\mathscr{O}_L$-lattice $T$ in $V$ (i.e. a finite $\mathscr{O}_L$-module that spans $V$ over $L$) and let $\Gamma$ be its stablizer in $\mathrm{GL}_n(L)$. This is an open subgroup of $\mathrm{GL}_n(L)$, so the inverse image $\Gamma^\prime$ is an open subgroup of $G_\mathbf{Q}$. Now take the sum of the translates of $T$ by the finitely many coset representatives for $G_\mathbf{Q}/\Gamma^\prime$. This is still a lattice, and it is $G_\mathbf{Q}$-stable by construction.
What this means concretely is that you can conjugate $\mathrm{GL}_n(L)$ so that the image of $G_\mathbf{Q}$ is contained in $\mathrm{GL}_n(\mathscr{O}_L)$. Now you apply the natural reduction map $\mathrm{GL}_n(\mathscr{O}_L)\rightarrow\mathrm{GL}_n(\mathbf{F})$, where $\mathbf{F}$ is the residue field of $L$.
The reason you don't have to really think about representations over $\overline{\mathbf{Q}}_p$ when you do this is that the image of any continuous homomorphism $G_\mathbf{Q}\rightarrow\mathrm{GL}_n(\overline{\mathbf{Q}}_p)$ has image in $\mathrm{GL}_n(L)$ for some $L$ finite over $\mathbf{Q}_p$. This is a consequence of the Baire category theorem and works with $G_\mathbf{Q}$ replaced by any profinite group. I guess maybe the argument I gave above for the existence of a stable lattice still works with $\overline{\mathbf{Q}}_p$, but I worry about whether a sum of translates of a finite free $\overline{\mathbf{Z}}_p$-module spanning a finite-dimensional $\overline{\mathbf{Q}}_p$-vector space will still be free...anyway, you don't need it because you can always descend to a finite extension of $\mathbf{Q}_p$.
Comment: Amazing answer ! Thank you very much for taking the time to write that, it clears up more than my original question !


Is google or tools available for jdk 8?

Question: I have to use JDK 8 for a project and want to give google OR Tools a try, which I included as jar library. When I ran the program it said, that my jdk is to old. Is google or tools also available for jdk 8?
Answer: well you can rebuild it from source with any jdk.
Just setup your JAVA_HOME env
ps: personnaly I use open jdk 8

Is google or tools available for jdk 8?


Perplexity of the following example

Question: This example is from Stanford's lecture about Language Models. A system has to recognise

An operator ($P=\frac{1}{4}$)
Sales ($P=\frac{1}{4}$)
Technical Support ($P=\frac{1}{4}$)
30000 Names ($P=\frac{1}{120,000}$)

The answer is given as 53. However, when I calculate it, it turns out to be around 56. This is how I did it: $$Perplexity \ = \ (4\times 4 \times 4 \times 120000)^{\frac {1}{4}}$$.
What am I doing wrong?
It's on page 34 here: https://web.stanford.edu/class/cs124/lec/languagemodeling.pdf
Answer: I think the correct calculation should be
$$(4^{1/4} \times 4^{1/4} \times 4^{1/4}) \times \left((120000)^{1/120000} \right)^{30000}$$
which is the product over all $30003$ possible outcomes of $(1/p)^{p}$ where $p$ is the probability of that outcome. I get $52.6$.
Answer: First understand that what is the meaning of the perplexity formula
$Perplexity = P(w_1,w_2,...,w_N)^{\frac{-1}{N}}$
Where $N$ is the number of words in the testing corpus. Assume that you have developed a language model, where each word has some probability of occurring. The given problem specifically gives you three words and their probabilities. Plus it states that among $N$ there are 30,000 names.
Now if you look at probabilities, you will see that probability of the word "Operator" is 1/4. As it is independent of context, it is safe to assume that whatever your language model outputs, 25% of the words are "Operator" only. Similarly, 25% are "Sales" and 25% are "Technical Support". Till now you know 75% of the words your model is going to output, remaining is 25%.
Now, remember the question said that the model recognizes 30,000 names as well. These names can be fit into the remaining 25% of your testing set i.e. 25% of output = 30,000.Hence, total words in output = 4*30K = 120K = $N$
Therefore your model output will look something like this: $\{ ``Operator"\times30K,\ ``Sales"\times30K,\ ``Tech Support"\times30K,\ 30K\ names \}$
Since our probabilities are not dependent on the context, the order doesn't matter.
Now if we go back to our Perplexity formula and put down the values, we get the following answer:
\begin{equation*}
Perplexity = \left( {P(Operator)}^{30K}\times{P(Sales)}^{30K}\times{P(TechSupport)}^{30K}\times{P(name)}^{30K} \right)^{\frac{-1}{120K}}
\end{equation*}
\begin{equation*}
 = \left( \frac{1}{4}^{30K}\times\frac{1}{4}^{30K}\times\frac{1}{4}^{30K}\times\frac{1}{120K}^{30K} \right)^{\frac{-1}{120K}} = 52.6
\end{equation*}

Perplexity of the following example


Conexão alternativa para WebService

Question: boa tarde!
Tenho a seguinte função:
function API($conteudoAEnviar) {
    try{
        $cabecalho = array(
                'Content-Type: application/json',
                'Authorization: Basic ' . base64_encode(TOTVS_JSON_USER_SECRET . ':' . TOTVS_JSON_PASSWORD_SECRET)
            );

        $ch = curl_init(TOTVS_URL_REST);

            $tpRequisicao = 'POST';

        if ($tpRequisicao == 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);

            curl_setopt($ch, CURLOPT_POSTFIELDS, $conteudoAEnviar);
        }

        if (!empty($cabecalho)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $cabecalho);
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $resposta = curl_exec($ch);

        curl_close($ch);
    }catch(Exception $e){
        return $e->getMessage();
    }
    return $resposta;
}

Sendo assim, preciso criar uma forma para quando a $resposta apresentar algum erro ou falha, seja de conexão ou qualquer coisa, que eu possa alterar para uma conexão local ao banco de dados, poderiam me dar uma luz a esse respeito, não encontrei nada nas pesquisas.
Existe alguma função que verifica se a conexão da foi bem sucedida?
Comment: Marcos, favor não colocar RESOLVIDO no titulo, não é bem assim que o site funciona. Se encontrou a solução, poste como resposta no campo abaixo e marque como aceito. Visite nosso **[tour]** para saber como funciona.
Comment: Marcos, em um sistema de perguntas e respostas, como é o [pt.so], existe uma clara diferença entre pergunta e respostas: uma é pergunta, outra é resposta. Dito isso, te aconselho a publicar **sempre** a solução como resposta, não editando a pergunta.
Comment: A função `curl_exec` retorna falso em caso de falha, com isso você pode utilizar `curl_error` e `curl_errno` para verificar o que aconteceu.
Answer: Faz a verificação com curl_error($ch), caso haja falha, lança uma exceção throw new Exception($error_msg, 1), trata a exceção, tentando uma nova requisição: ficaria algo como:
function API($conteudoAEnviar) {
        try {
            $cabecalho = array(
                'Content-Type: application/json',
                'Authorization: Basic ' . base64_encode(TOTVS_JSON_USER_SECRET . ':' . TOTVS_JSON_PASSWORD_SECRET)
            );

            $ch = curl_init(TOTVS_URL_REST);
            $tpRequisicao = 'POST';

            if ($tpRequisicao == 'POST') {
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $conteudoAEnviar);
            }

            if (!empty($cabecalho)) {
                curl_setopt($ch, CURLOPT_HTTPHEADER, $cabecalho);
            }

            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $resposta = curl_exec($ch);

            if (curl_error($ch)) {
                $error_msg = curl_error($ch);
                throw new Exception($error_msg, 1);
            }

            curl_close($ch);

        } catch (Exception $e) {

            try {
                echo "Inplementar aqui a outra chamada";
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }
}

Comment: Obrigado lstonon.

Conexão alternativa para WebService


Postgresql nested SELECT

Question: I'm learning postgresql and I can't figure out how to write this nested query or if it's even possible.
Table -> Points: pid | val

Table -> Grid: gid | max_val | min_val

Return I want: pid | gid | val

This is how I see it in my head
for p in (SELECT * FROM Points)
    SELECT gid FROM Grid AS g WHERE p.val < g.max_val AND p.val > g.min_val

Is this possible? If so can someone point me in the right direction?
Answer: I wouldn't think you need a nested query, just a join.  Does something like this give what you need?
SELECT
  P.pid,
  G.gid,
  P.val
FROM
  Grid          AS G
INNER JOIN
  Points        AS P
    ON  P.val < g.max_val
    AND P.Val > g.min_val

Answer: Following query will always return point even if point's val is not in any grid range - in such case gid will be NULL:
SELECT
  p.pid,
  g.gid,
  p.val
FROM
  Points p
  LEFT JOIN Grid g ON g.min_val > p.val AND g.max_val < p.val

If there is more than one Grid with a range that will match the point's val, query will return two rows for each gid.
If you want to return only points matching any grid, just add a condition:
WHERE
  g.gid IS NOT NULL

Postgresql nested SELECT


Is it ok to use a cheap violin as a beginner?

Question: I am just about to start learning the violin. To provide some context, I am not looking to pursue it professionally and am pursuing it for recreation. However, i still want to reach an intermediate level of skill. Currently, I have no background in music.
My main concern is that I am not very well financed and would not like to invest substantial amounts of money as a beginner(however, I am completely fine with spending more money later on as I get advanced). My current budget is less than $100 which is amongst the cheapest rates for a violin.
I was wondering if starting to learn the violin on a cheaper instrument could be detrimental later on as I transition to a better crafted instrument.
Regarding research, I looked at a similar question on the site however the question was slightly different and have thus, asked it afresh.
This is my first question on the music stack exchange and please suggest any edits if required.
Thanks!
Answer: No recommendations - not from this site! A cheap full-sized violin will do you for a year or so, by when you'll have either given up, or realised it's a cheap violin. Go for it.
Cheap doesn't necessarily mean nasty. There are plenty of beginner instruments around these days. Might even pick up a pre-loved (my favourite). So, it would suffice for the time being, as you may find it's not your dream after all. Even if you had a Strad. it might be that the violin's not for you! At that point, not a lot of money badly invested. But if you do take to it, the violin itself will tell you it's time for an improvement. So get a better one then!
One potential problem with a cheap instrument can be that it has a poor sound quality. However, as long as you are satisfied with it at the beginning, you can upgrade later on as your ear develops. The key is that you feel good playing whatever instrument you buy. Purchase the instrument you like most within your budget. Perhaps you can hear someone demonstrating the instrument for you.
Comment: @Aaron - I felt it was apposite in itself to be an answer. However...
Comment: This reads as a comment. May add something about why a cheap violin is okay and why OP will outgrow it?
Comment: Well, major bonus points for using the word "apposite", but, yeah, IMO it's too thin.
Comment: @Aaron - read on... and where's me bonus points?
Comment: Putting on my editor hat ... :-) It reinforces your core point, but I think it's a really strong answer if you add something specific about *why* OP might outgrow an instrument. IMO, the key factor is the tone of the instrument, which I infer in your answer, but +1 for making it (or other factor) explicit.
Comment: @Tim Where I live, I dont have access to a violin of the renowned brands(like mendini etc.) without high shipping charges. Do you feel a violin from a lesser known brand(but still commonly bought) would be ok?
Comment: Since your profile (like too many) gives no clue at all as to where that may be, I cannot give any sensible answer. How can anyone?
Comment: @Aaron - how the heck can I do that? I don't know how enthusiastic OP is, or will be. Or how long they may persevere on their own. Or how soon they may decide that it's not worth the effort.Or if they like/dislike the tone. Or if that's their fault or the violin's.Etc., etc. Out of my hands now - someone else's turn. Any thoughts..?
Comment: @Tim I live in India and a Mendini MV300 4/4 costs over $250 on amazon India (I don't know how that is possible)...I am thinking to buy this violin- https://www.amazon.in/gp/product/B07VXJN67B/ref=ox_sc_act_title_1?smid=A14CZOWI0VEHLG&psc=1
Answer: For a while I repaired amplifiers in a music store that provided rental instruments for students. These instruments were not top of the line instruments because there is no way of knowing how well these instruments would be cared for, but literally thousands of students learned how to play on these instruments. That shows that it's a valid approach when a new student is starting their musical education. You have the option of purchasing your own instrument and then upgrading when you can afford it or you might consider signing a rental contract at your friendly neighborhood music shop until you can upgrade. It's another option.


Loading flat files /adding filename to table column

Question: I am trying to load a ton of flat files into a sql table and adding a filename column to the table.
in control flow I have 2 foreech loops grabbing the filenames and passing them to 2 variables.
this is where im having trouble in my data flow, I first have my flat file source pointing to derived column then pointing to OLE DB Destination.. in the OLE DB destination it is recognizing my filename derived column, but when I run the package it executes fine it just creates the table, it doesn't insert the flat file data or the filename from the 2 variables
Answer: Variable value changes cannot be read within the same DataFlow Task. You have to write an expression that get the Destination Table name in a Script Task or Expression Task inside the ForEach Loop container, then connect this task to the DataFlow Task. Note that you have to set the Delay Validation of the DataFlow Taskto True.
Answer: The flat file source has a special property for the purpose of giving you the file name:

Right click on the flat file connection manager and go to advanced properties.
In the component properties tab, go to Custom Properties> FileNameColumnName and enter a name, i.e. FileName
Once you hit ok to save the changes, the FileName column will be added to the output buffer and this can be mapped in the data flow.


Move pointers in order to print in a different order

Question: I have to complete this program.
I've a file like that
Name iD Num_of_elements elem(1) elem(2), ... , elem(n)
james 1 3 AAA BBB CCC
arthur 2 2 EEE FFF
james 1 1 KKK
irine 3 4 EEE FFF DDD AAA
james 1 1 XXX

I need to create a list, load the file into the list and print it ordering it as follow:
james 1 3 AAA BBB CCC
james 1 1 XXX
james 1 1 KKK
arthur 2 2 EEE FFF
irine 3 4 EEE FFF DDD AAA

(it's necessary to print persons with the same iD before, then the others).
I've created part of program in ANSI C, but I'm not able to complete the "final function" as request.
void printListOrderedByiD(struct list *top)
{ }
That's my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define len 35

struct elements
{
    char name[len];
};

struct list
{
    char name[len];
    int id;
    int numOfElements;
    struct elements *pElements; /* pointer to the struct elements */
    struct list *next;
};

FILE *openFile(FILE *fp)
{
    fp=fopen("file.txt", "r");
        if (fp==NULL)
            {
                perror("");
                exit(1);
            }
    return (fp);
}

struct list *newNode(FILE *fp)
{
    int i=0;
    struct list *temp=(struct list *)malloc(sizeof(struct list));

    fscanf(fp, "%s\t%d\t%d\t", temp->name, &temp->id, &temp->numOfElements);

    temp->pElements=(struct elements *)malloc(temp->numOfElements*sizeof(struct elements));

        for (i=0; i<temp->numOfElements; i++)
        {
            fscanf(fp, "%s\t", temp->pElements[i].name);
        }

        temp->next=NULL;

    return temp;
}

struct list *insertAsLast(struct list *top, FILE *fp) /* this function will insert every node at the end of the list */
{
    if (top==NULL)
    {
        top=newNode(fp);
    }
    else
    {
        top->next=insertAsLast(top->next, fp);
    }

return top;
}

void printList(struct list *top) /* this procedure will stamp the list as loades from the file */
{
    int i=0;

    if (top==NULL)
    {
        printf("//\n");
    }
    else
    {
        printf("%s %d %d ", top->name, top->id, top->numOfElements);

            for (i=0; i<top->numOfElements; i++)
            {
                printf("%s ", top->pElements[i].name);
            }
            printf("\n");

        printList(top->next);
    }
}

int main()
{
    struct list *top=NULL;
    char firstLine[200];
    FILE *fp=NULL;
    fp=openFile(fp);

        fgets(firstLine, 200, fp); /* in order to jump the 1st line */

            while (!feof(fp))
            {
                top=insertAsLast(top, fp);
            }
    fclose (fp);

    printList(top);

    return 0;
}

anyone is able to help me?
Answer: Sorted by the ID stored in the array temporarily.
static int cmp(const void *a, const void *b){
    int x = (*(struct list**)a)->id;
    int y = (*(struct list**)b)->id;
    return x < y ? -1 : x > y;
}
void printListOrderdByID(struct list *top){
    struct list **table, *p;
    size_t size=16, n=0, i;
    table = malloc(size*sizeof(struct list*));
    //Can be secured in the malloc simply if you use it the number of elements already known from a reading from a file.
    for(p=top; p ; p=p->next){
        table[n++] = p;
        if(n == size)
            table = realloc(table, (size+=16)*sizeof(struct list*));
    }
    qsort(table, n, sizeof *table, cmp);
    for(i = 0; i < n; ++i){
        int j;
        p = table[i];
        printf("%s %d %d ", p->name, p->id, p->numOfElements);
        for (j=0; j
numOfElements; j++){
            printf("%s ", p->pElements[j].name);
        }
        printf("\n");
    }
    free(table);
}

Comment: please could you explain what is

static int cmp(const void *a, const void *b){
    int x = (*(struct list**)a)->id;
    int y = (*(struct list**)b)->id;
    return x < y ? -1 : x > y;
}

Thank you
Comment: @Mariadegregorio elements of the array passed a pointer to the element as a `void *` to comparison function that is used in `qsort`. So `(struct list**)a` is `const void *a` --> `struct list **`, `*` is `struct list **` --> `struct list *`.
Comment: @Mariadegregorio comparison function shall return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively less than, equal to,
or greater than the second.
Comment: sorry and If I would like to order the list and then use the normal "printList"?
Comment: of course... as I did in my code...

I was asking if it woule be easy to
-order the list by ID
-use printList(top);

As I'm really newbe with programming, I think your code is a little bit hard for me...

I'll try to study it later, right now I'm not at home :(

Thank you for your support and your answers.
Have a nice weekend. :D
Comment: @Mariadegregorio You need to sort the list itself to print using the `printList` in the order of `ID`. E.g `sort(⊤);printList(top);`


Configure apt to use proxy in vagrant box

Question: I'm using Vagrant to setup a virtual machine for testing. I would like apt inside the virtual machine to use a proxy on the host machine to allow caching of all the downloads to persist between instances of the virtual machine running, not only for improved speed but to allow me to start the vagrant instance when I have no internet connection.
I've setup the proxy which is running, and I thought I'd told apt to use it by setting this in the Vagrant script:
config.vm.provision :shell, :inline => 'echo \'Acquire { Retries "0"; HTTP { Proxy "http://10.0.2.2:3128"; }; };\' >> /etc/apt/apt.conf'
config.vm.provision :shell, :inline => 'echo \'Acquire { Retries "0"; FTP { Proxy "ftp://10.0.2.2:3128"; }; };\' >> /etc/apt/apt.conf'
config.vm.provision :shell, :inline => 'echo \'Acquire { Retries "0"; HTTPS { Proxy "https://10.0.2.2:3128"; }; };\' >> /etc/apt/apt.conf'

And it's working partially i.e. the initial requests for sources hit the cache and work when my wifi connection is disabled but Squid is running and has some entries in it's cache. I can also see some requests hitting Squid from Squids log file:
1367492453.816     34 127.0.0.1 TCP_REFRESH_MODIFIED/200 592 GET http://security.ubuntu.com/ubuntu/dists/precise-security/Release.gpg - DIRECT/126.96.36.199 -
1367492453.987    168 127.0.0.1 TCP_REFRESH_MODIFIED/200 49973 GET http://security.ubuntu.com/ubuntu/dists/precise-security/Release - DIRECT/220.127.116.11 -
1367492453.999    325 127.0.0.1 TCP_MISS/404 588 GET http://us.archive.ubuntu.com/ubuntu/dists/precise/InRelease - DIRECT/188.8.131.52 text/html
1367492454.113    114 127.0.0.1 TCP_MISS/404 596 GET http://us.archive.ubuntu.com/ubuntu/dists/precise-updates/InRelease - DIRECT/188.8.131.52 text/html

However, the bulk of the download of packages are not being cached and doesn't appear to go through Squid at all i.e. I can see large network usage when they're downloaded and they don't appear in the Squid access log.
So my question how do I configure Apt to use a proxy for all it's requests?
btw I also tried configuring by setting the environment variable http_proxy:
 config.vm.provision :shell, :inline => "echo 'export http_proxy=http://10.0.2.2:3128' >> /etc/profile.d/proxy.sh"

This has the same effect - some requests appear to be hitting Squid but not all of them, and particularly not the actual packages.
Comment: possible duplicate of [wget works with company proxy but apt-get and dpkg doesn't](http://serverfault.com/questions/145451/wget-works-with-company-proxy-but-apt-get-and-dpkg-doesnt)
Comment: Hi Michael - the accepted answer to that question is to set "Acquire::http { Proxy "http://proxy:port"; };" which I'm already doing. I think the error may be on the squid side so will update it with relevant info.
Answer: Even though your problem might be in the squid config, to answer to the topic, there is now vagrant-proxyconf plugin. You can install it via:
vagrant plugin install vagrant-proxyconf

With it you can specify the Apt proxy globally in $HOME/.vagrant.d/Vagrantfile without the need to use shell provisioners in all project specific Vagrantfiles.
Example:
Vagrant.configure("2") do |config|
  config.apt_proxy.http  = "http://10.0.2.2:3128"
  config.apt_proxy.https = "http://10.0.2.2:3128"
end

or default proxy configuration:
Vagrant.configure("2") do |config|
  if Vagrant.has_plugin?("vagrant-proxyconf")
    config.proxy.http     = "http://192.168.0.2:3128"
    config.proxy.https    = "http://192.168.0.2:3128"
    config.proxy.no_proxy = "localhost,127.0.0.1,.example.com"
  end
  # ... other stuff
end

Comment: Would it be possible to autodetect a local apt proxy via Zeroconf, like squid-deb-proxy-client does?
Answer: Its possible that apt is using squid for all its requests, but squid isn't caching the results. You could verify this by sniffing traffic, or shutting down squid while apt is downloading packages and seeing if they fail. What is the maximum_object_size in your squid configuration?
Comment: You may want to look at the config squid-deb-proxy uses. http://www.jorgecastro.org/2010/02/04/introducing-squid-deb-proxy/
Comment: It was set to 128MB which I though was enough. However changing it to 256MB makes the actual packages appear in the squid log. It looks like Squids still not caching them, but now they are appearing and I'm investigating with your suggestion of inspecting the packets.
Comment: I'm still not sure why changing it to 256 made all the difference. None of the objects are anywhere near that size, but all the packages are showing up in the access log now. There's still some issues but they're Squid config issues.
Answer: Following title question, if you've private network set-up, like:
config.vm.network "private_network", ip: "192.168.22.22"
config.vm.provision "shell", path: "scripts/provision.sh"

I've found it easy to set-up proxy by simply exporting http_proxy in provisioning script, like:
# Detect proxy.
GW=$(netstat -rn | grep "^0.0.0.0 " | cut -d " " -f10)
curl -s localhost:3128 > /dev/null && export http_proxy="http://localhost:3128"
curl -s $GW:3128       > /dev/null && export http_proxy="http://$GW:3128"

Then run apt-get as usual.
This should detect your squid proxy on your localhost or host it-self.
To increase maximum_object_size value, the example is:
maximum_object_size 64 MB

which needs to be defined before cache_dir line.


ES Lint Error When Passing Parameter to Method in Vue

Question: I have an ES Lint Parsing Error in my Vue page. This is occurring because my parameter I am passing to the method contains a "." symbol.
Error - Syntax Error: Unexpected token (1:1628)

What is the solution to this syntax? Is there a way to escape this in the template file?
Full code can be found here
Thanks in advance for any help!
Answer: Define highlight as a computed property which returns a function that takes the price as parameter :

    computed:{
      highlight(){
        return (priceChange)=>{
        if(priceChange < 0)
        {
          return 'text-red-900'
        }
        if(priceChange > 0)
        {
          return 'text-green-900'
        }
        return '';
       }
      }
    },

and bind it to the class without using {} :


How to find out the relationship between variables?

Question: I have two variables Distance and Slope. These go into a model resulting in a cost variable. I like to figure out the influence of the variables Distance and Slope on the Cost variable. I have several hundred test numbers for the variables. What programs or steps could I use to see the impact of the two variables on the cost?
In the end I would like to know for example Distance influences the Cost variable too 70 %. Slope influence Cost too 30 %.
Answer: This sounds like you want a multiple regression model.  However the topic is much more than can be covered in a forum like this.  To do a proper regression model (and be sure that it is the correct model) really requires at least 2 courses in statistics (more recommended).
So, you should either enroll in some statistics courses (or find the equivalent self-study) or consult with a local statistician who can make sure that you are doing the right thing and help you understand the results.
Comment: Thanks Greg for your answer. Now I know at least that it is more complicated than I thought. I will talk to a statistician at my company.


Is LSTM (Long Short-Term Memory) dead?

Question: From my own experience, LSTM has a long training time, and does not improve performance significantly in many real world tasks.
To make the question more specific, I want to ask when LSTM will work better than other deep NN (may be with real world examples)? I know LSTM captures the sequential relationship in data, but is it really necessary?
Most demos on related topic are meaningless. They just focus on toy data e.g., IMDB review, where simple logistic regression will get very good results. I do not see any value of using LSTM which has huge computational cost but marginal improvements (if there are any).
Even with these toy examples, I did not find any good use cases that LSTM can solve very well but other models cannot.
Comment: Where exactly does logistic regression work better then LSTM? LSTMs work good for problems where we are dealing with time-dependent data, e.g. human language, for such data it is unlikely that logistic regression would give any reasonable results. Obviously, you can solve some simple tasks, or even more complicated ones, without LSTMs, sometimes even with trivial algorithms like Naive Bayes etc.
Comment: On most NLP tasks that have enough training data, LSTMs and GRUs perform better, then TF-IDF + plus other extracted features, that later later on passed to logistic regression, at least in my experience. But then there are techniques: https://www.youtube.com/watch?v=S27pHKBEp30, that are said to be better then LSTMs
Comment: yeah, transformers rule over LSTM! :)
Comment: A recent blog post claiming that LSTMs are dying: https://towardsdatascience.com/long-short-term-memory-networks-are-dying-whats-replacing-it-5ff3a99399fe
Comment: No. They perform superbly for time-series problems for real-valued data.
Answer: Maybe. But RNNs aren't.
Transformers learn "pseudo-temporal" relationships; they lack the true recurrent gradient that RNNs have, and thus extract fundamentally different features. This paper, for example, shows that the standard transformers are difficult to optimize in reinforcement learning settings, especially in memory-intensive environments. They do, however, eventually design a variant surpassing LSTMs.
Where are RNNs still needed?
Long memory tasks. Very long memory. IndRNNs have show ability to remember for 5000 timesteps, where LSTM barely manages 1000. A transformer is quadratic in time-complexity whereas RNNs are linear, meaning good luck processing even a single iteration of 5000 timesteps. If that isn't enough, the recent Legendre Memory Units have demonstrated memory of up to 512,000,000 timesteps; I'm unsure the world's top supercomputer could fit the resultant 1E18 tensor in memory.
Aside reinforcement learning, signal applications are memory-demanding - e.g. speech synthesis, video synthesis, seizure classification. While CNNs have shown much success on these tasks, many utilize RNNs inserted in later layers; CNNs learn spatial features, RNNs temporal/recurrrent. An impressive 2019 paper's network manages to clone a speaker's voice from a only a 5 second sample, and it uses CNNs + LSTMs.
Memory vs. Feature Quality:
One doesn't warrant the other; "quality" refers to information utility for a given task. For sentences with 50 words, for example, model A may classify superior to model B, but fail dramatically with 100 where B would have no trouble. This exact phenomenon is illustrated in the recent Bistable Recurrent Cell paper, where the cell shows better memory for longer sequences, but is outdone by LSTMs on shorter sequences. An intuition is, LSTMs' four-gated networking permits for greater control over information routing, and thus richer feature extraction.
Future of LSTMs?
My likeliest bet is, some form of enhancement - like a Bistable  Recurrent Cell, maybe with attention, and recurrent normalization (e.g. LayerNorm or Recurrent BatchNorm). BRC's design is based on control theory, and so are LMUs; such architectures enjoy self-regularization, and there's much room for further innovation. Ultimately, RNNs cannot be "replaced" by non-recurrent architectures, and will thus perform superior on some tasks that demand explicitly recurrent features.
Recurrent Transformers
If we can't do away with recurrence, can't we just incorporate it with transformers somehow? Yes: Universal Transformers. Not only is there recurrence, but variable input sequences are supported, just like in RNNs. Authors go so far as to argue that UTs are Turing complete; whether that's true I haven't verified, but even if it is, it doesn't warrant practical ability to fully harness this capability.
Bonus: It helps to visualize RNNs to better understand and debug them; you can see their weights, gradients, and activations in action with See RNN, a package of mine (pretty pics included).

Update 6/29/2020: new paper redesigns transformers to operate in time dimension with linear, O(N), complexity: Transformers are RNNs. Mind the title though; from section 3.4: "we consider recurrence with respect to time and not depth". So they are a kind of RNN, but still differ from 'traditional' ones. I've yet to read it, seems promising; a nice video explanation here.
Comment: That [Transformers are RNNs](https://arxiv.org/pdf/2006.16236.pdf) paper you cite is an interesting one.  Notably, they replace the Softmax operator with with a nonlinearity that occurs BEFORE the pairwise dot-products instead of after, as Softmax does.  So their transformer computes a very different output than the standard one.  I don't think it has caught on yet, has it?
Answer: It is funny that you ask now, since just today I came across a paper by Wang, Khabsa, and Ma (2020) To Pretrain or Not to Pretrain who show that if you have large enough training set, the difference in performance between huge, "SOTA" model (RoBERTa), and LSTMs is small for NLP task. There was another recent paper by Merity (2019) Single Headed Attention RNN showing similar results, the abstract is worth quoting in full

The leading approaches in language modeling are all obsessed with TV
shows of my youth - namely Transformers and Sesame Street.
Transformers this, Transformers that, and over here a bonfire worth of
GPU-TPU-neuromorphic wafer scale silicon. We opt for the lazy path of
old and proven techniques with a fancy crypto inspired acronym: the
Single Headed Attention RNN (SHA-RNN). The author's lone goal is to
show that the entire field might have evolved a different direction if
we had instead been obsessed with a slightly different acronym and
slightly different result. We take a previously strong language model
based only on boring LSTMs and get it to within a stone's throw of a
stone's throw of state-of-the-art byte level language model results on
enwik8. This work has undergone no intensive hyperparameter
optimization and lived entirely on a commodity desktop machine that
made the author's small studio apartment far too warm in the midst of
a San Franciscan summer. The final results are achievable in plus or
minus 24 hours on a single GPU as the author is impatient. The
attention mechanism is also readily extended to large contexts with
minimal computation. Take that Sesame Street.

I don't think there's much to add.
Here is another example from very recent paper by Abnar, Dehghani, and Zuidema (2020) Transferring Inductive Biases through Knowledge Distillation

Several studies, however, have shown that LSTMs can perform better
than Transformers on tasks requiring sensitivity to (linguistic)
structure, especially when the data is limited [37, 6].  This is mainly
due to the recurrent inductive biases of LSTMs that helps them better
model the hierarchical structure of the inputs.

hence authors show how distilling information from LSTMs can positively impact Transformer model. This another, of many, examples that LSTMs, and RNNs in general, are used and perform good for a particular class of problems. Sure, they have limitations, but for language they are standard model, that is taught on on every NLP course (like Stanford's CS224n), and mentioned in every modern handbook on this topic. The above examples focus on language data, because in this area this model is very popular, but of course it is successfully applied to other kinds of time-series data as well, as mentioned in other answers.
Comment: Your answer shows LSTM is almost as good as some more complex competitors. The OP states the even simpler competitors (such as logistic regression) of LSTM may be almost as good as LSTM. Taken the two together, shall we say logistic regression is a decent substitute for the SHA-RNN? More seriously, I think you answer a slightly different question. (+1 nonetheless)
Comment: @RichardHardy added a comment under the question to clarify. Obviously, LSTM is overshot for many problems where simpler algorithms work, but here I'm saying that for more complicated problems, LSTMs work good and are not dead.
Comment: @Tim just one last comment: at least transformer does not involve using tf.while lol
Comment: @Tim Not sure why transformer is considered more complex than LSTM. Also from the SHA-RNN paper it seems the number of parameters is about the same. I'd be really surprised if it reaches BERT-like quality on GLUE fine-tuning tasks.
Comment: @JohnJiang transformer is considerably more complicated architecture, but comments is not the place for such discussion.
Answer: Our group recently built an LSTM model in a real world application. At first we had used other approaches, but then we decided to include features that were measurements taken over time, but of variable length - so for one person, we would have 15 measurements (of the same parameter) taken over a 3-month period, for another we would have 20 measurements over a 2-month period, and so on. Other features were present once per person, e.g. gender.
In this situation, standard time series approaches turned out to be unusable, since they expected us to have an equal number of measurements per person, taken at equal intervals. LSTM allowed us to build a model predicting if a certain event will occur for a person, using the variable length measurements combined with the once-per-person measurements.
We also compared our model to a simpler regression model using only one value per time-varying parameter (I forget what it was, probably the average value over time) and to a regression model using three measurements per time-varying feature per person and treating them as measurements of independent variables. The LSTM model had much better accuracy than both of these models, especially for the class of persons for whom the event occurred.
I know that this is just one counterexample, and LSTM is not the only algorithm to deal with that kind of situation - but the way your question is stated lends itself to counterexamples, and statistics/ML would be an impoverished area if we didn't have different tools to choose from.
Answer: LSTM is a statistical method. It is not alive so it cannot be dead. It can be useful though. Any statistical method is another tool in a box. If one does not work it is good to have an alternative.
LSTM is good for language recognition tasks where context is important. It is also good for forecasting time series. The M4 competition was won by LSTM.
If it was not useful there would not be a significant body of research dedicated to it. However as far as I know there is no proof that LSTM is inferior to any other method in some meaningful sense, i.e. the class of problems which LSTM is able to solve is smaller than logistic regression, etc.
Comment: Downvote. I had a look at that paper. The winner (Smyl) is a new innovative hybrid that partly uses RNN, not saying that this RNN was an LSTM. "The superiority of a hybrid approach that utilizes both statistical and ML features.The biggest surprise of the M4 Competition was a new, innovative method that was submitted by Slawek Smyl, a data sci-entist at Uber Technologies, which mixes ES formulaswith a recurrent neural network (RNN) forecasting en-gine." The link is nice, thanks for that, but your answer seems wrong.

Is LSTM (Long Short-Term Memory) dead?


How do I add a password field on registration form?

Question: I have a basic website, with nothing installed on it yet. My first task is to get my users to be able to register with a password. I see that certain "modules" will allow you to do this, but is a module really necessary to be able to register with a set password?
I'm using Drupal 7.
Answer: Go to Account Settings (admin/config/people/accounts) and uncheck the Require e-mail verification when a visitor creates an account checkbox.

With this setting disabled, users will be logged in immediately upon
  registering, and may select their own passwords during registration.

If you want both (Password field + email verification), use the User registration password module
Comment: Check also [Login Toboggan](http://drupal.org/project/logintoboggan)


Missing edit button on node page

Question: Im allowing authenticated users to add field values on existing nodes on my site using the "Field Permissions" module. I`ve set up the necessary custom permissions in the "manage fields" screen:

However, an authenticated user is never shown the "Edit" button on the node page:

If everything where working, the user should have a "Edit" button to be able to add field values. What`s wrong?
Comment: Impossible to debug from here. Maybe some module blocks edit anyway? Maybe user does not have permission to text format used in given node? Maybe theme is flawed and simply fails to render that button? Maybe something else entirely.
Comment: OK, its not the theme. Ive checked.
Comment: List of things you already checked should be in the question directly. Preferably with info on *how* you checked.
Comment: Have you tested to narrow it to a display or permission issue? For example, having the auth user navigate to */node//edit* to see if they can access the node edit form.
Answer: The Field Permissions is so the field shows up, they can see it, when they are editing the node.
The problem here looks to be that they don't have permission to edit the content type node.
Ex:

Allow to Edit Own Articles
Allow to Edit All Articles

Missing edit button on node page


Predict probabilities for continuous variable

Question: Usually, with a continuous dependent variable, we can apply linear regression and then predict values based on new data.
For instance, defaults on loans: let's say we know an individual will default on his loan, and we want to estimate how long it takes him to default (1 year, 2 years, 3 years... after he took the loan).
With linear regression, we can predict for a new individual that, based on his characteristics, he will default after X years.
But what I'm looking for is a model which will give me probabilities for each of the values.
Here, it would be: for a new individual that we know is going to default, what is the probability he will default after 1 year vs the probability he will default after 2 years...
One possibility would be to consider that the dependent variable is categorical, and regress a logit / probit model to get probabilities.
But 1) there is some loss of information. Multinomial logit does not consider the categories as related. At best, ordered logit will order them. But we still don't take into account the increment is the same between all categories (1 year).
And 2) if we want to consider defaults on more than a few years, the number of categories of the dependent variable quickly increases, which will affect the performance of the predictions.
So if anyone has an idea on how to tackle this problem, I'd like to know your thoughts! I feel like I'm not approaching it right at the moment, and maybe I need another kind of modelisation altogether.
Thank you very much !
Answer: If you want to predict things like probability of default as a function of time, then you are interested in survival analysis models, so check the questions tagged as survival-analysis.
As about your general question, with binary data we use logistic regression that enables us to predict the probability of success by assuming Bernoulli distribution, with multiple categories we assume multinomial distribution, and for continuous data, we assume an appropriate continuous distribution. In case of linear regression, the probabilistic model behind it assumes normal distribution, so if know the parameters of the distribution, you can estimate the probability densities for a particular outcome, given the estimated parameters. Same with other distributions, so basically the all you need is a probabilistic model.
Comment: Note also ordered (ordinal)  logit or probit, although that seems a little artificial in this case.
Comment: Thanks a lot for your answers! About survival analysis models, is the probability of survival necessarily decreasing with time? Ideally I'd rather be able to model the peak  for example in year 3, in general not necessarily year 1. About linear regression, when you say parameters do you mean the normal distribution parameters (mean and variance) ? Can I get them through the usual packages (in R for instance) or would I have to compute them myself?
Comment: @ALF survival analysis models model cumulative probabilities, they do not assume that probability increases over time, but obviously the cumulative probabilities increase (you can extract the non-cumulative probabilities from this). As about R, there's a `survival` package.
Comment: @Tim I see,with cumulative probabilities it should correspond to what I want, and indeed it would be easy to extract the non-cumulative probabilities from there. Thanks again!


Running javascript in a page loaded by xmlhttprequest

Question: In my javascript method I'm calling a xmlhttprequest to grab some data and display it in a div called 'myDiv' (index.php)
function combo_change(theid)
{
  if (window.XMLHttpRequest)
  { // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  xmlhttp.onreadystatechange=function()
  {
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","anotherpage.php?id=" + theid,true);
  xmlhttp.send();
}

Now, I'm trying to call some javascript within the page "anotherpage.php", but it does not want to work. As a test I'm just doing a document.write('hello');. If I load the page directly it will show, but when using the code via xmlhttp open it will not.
I can assume that when loading like this, the javascript is not being run. So, is there anyway I can make it run?
Comment: For a quick, dirty hack, you can use eval. I'm not recommending it though.
Comment: Why are your quotes escaped? (don't say "because it's inside a PHP script" - that's not an acceptable reason)
Comment: Good spot. Whats wrong with doing that?
Answer: Write your JavaScript code inside
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
  document.getElementById(\"myDiv\").innerHTML=xmlhttp.responseText;
  //Your js code
}

Answer: Have a look at this: http://zeta-puppis.com/2007/05/27/javascript-script-execution-in-innerhtml-another-round/
Short version: document.write() has issues, try alert() instead to see if your script runs.
Comment: +1 This looks interesting but would be a bit of a rewrite right now. Will have to implement this later though! Thanks.


How to calculate minimum unixtimestamp value using sparksql?

Question: completion time | unixtimestamp | user|
0.07            |1529094938000  |user3|
0.16            |1529094944000  |user2|
0.27            |1529094947000  |user1|
0.08            |1529094950000  |user2|
0.24            |1529094953000  |user1|
0.10            |1529094956000  |user1|
0.64            |1529094959000  |user3|
0.13            |1529094962000  |user3|
0.67            |1529094965000  |user1|

I want minimum timestamp for every user. How can we do it using Sparksql?
Assume the above table is in a dataframe.
Answer: we will first convert the timestamp field into integer type if it is not already by any chance.
val new_dataframe =  dataframe.select($"unixtimestamp".cast(IntegerType).as("unixtimestamp"))

1) Create sqlContext in spark if not exists using the SparkContext object
val sqlContext = new org.apache.spark.sql.SQLContext(sc)

2) Register this dataframe as a table
new_dataframe.registerTempTable("user_timestamp_data")

3) Now with the prior created sqlContext we can query as
    val result =
    sqlContext.sql("SELECT q.user,ROUND(UNIX_TIMESTAMP(q.min)*1000) as
    MinimumUnixTimeStamp
    FROM (
    select  user, MIN(FROM_UNIXTIME(unixtimestamp/1000) min
    FROM user_timestamp_data
    GROUP BY user
    ORDER BY user ASC) AS q ")

That should give you users and their corresponding minimum timestamp value
Answer: Use groupBy and agg:
val df2 = df.groupBy("user").agg(min(col("unixtimestamp")))


Plane of symmetry and geodesics in surfaces

Question: Let $(M,n)$ be an oriented regular surface of $\mathbb{R}^{3}$ such that the intersection of $M$ with the plane
$\Pi:=\{(x,y,z) \in \mathbb{R}^{3}:z=0\}$ is the image of a curve parametrized by arc length $\alpha$.
I am trying to prove that if $\varphi:M \rightarrow M$ defined by $\varphi (x,y,z)=(x,y,−z)$ is an isometry of M then the curve $\alpha$ must be a geodesic of M.
I would like to prove that the normal vector $n \circ \alpha(t)$ is orthogonal to the vector $e_3 = (0,0,1)$ (for any $t \in \operatorname{dom}(\alpha)$).
I know that the vector $n \circ \alpha(t)$ is an eigenvector of the linear transformation $R: \mathbb{R}^{3} \rightarrow \mathbb{R}^{3}$ given by  $R(x,y,z)=(x,y,−z)$, but I don't know how to prove that the tangent space $T_{\alpha(t)}M$ can't be the vector space $\operatorname{span}\{e_1,e_2\}$.
I also know that the hypothesis $M \cap \Pi$ equal to the image of a curve is important and necessary.
I have tried many things but I'm not making any progress. So I would really appreciate any help.
Answer: The reason that the tangent plane $T_{\alpha(t)}$ can not be $span\{e_1, e_2\}$ is that in that case the projection to the $x-y$ plane would be a chart near $\alpha(t)$, i.e. $M$ would be locally a graph of $z=f(x,y)$; but the only graph invariant w.r. to $R$ is the graph of the zero functions $z=0$. However, in such a case the intersection of $M$ with $\Pi$ would not be a curve (a smooth curve can not have an image that fills in any open set of a plane). So this is excluded.
Now, (as you have perhaps already figured out) the derivative of any map $\varphi$ mapping $M_1$ to $M_2$ sends the tangent plane $T_p M_1$ to the tangent plane $T_{\varphi(p)} M_2$. In our case, when $p$ is on the curve $\alpha$ we have $\varphi(p)=p$ and $D\varphi$, being the linearization of $R$, which is already linear and fixes $p$, is $R$. Thus the tangent plane is invariant, and so the normal vector is invariant (up to sign), i.e. an eigenvector with eigenvalue $\pm 1$, and the case of it being $\pm e_3$ is excluded, so it lies in the $x-y$ plane. Now the acceleration vector of $\alpha$ is also in the $x-y$ plane and, since $\alpha$ is unit speed it is orthogonal to the velocity vector of $\alpha$, hence parallel to the normal vector to $M$, making $\alpha$ a geodesic.


Combination Factorial formula

Question: Is there a formula for working out combinations using the factorial of the 'choice' number?
E.g.: for a group of 6, what are the total possible combinations of up to 4 selections?
I have been doing this by adding the individual combinations, so (in the above example) I would add:
$$ \def\c#1#2{\binom{#1}{#2}}
     \c64+
    \c63
    + \c62
    + \c61 = 15+20+15+ 6 = 56 $$
to arrive at 56, but I'm interested to know if there is a formula that I can use.  I've looked at the combinations questions but didn't see one similar.
Many thanks
Comment: See http://mathoverflow.net/a/17203/36426 for partial sums of binominal coefficients.
Comment: You missed "no selection", that is $\binom 60= 1$ should be added, or?
Comment: No, must be at least one.  The use case is number of possible valid vote combinations in a 'first past the post' election.  Voters can nominate up to the number of vacancies to make a valid vote, but an empty ballot paper is considered invalid.
Answer: According to WolframAlpha the result is not very simple. The only easy cases I can think of is summing over all possibilities ($2^n$) or summing over half the possibilities. This only really works if you have an odd number of total people, but can be adapted to an even number $2k$ of people if you take care what you do with the special $k$-group case. The rest are, I believe, easiest found by getting to one of these points and add / subtract as necessary.
For instance, with $6$ people there are $2^6 = 64$ ways to choose groups in total, and since you want groups with no more than $4$ people it's easier to subtract the number of $5$-groups and $6$-groups as well as the empty group to get
$$
2^6 - \binom 6 5 - \binom 6 6 - \binom 6 0 = 64 - 6 - 1 - 1 =  56
$$
which in my opinion is easier to calculate than your summing over all valid combinations. Not much easier in this case, but it might help considerably once you get to the double digits.
Comment: OK, so there's no simple formula, and (though not the most efficient), the method I'm following is correct.  I will probably keep adding all combinations lower than 'k' as the computer can decrement through the list faster than I can determine whether that is quicker than subtracting the remaining non combinations from the (2n) total.  Many thanks.
Answer: Pascal's triangle:

What you are looking for is the sum on a diagonal.
The diagonal 1, 6, 15, 20, 15, 6, 1 contains what you're looking for.
The array is easy to compute a[x][y]=a[x-1][y]+a[x][y-1]
Although to find the sum on diagonal N you need O(N^2) computations.
The triangle is mirrored so you could only compute N^2/4 values.

Combination Factorial formula


How to check How I installed MongoDB

Question: I am making full stack application(MERN) using MongoDB Atlas.
I want to access to mongod.conf to change some configuration on my mongoDB on my Mac OS Big Sur(Version 11.5.2).
on the internet, almost all of information says, if I installed it through Homebrew, it should be in /usr/local/etc/mongod.conf.
However I don't find it in this directory, so I must have installed it from somewhere else.
How do I know how I installed something in my mac?
Also, Is it possible that I am using MongoDB Atlas without installing them in my machine?
Thank you
Answer: With brew if more easy, documentation says, first

brew tap mongodb/brew

brew update

brew install firstname.lastname@example.com

then you need start the service

brew services start email@example.com

To see the service running you need write on the terminal

brew services list

and you will see this

It's not needed to have installed locally, you can use the free tier from MongoDB Atlas or mlab. You will need to setup the user access permission and the url where your database is stored.
Finally you can use the command "mongo" in the terminal and you will see if it's installed correctly.

How to check How I installed MongoDB


Is this an imperfect authentic cadence in a minor key?

Question: In the case where the chords ending a phrase (in B minor) are:
| D | A | A#m | Bm |
in B minor it would be
III V/III(VII) #vii i
In my opinion the A#m is a passing chord, which leaves me with D A Bm. I understand that in this case the secondary dominant  of III also acts as VII being the substitution for V. If I understand correctly the leading tone is E (to F in the passing chord and Bm).
Could this be regarded as an imperfect authentic cadence? Is such a term strictly limited to diminished vii and I in major keys (in relation to the similar movement)?
Comment: Related: https://music.stackexchange.com/questions/52342/cadence-naming-confusion
Answer: An authentic cadence will always have a root-position V moving to a root-position I (or i). In B minor, this means that we'll have an F♯ major chord moving to B minor.
The distinction between perfect and imperfect authentic cadences regards the highest-sounding pitch. If the tonic scale degree (in this case, B) is the highest-sounding pitch, it will be a perfect authentic cadence (or PAC).
But if the highest-sounding pitch is another member of the tonic triad (D or F♯), it will be an imperfect authentic cadence (or IAC).
Your progression of ♯vii to i would be more along the lines of what many call a contrapuntal cadence.
(Is there a text somewhere that told you viio to I was an authentic cadence?)
I'm also not sure what you mean by:

If I understand correctly the leading tone is E (to F in the passing chord and Bm).

I've never heard of such a leading-tone IAC, but if we're following that definition, it seems that your example would fall under the "subV" category, and therefore fit. IACs are not only limited to major keys, and they do occur in minor keys.
Comment: I've never heard of such a leading-tone IAC, but if we're following that definition, it seems that your example would fall under the "subV" category, and therefore fit. IACs are not only limited to major keys, and they do occur in minor keys.
Comment: @MaikaSakuranomiya - Power chords based on the leading tone are so common in heavy metal that I'd count them as their own full entities, not passing chords.
Comment: Richard, ♯vii is a **passing chord**, as the OP (Mat) has noted.  Therefore, the actual cadence is rather a VII - i.
Comment: Thank you for your answer. According to wiki: https://en.wikipedia.org/wiki/Cadence_(music) , "Imperfect authentic cadence (IAC), best divided into three separate categories: 1. (...), 2. (...), 3. Leading tone IAC: the V chord is replaced with the viio/subV chord (but the cadence still ends on I)."
Comment: As to the leading tone, I thought that the use of a semitone movement (in a more broad sense than seventh scale degree of a major scale to I) is necessary in order to use "Leading tone IAC" mentioned above. I am not sure whether the application of IAC is limited to major keys.
Answer: So, your chord progression is D - A - (A♯m) - Bm (b: III - VII - (♯vii) - i).  Since ♯vii (A♯m) is a passing chord, we skip over it - which means, we get D - A - Bm (b: III - VII - i).
(I'm not sure why you are counting the A chord as a secondary dominant if it comes before a passing chord and actually resolves to Bm.)
Your cadence is a VII - i in B minor, because it is A - Bm.  VII - i (or ♭VII - I in major) cadences are extremely common in modern popular music, and is fairly common in late Romantic and Modern classical music.
For example, we have an E minor cadence of VII43 - I (D7/A - E).

The D7/A chord has dominant function in this case.  Its top note, D, is not a leading-tone if you say it is "subtonic".  However, it acts more like a leading-tone.  Specifically, the ^7 degree note is a whole step below the tonic, but gives us a "pull" back to the tonic.  It resolves to E, which is the tonic chord that has tonic function.
Your example is basically the same.  The A chord has dominant function and resolves to Bm, which is the tonic.

Now, the question is basically confusing to answer - The VII chord creates tension and resolves to the stable i chord.  However, the root of the VII is a whole step below the tonic, not half.  Therefore, it is either a variant of the leading-tone IAC, or "what?".  So the answer to your question is: could argued to be a "yes", while it can also be a "no".
Answer: Authentic cadence is always from V -> I.
Imperfect cadence is one that inverts the V or I in some way. So for example vi -> II is an imperfect cadence since vi is the inversion of V and II is the inversion of I.
Reference: https://www.solfej.io/blog/cadences/


[Leetcode]448. Find All Numbers Disappeared in an Array

Question: problem link from leetcode
I came up with two solutions wrote in Python but did not pass and do not know why.

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array),
  some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this
  array.

Here is my first solution:
class Solution(object):
  def findDisappearedNumbers(self, nums):
     nums=sorted(list(set(nums)))
     for x in range(1, nums[-1] + 1):
       if x in nums:
         nums.remove(x)
       else:
         nums.append(x)
     return nums

the result is  " Runtime Error Message: Line 4: IndexError: list index out of range". But I did not get it.
The second solution:
return [x for x in range(1, len(nums) + 1) if x not in nums]

The result is "Time Limit Exceeded",still,confused.
Both solutions works okay in my Pycharm with python 2.7.11.Maybe there are some test cases my solutions did not pass but I can not find it.
Answer: First of all, try to use xrange instead of range as this uses less space when the value of nums is very large. Also, you are trying to iterate as well as delete/append a value at the same time in the same array. This is most likely the reason why you are getting the error.
Also, removing a value in the list (if it is not at the end) takes a lot of time because all other elements before it need to moved.
Answer: From the first solution: DO NOT modify the list you are iterating. Always brings problems. Better copy the list and modify the list!
class Solution(object):
    def findDisappearedNumbers(self, nums):
        nums=sorted(list(set(nums)))
        nums_copy = nums.copy(nums)
        for x in range(1, nums[-1] + 1):
            if x in nums:
                nums_copy.remove(x)
            else:
                 nums_copy.append(x)
        return nums_copy

On the other hand, if num is very large (has many elemente)range can bring problems because it creates the list first (and VERY large lists occupy a LOT of memory). For me cases it is better to xrange than to return a generator.
This does not happen in python3, where the default range returns a generator.
Comment: yeah,u r right! thanks!,shouldn't manipulate the list while iterating,especially change the len of the list.
Answer: You can use nums = set(nums) which will sort and remove all the duplicates. Then you can run a loop to append all the numbers not present in nums to output array.
Comment: A `set` doesn't sort the elements. Quite the opposite actually, a set is a random data structure
Answer: Your first solution will fail if the test input is an empty list as num[-1] would give an index out of bound.
Your second solution will be slow as it has to iterate through the list. Would the below solution work? Set operations are optimised. But is the space complexity ok for you?

    ret = set(range(1, len(nums)+1))
    ret = ret - set(nums)
    return list(ret)

Comment: "if x not in nums" takes too much time, my final solution "return list(set(range(1, len(nums) + 1)) - set(nums))" works out and basiclly the same as ur solution, Thanks!


Steel-string parlor guitar - effect on tuning stability when changing string gauge?

Question: I have an acoustic guitar that's currently strung with .012 gauge strings. I'd like to change that to lighter strings (around .010) and lower the action a bit. (This is my secondary acoustic, and I'd like to differentiate it from my main ax a bit more.)
One of the obstacles facing me is that this guitar tends to get thrown out of tune by heavy strumming, sometimes lasting only a song before it needs to be retuned. Will this tendency continue with lighter strings, or possibly worsen?
I'm planning to work on increasing the angle of the strings at the nut (by winding the stings differently) in an attempt to help the tuning problems. But is there anything else I can do while upgrading the guitar's setup?
The guitar is a Seagull "Grand" parlor acoustic.
Answer: When you change string gauge, it's often necessary to adjust the truss rod to compensate for the change in tension.
You can get away without doing this if you don't mind some minor intonation issues but it sounds as if you are exacting enough to care.
If the instrument won't stay in tune, then either you're not tensioning the strings properly after fitting them, or you have faulty machine heads.
It sounds like now is a good time to take the instrument to a guitar tech for some maintenance.   If it's not been serviced for so long that it won't stay in tune, there are likely to be other servicing jobs.
A service every 2 years is reasonable for a well played guitar. You can expect to see some fret wear in that time, for example.
Comment: What would you say constitutes a service? This guitar has no intonation adjustment, so tuning initially may be fun, with lighter strings.Having done just this on several guitars (including a parlour) it should work out o.k.Agree with pre-tensioning of strings,several times for a couple of days !The pegs on the bridge may also not be as tight as neccessary.
Comment: Pre-tensioning: Is this stretching the strings out and letting them settle? Or something else?
Comment: I mean stretching them lots once they are on, and seemingly up to pitch. Maybe re-tensioning is a better word.I must have been influenced by the term 'pre-bend' which HAS to be a misnomer.
Comment: Tensioning: tune, then put your fingers underneath each string and give it a good tug away from the body. It will go flat. Retune and repeat until it doesn't go flat.
Comment: A good service will include lots of things - clean, fix any worn frets, (search online, lots of guitar techs describe in detail what they do) but what's important to you here is checking the machine heads (repair or replace) and getting the truss rod adjusted right (which is the only way intonation can be influenced in the absence of an adjustable bridge).
Comment: Not sure what difference it makes, but I stretch the strings by pushing with  thumb and pulling with a finger, all along their lengths. To me, it's safer for the guitar than using it like a bow shooting an arrow.


Error when trying to access Webform settings

Question: When I try to go to the Structure > Webforms > Settings and Webforms I am getting the following error. I tried the $ drush webform-repair command, but that doesn't work. My Drupal version is 8.6.4.

The website encountered an unexpected error. Please try again later.
  TypeError: Argument 4 passed to
  Drupal\webform\EntitySettings\WebformEntitySettingsBaseForm::appendBehaviors()
  must be of the type array, null given, called in
  /Applications/MAMP/htdocs/ubci+webform/modules/webform/src/EntitySettings/WebformEntitySettingsGeneralForm.php
  on line 274 in
  Drupal\webform\EntitySettings\WebformEntitySettingsBaseForm->appendBehaviors()
  (line 104 of
  modules/webform/src/EntitySettings/WebformEntitySettingsBaseForm.php).

And I am getting another error when I try to download the results on Webforms > Download.

The website encountered an unexpected error. Please try again later.
  Error: Unsupported operand types in
  Drupal\webform\Form\WebformResultsExportForm->buildForm() (line 57 of
  modules/webform/src/Form/WebformResultsExportForm.php).
  Drupal\webform\Form\WebformResultsExportForm->buildForm(Array, Object,
  Object)
Comment: In case you have not tried it: Goto Configuration/Development/Performance and clear the cache. Also since you are using Webform... be sure to use composer and see if the Webform and it's requirements are up to date.
Answer: I found the solution on the maintainer's blog: https://www.jrockowitz.com/blog/managing-webform-configuration. Go to admin/structure/webform/config/advanced and click 'Repair configuration'.

Repairing admin configuration and webform settings
If you happen upon some webform configuration that is outdated, you
  can run the drush webform:repair command or click the 'Repair
  configuration' via the admin UI under that 'Advanced' configuration
  tab (admin/structure/webform/config/advanced)
Comment: this fixed the issue for me today
Answer: In my case, I was working on a migrated site and didn't have the webform.settings config.
To fix:

Grab config from an existing site: /admin/config/development/configuration/single/export
Import the config to current site: /admin/config/development/configuration/single/import

I had some errors about themes not being present, so I had to create dummy themes, install them, then uninstall them before the config import would work.


ViewPager + recycling views?

Question: I'd like to create a gallery of photos that swipe left and right. At first I took a look at Gallery, but it's marked as deprecated.
http://developer.android.com/reference/android/widget/Gallery.html
We're told to try ViewPager instead. But the PagerAdapter class doesn't handle recycling of views for us (like a standard ListView), does it?
http://developer.android.com/reference/android/support/v4/view/PagerAdapter.html
Is it up to us to build the recycling mechanism?
Thanks
Answer:
But the PagerAdapter class doesn't handle recycling of views for us
  (like a standard ListView), does it?

No, and I think it's because it was built assuming you are using different layouts for each of the page.
Also, as it is not being scrolled as fast as a ListView (you cannot "fling" a ViewPager to skip multiple pages), I think it doesn't need to have to recycle.
Comment: But Gallery is deprecated, so they basically don't give us any recyclable horizontal swiping solution?
Comment: hah, if you think of it that way, recycling in this context can mean two opposite things! :) yes in fact it's currently the only way to do horizontal swiping, short of implementing your own (or using a 3rd party) horizontal listview.
Comment: @user291701 Gallery doesn't recycle views anyway, despite using an adapter (`convertView` is always null)
Comment: @ılǝ keeping views alive is not the same as recycling... it's just alive so the adapter doesn't need to inflate it again when the user is just switching between two or three views, but it doesn't necessarily use the same view for different pages. Also FragmentPagerAdapter does not hold Views -- it holds Fragments, and there is no overload of the method getItem(int position) for FragmentPagerAdapter, so I don't think it's recycling anything.
Comment: Well `FragmentPagerAdapter` calls `onDestroy()` for fragments which are not displayed or adjacent to the visible fragment. Hence - they are in fact recycled, no?
Comment: the fact that onDestroyed is called would suggest that they are not recycled, but that's just my opinion. also as mentioned in my previous comment there is no overload for the getItem that gives you an instance of a recycled fragment, as is the case with a list adapter (that has a convertView argument in its getView method)
Comment: I just realized that "recycling" isn't the same as "available for collection by the JVM GC". :) Anyway, it seems FragmentPagerAdapter can be a good solution for a horizontal swiping UI, even though it's not as efficient as ListAdapters. (and thanks for bearing up with me @JosephusVillarey :) )
Answer: This HorizontalListView is great, i used it to do exactly what you want.
Answer: see the link in the edit on this question The link in the Edit, and the answers give you some possible ways to solve.
There is also a HorizontalListView online somewhere if you search for it that makes a fine replacement for Gallery and does recycle its views.

ViewPager + recycling views?


NodeJS + sqlite3: erro ao obter informação pelo Select

Question: estou aprendendo nodeJS.
Estou tentando integrá-lo ao Sqlite3, mas ao tentar ler uma informação do banco está sendo gerado o seguinte erro:
/home/ubuntu/workspace/node_modules/sqlite3/lib/trace.js:28
                    throw err;
                          ^
TypeError: Cannot read property 'counter' of undefined
    at Statement.<anonymous> (/home/ubuntu/workspace/server.js:15:56)
--> in Database#each('SELECT COUNT(id) AS counter FROM tasks', [Function])
    at Database.<anonymous> (/home/ubuntu/workspace/server.js:10:10)
    at Object.<anonymous> (/home/ubuntu/workspace/server.js:6:6)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain [as _onTimeout] (module.js:497:10)
    at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

Segue abaixo o código do servidor:
    var fs = require('fs');
    var sqlite3 = require('sqlite3').verbose();
    var db = new sqlite3.Database("teste_db");

    db.serialize(function() {
        db.run("CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, expires INTEGER, done SMALLINT, user CHARACTER(32))");
        db.each('SELECT COUNT(id) AS counter FROM tasks', function(err, rows){
                if (err) {
                    callback(err);
                    return;
                }
                console.log("contagem de linhas: " + rows[0].counter);
            });
        });
    db.close();

Não importa qual nome eu dê para o campo a ser lido no banco, ele sempre presume que o nome do campo seja uma propriedade do array ROWS.
OBS: no exemplo usei um COUNT, mas em qualquer tipo de select ele retorna esse erro
Alguém pode me dizer onde estou errando?
Comment: pode logar o objeto rows e postar aqui? pode ser quye a tabela não tenha sido criada, pela natureza assíncrona do nodejs
Comment: Outra coisa, existe um ORM bem leve e simples para node, com uma documentação ótima. Chama-se Sequelize, recomendo dar uma olhada qualquer hora. Facilita bem o trabalho
Answer: A função de grupo COUNT não retorna um array. Se você inspecionar o retorno você vai verificar o seguinte JSON: { counter: 0 }.
Portanto, modifique a linha onde você imprime a contagem de linhas para
console.log("contagem de linhas: " + rows.counter);

e tudo vai funcionar corretamente.
P.S.: como na verdade não retornam vários registros, sugiro mudar rows para row, result ou algo mais apropriado.


Updating label twice and calling sleep() in between -- only second update is seen

Question:
Possible Duplicate:
Obj-C -> Incrementing a number (and showing steps on a Cocoa label)

I'm wondering why this isn´t working: the sleep and "whatever" is showing up as expected, but not the NSString before the sleep function (computing...). The label is empty for 1 second and then the second string shows up. Why is that?
if ([label.text isEqualToString : @"1"]) {
    [label2 setText : [NSString stringWithFormat : @"Computing..."]];
    sleep (1);
    [label2 setText : [NSString stringWithFormat : @"Whatever"]];
}

Comment: possible duplicate of [Obj-C -> Incrementing a number (and showing steps on a Cocoa label)](http://stackoverflow.com/questions/237621/obj-c-incrementing-a-number-and-showing-steps-on-a-cocoa-label), [Loop to change label text](http://stackoverflow.com/questions/6325202/), [Text field waits until the end of a loop to update](http://stackoverflow.com/questions/5829977/), and especially [Calling sleep() and updating text field not working](http://stackoverflow.com/questions/5834062/calling-sleep5-and-updating-text-field-not-working)
Answer: This is presumably taking place on the main thread. By sleeping, you stop the screen from updating and so the first change is not displayed. Then as soon as the thread resumes, you change the text again, causing it to appear as if the text was never set before.
Edit:
If you want to fix it, the easiest way is to change the sleep call and the second -setText: to be just [label2 performSelector:@selector(setText:) withObject:[NSString stringWithFormat:@"Whatever"] afterDelay:1.0];.
Comment: It´s taking place in an Instance method (IBAction) user touches a button. I thought that the compiler reads "top to down" I don´t know how I would make 1 variable run before the other hmm..
Answer: You could call:
[self performSelector:@selector(updateLabel) withObject:nil afterDelay:1.0f];

Then have the method updateLabel:
[label2 setText:@"Whatever"];

Answer: My guess would be that the actual screen update hasn't occured yet when you call the sleep() function, so when you update the field again immediately after, that's what you end up seeing on screen.
If you really need to make sure the first string appears on screen before the second one, you're going to have to make sure that the display has actually been updated, not just do sleep().


Inserir icone em uma tabela

Question: tenho o seguinte código em um arquivo .vue:
<template>

    <ModalRegister/>

</template>

Mas ele não funciona, ele interpreta o código como texto e não coloca o icone. Como posso fazer para adicionar um ícone a tabela?
Comment: Como a sua pergunta esta incompleta, a solução genérica é a diretiva [`v-html`](https://vuejs.org/v2/api/#v-html)([#docs](https://vuejs.org/v2/guide/syntax.html#Raw-HTML)). Porém nada disso importa se não conhecermos o código fonte do componente ``. Você poderia mostrar o código deste componente ou [edit] a pergunta para adicionar uma tag com a biblioteca que você está usando?
Answer: Passa um campo fields no data e nele insere uma chave e um label, e no Html cria um slot dentro do b-table com a tag i pegando os valores do data:
<template>

    <ModalRegister/>

        <template slot="opcao" slot-scope="{ item: { opcao} }">

        </template>

</template>

Também troque o nome do campo opção por opcao, pois, isto pode ocasionar erros no Javascript.
Comment: isso não resolveu... continuou com exatamente o mesmo problema
Comment: Estranho, aqui funcionou perfeitamente: https://codepen.io/leandrobeandrade/pen/KKPYVNB
Comment: estranho. mesmo copiando e colando seu codigo, aqui nao vai..

Inserir icone em uma tabela


Integration of $\tan(\frac1x)$

Question: $$\int_{-1}^{1}\tan\left(\frac1x\right) dx$$
How do I proceed? Please help.
Comment: How do you even know that the function is integrable? I do not know which integral(Riemann/Lebesgue) you are dealing with, but this function is unbounded at various points in the given domain. If it happens to somehow exist, then it can only be $0$, because the function $\tan \frac 1x$ is an odd function wherever defined.
Comment: why is this $$\partial x$$? and not $dx$
Comment: This integral has a Cauchy principal value, which is $0. \qquad$
Comment: Please remember that you can choose an aswer among the given is the OP is solved, more details here https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work
Answer: Hint. The function  $\tan(1/x)$ is not integrable in a neighbourhood of $\frac{2}{(2k+1)\pi}\in [-1,1]$ for all $k\in\mathbb{Z}$ because as $x\to \frac{2}{(2k+1)\pi}$
$$\tan(1/x)\sim \frac{C_k}{x-\frac{2}{(2k+1)\pi}}.$$
Comment: Thanks for the explanation
Answer: Note that for $x=\frac{2}{\pi}+h$ with $h\to 0$
$$\tan\frac1x=\tan\frac1{\frac{2}{\pi}+h}=\tan\left[\left(\frac{2}{\pi}+h\right)^{-1}\right]=\\\tan\left[\frac{\pi}2\left(1+\frac{\pi h}{2}\right)^{-1}\right]=\tan\left[\frac{\pi}2\left(1-\frac{\pi h}{2}+o(h)\right)\right]=\tan{\left(\frac{\pi}2-\frac{\pi^2 h}{4}+o(h)\right)}=\frac1{\tan{\left(\frac{\pi^2 h}{4}+o(h)\right)}}\sim\frac1{\frac{\pi^2 h}{4}}$$
and thus the integral does not converge.
Comment: Now it is correct.

Integration of $\tan(\frac1x)$


jQuery Object Serialization

Question: If I've for example an object like:
{start: 1, end: 2, someString="someStringValue"}

Is there any simple way to serialize it into a string of data? Example:
start=1&end=2&someString=someStringValue

Thanks.
Answer: You can use the param() function:
var str = jQuery.param({start: 1, end: 2, someString: "someStringValue"});

jQuery Object Serialization


Significance of explanatory variables in Bayesian models

Question: I was wondering if there is a general way to handle parameters of which posterior distributions include zero.
Should one remove these parameters and refit the model?
E.g.
You fit a regression model y = N(a + B_1*x_1 + B_2*x2,sigma).
Now, B_2's posterior includes zero, maybe p(B_2 = 0) = 10%. Should one consider B_2 insignificant, throw it out of the model and refit?
Comment: With a continuous prior, we always have $P(\beta_2=0)=0$... Do you mean that $0$ belongs to a certain confidence region on $\beta_2$?
Comment: Yes.  e.g  the posterior on B_2 could be N(0.5,0.5)
Comment: So what i'm asking is, is there any general way of handling insignificant parameters for bayesian models. For example if 0 is inside a 95% credible interval for a certain parameter, should one keep it in the model?
Answer: Yes, but it does not use the idea of "significance."  Indeed, it is not clear at all that zero being inside the interval is meaningful in Bayesian methods as an idea.  For Frequentist models the null is held to be true and so if $\beta=0$ then that implies that if the null is not falsified then the null can be treated as provisionally true.
Instead, in Bayesian methods, model selection is the rough equivalent to variable significance testing.  Consider, for example, three variables $\{a,b,c\}$ being used to estimate $y$.  Assuming some simple form, the possible combinations of  variables that matter are $\{(a),(b),(c),(a,b),(a,c),(b,c),(a,b,c)\}.$
For simplicity, let's assume the $P(Model=(a,b)\to{y})\gg{P}(Model\ne(a,b)\to{y})$ so $P(Model=(a,b)\to{y})\gg{P}(Model=(a,b,c)\to{y})$.  The difference is that $c$ is missing from the best model, so this is similar to saying $c$ is not significant.  Notice that there is no requirement that $c$ is near zero.
Answer: Even in frequentist model building using a criterion of $p\leq 0.05$ for a whether a parameter should be in a model is not in general a useful approach. It may to some extent be reasonable for judging whether a variable is associated with the outcome (when there are multiple parameters there is clearly a multiplicity problem when doing so). However, it is not appropriate to remove such a variable from the model (either based on whether some value is in the posterior credible interval, some model probability or the like), simply re-fit it and then make statements based on the remaining model (i.e. do model selection and then do inference as if no model selection had occurred) - whether these statements are about the association of the remaining variables with the outcome, about prediction or any other thing. When you are in a Bayesian framework this does not become any more appropriate.
Many of the same strategies as in frequentist inference can be considered in a Bayesian setting when there is model uncertainty. E.g. Bayesian model averaging with priors given to each model, various approximations to a full Bayesian model averaging (e.g. model weights based on $\exp(-\text{BIC}/2)$, using shrinkage priors like the horseshoe etc.), methods that can potentially set coefficients exactly to zero (mostly maximum-a-posteriori methods), cross-validation and so on.


parallel lines (cluster) in PCA plots (PC1 vs PC2)

Question: There are about 20 subjects, 3 treatment groups, and 1000+ genes in my data; the 1000+ genes were processed in two batches. Could anyone comment on why I am seeing parallel lines/clusters in the PCA plots? The plots strike me as funny because

The way the analyte was processed shouldn't differ by batch. But why am I seeing two clusters that are perfectly aligned with batch?

PCA doesn't create lines, so I think the lines represent some hidden, non-random pattern in the original data that are revealed by PCA after transformation. What kind of raw data would become lines after running PCA?

.

Also, "lines" in the PCA plot suggest PC1 and PC2 are linearly correlated...but isn't PC1 supposed to orthogonal to PC2?
Answer:
The way the analyte was processed shouldn't differ by batch.

That's always the hope, but it's seldom the case in practice. Correction for batch effects has been a critical part of gene-expression analysis going back to ancient times with spotted microarrays.

why am I seeing two clusters that are perfectly aligned with batch?

Although you don't say what software you used to produce these plots, I infer that PCA was done separately for each sample. Then the PC2 magnitudes were plotted against the PC1 magnitudes sample-by-sample. The two clusters very strongly suggest a batch difference, however much you might have hoped not to have one.

What kind of raw data would become lines after running PCA?

Your coloring by treatment helps to explain that. In each batch, samples with treatment 1 tend to have points toward the top right while those with treatment 2 tend to have points toward the bottom left. That suggests that treatments and their associated differences in gene expression account for what you see. Versus treatment 0, both PC1 and PC2 increase under treatment 1; they both decrease versus treatment 0 under treatment 2.

isn't PC1 supposed to orthogonal to PC2?

The orthogonality is with respect to the principal component vectors, linear combinations of the gene-expression values in this case. Within any PCA, the gene-expression vector for PC1 is orthogonal to that of PC2.
What you plot, however, are magnitudes of PC2 versus PC1 among different samples. That's an important part of quality control in this type of study, but such plots need not have any particular shape.


Linearity of system of differential equations?

Question: I am learning how to solve differential equations (ordinary and partial)and why they are so important for physics.One thing I have noticed so far is that we know so little on the nature of the solutions of a differential equation , only very few forms of differential equations are solvable and even less forms of systems of differential equations are solvable.
I have always wondered.Small changes in the starting conditions of a system cause big changes only if the system isnt linear.Can small changes in the coefficients of the terms of a system of differential equations cause huge changes in the solution?Is there any related research going on?
Comment: Even for a linear differential equation, small changes in the initial conditions can cause big changes eventually.  Try $dx/dt = x$ and compare initial conditions $x(0) = 0$, $x(0) = \epsilon$ and $x(0) = -\epsilon$.
Comment: Your question is interesting but too broad. The short answer is yes, but it really depends on a lot of factors. If you want to learn more, read some books related to Mathematical Physics. Differential equations are about the rate of change and if you look around, not many things are static in this world. Even our galaxy is moving.
Comment: There is perturbation theory where small changes in the equation produce, over fixed time intervals, small changes in the solution. And the other extreme of singular perturbation, where a small change in the leading order coefficient produces short phases of rapid changes.
Answer: Indeed, I have never used analytical solution of differential equations in practice or at least for engineering application. As you pointed out, only the simplest problems have known solutions and these are nowhere near the complex problems we face in real world.
Most of the time, engineers resort to empirical or numerical solutions. Empirical solutions come from experiments and numerical solutions are obtained through simulations such as Finite Element Method (FEM), Finite Volume Method (FVM), etc.. As my mentor told me, if we waited for analytical solutions, we wouldn't have airplanes for another couple of centuries.
As for your question, there are plenty of researches in that field e.g. sensitivity analysis, stochastic model, etc.. For example, one may study how much change in structural beam's thickness (related to coefficient of DE) affect overal structure's thickness.


View mode template for user-profile.tpl.php?

Question: I can set up a view mode for the user profile, but I don't know how to create a template targeting it. user-profile.tpl.php is the template used, but I can't figure out how to make a view-mode targeted version of it.
Any suggestion?
Comment: What does devel_themer tell you? http://drupal.org/project/devel_themer Also, is there any reason you can't use display suite to achieve what you're trying to do with view modes instead of .tpl.php files?
Answer: You already figured out how to create an additional view mode for the user entity:
/**
 * Implements hook entity info alter
 * Adds additional view mode for user entity
 */
function MYCUSTOMMODULE_entity_info_alter(&$entity_info) {
  $entity_info['user']['view modes']['teaser'] = array(
      'label' => t('Teaser'),
      'custom settings' => TRUE,
  );
}

Now you can define theme suggestions for that view mode using HOOK_preprocess_user_profile:
/**
* Implements HOOK_preprocess_user_profile()
* Adds theme suggestions for the user view mode teaser
*/
function MYCUSTOMMODULE_preprocess_user_profile(&$vars) {
  if ($vars['elements']['#view_mode'] == 'teaser') {
    $vars['theme_hook_suggestions'][] = 'user_profile__teaser';
  }

After clearing the caches Drupal will search in the theme folder for a file called user-profile--teaser.tpl.php, which could look like this example*:

  <?php print render($user_profile['field_last_name'][0]); ?>

<?php print render($user_profile['field_user_picture'][0]); ?>

    <?php print render($user_profile['field_biography']); ?>
    <?php print render($user_profile['field_birthdate']); ?>
    <?php print render($user_profile['field_nationality']); ?>

(* actual code will depend on the fields you defined for the user profile)


What is an indeterminate in a polynomial ring?

Question: I am currently studying polynomial ring. I have a basic doubt. What is $x$ in a polynomial?
A polynomial is an expression $\sum_{k = 0}^n a_k x^k$, where $n,k \in \mathbb{N}$ and $a_k \in R$ where $R$ is a ring. Here $x$ is considered as an indeterminate. Can you please explain what an indeterminate is with some examples? What is its definitions and properties ?
I am studying the book of Dummit and Foote. I am not getting the explanation there. Similarly Herstein has kept silent also. In the chapter Polynomial Ring of the book Linear Algebra of Hoffman Kunze it is explained a little. $x$ is considered as a vector $( 0, 1, 0, \dots, 0$ $(n$ times $) ) $ and so not an element of the ring or the field on which the polynomial ring is constructed. $x^k$ can also be expressed similarly as a vector having $1$ at the $k$-th position and all other terms are $0$.
In analysis when we consider polynomial function we just use $x$ as a dependent variable may be real or a complex. It may be different in Algebra. Please explain the difference and similarity of the two concepts.
Thanking you very much.
Answer: An indeterminate $x$ over $R$ is simply an element that is trascendental over $R$, that is, such that
$$
a_{0} + a_{1} x + \dots + a_{n} x^{n} = 0
$$
only when $a_{i} = 0$ for all $i$.
The construction with sequences you are mentioning is a safe method to construct an indeterminate over any (commutative) ring.
You are surely aware that over a finite field there are pairs of distinct polynomials that induce the same function. For instance, if $F$ is a field with $q$ elements, the polynomial $x^{q} - x$ evaluates to zero for all elements of $F$, exactly like the zero polynomial. That's why the approach via functions is not adequate in these situations.
Comment: If you say "element", the next question would be "element of what?"  I'd rather say "symbol".  There is really no need to represent it as something more concrete than that.
Comment: @Samprity, but I already did! Please check http://en.wikipedia.org/wiki/Algebraic_element
Comment: @Samprity He defined "transcendental" in the very same sentence where he used it.
Comment: Let me study a little. I am very now with this subject.
Comment: @RobertIsrael, I have noted your comment, thanks, let me think a bit before answering.
Comment: Thank you all. I am getting it. Algebraic number (element) and trancendental element are same. i.e. solution of an algebraic equation.
Comment: Very nice Andreas +1
Comment: @AndreasCaranti do u now have an answer for Robert Israel question?
Comment: or @RobertIsrael ? (if it is a symbol, do you mean the logical definition of a symbol ?)
Comment: @AndreasCaranti I think you ought to add that the $a_i's$ must all be in $R$
Comment: To answer myself, symbol should be defined in some mathematical logic books.
Answer: There are two differents aspects of polynoms : in algebra, polynoms can be defined with sequences $a_0,a_1,...$ such as $a_n=0$ below a given rank. With this definition, you can define laws on your sequences in order to have an algebra. That is in this case that $x$ is a "vector" that represents the polynom $0 + X + 0\cdot X^2 + ...$ so this is the vector $0,1,0,0,...$.
In analysis, polynoms are only usuals fonctions, that have a given kind of formula.In this case the indeterminate is only the variable of the function.
 The similarity of the concepts is that if $R$ is principal and infinite (i don't know if it is optimal),the application from $R[X]$ to $R[x]$ (the second set is seen as a subset of $\mathcal F(R,R)$) is an isomorphism between algebras (and rings a fortiori).
Indeed, this application is obviously a surjective morphism. It is injective because the kernel is trivial. In order to prove it, you need to use ideals and show that you can factorize your polynom an infinity of times if he is in the kernel.


The body might complete normally, causing 'null' to be returned, but the return type, 'Widget', is a potentially non-nullable type?

Question: I have this error in my code before the { (builde:(context,snapshot)
buildSearchresult() {
    return FutureBuilder(
        future: searchresultfuture,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return CircularProgress();
          }

        });
  }

Comment: @HasanAlyazidi can you help me with this please
Answer: The builder must always return a widget. However, in your code, if the condition !snapshot.hasData is not satisfied, the builder returns null. So you should return a widget outside this condition:
buildSearchresult() {
    return FutureBuilder(
        future: searchresultfuture,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return CircularProgress();
          }
          return Container(); // The widget containing your data
        });
  }

Answer: Possible duplicate.
You are returning widget only when you don't have data.
you need to return widget on every possible case, like

error
on data
no data
waiting

You can also simplify by returning default widget others state.
builder: (context, snapshot) {
  if (snapshot.connectionState == ConnectionState.waiting) {
 /// return your widget while loadling
 } else if (snapshot.hasError) {
 /// return your widget based on error
  } else if (snapshot.hasData) {
 /// return your widget while have data
  } else if (!snapshot.hasData) {
 /// return your widget while there is no data
  } else {
 /// return  widget
  }
},

Answer: You forgot return from your FutureBuilder().
The return you have is just for your if statement not FutureBuilder().
Use:
buildSearchresult() {
    return FutureBuilder(
        future: searchresultfuture,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return CircularProgress();
          }
          return ...     // add this to return something.

        });
  }

See a similar question here for more info.