Generics function call not compiling in java 8 extending multiple interfaces

Question: Running Java 1.8
JavaSE-1.8 (jdk1.8.0_20)
This class:
public class SimpleQuestion {

    public static void main(String[] args) {
        DoNothing();
        DoNothing2();
        DoNothing3();
        DoNothing4();
    }

    public interface Interface1 {
        public void go();
    }

    public interface Interface2<X> {
        public X go2();
    }

    private static <X, T extends Interface2<X> & Interface1> void DoNothing() {
        return;
    }

    private static <X, T extends Interface2 & Interface1> void DoNothing2() {
        return;
    }

    private static <X, T extends Interface2<X>> void DoNothing3() {
        return;
    }

    private static <T extends Interface2<T> & Interface1> void DoNothing4() {
        return;
    }

}

gives the compile error:
The method DoNothing() in the type SimpleQuestion is not applicable for the arguments ()
Why that one and not DoNothing2,3, and 4?
Comment: It fails in Eclipse. Oracle compiler works for me. I cry bug!
Comment: Why do all the `void` methods have a `return ;` statement? Also, `DoNothing2()` method will cause a compiler error (*untested* but based on what I see since `Interface2` hasn't been *bounded*).
Comment: However, it works if you explicitly provide type arguments.
Comment: Compiles fine for me in Java7; possibly a bug in the compiler/IDE you're using
Comment: I don't know what you are saying, it is working for me in java8 as well as java7. There might be some problem on your softwares or may be you are doing some other mistake.
Comment: The funny thing here is that Eclipse's auto-completion does not provide any argument stub when you select `doNothing()`, and then cries at you because there is no argument.
Comment: https://bugs.eclipse.org/bugs/show_bug.cgi?id=446223
Answer: The error message appears to be referring to a failure of the algorithm defined in section 18.5.1 of the spec.
For DoNothing, the algorithm proceeds as follows (using the terminology from the above link):

The type parameters are
P1 = X
P2 = T extends Interface2<X> & Interface1
and I'll use a1 and a2 for the corresponding inference variables.
The initial bound set is
B0 = {a1 <: Object, a2 <: Interface2<a1>, a2 <: Interface1}
There are no arguments, so no extra bounds are added at this point (B2 = B0).
There is a dependency of a2 on a1, so we try to resolve a1 first. It has a proper upper bound of Object, so we instantiate it to this. Incorporating a1 = Object involves adding the bound
a2 <: Interface2<Object>
Next we resolve a2. This now has two proper upper bounds, so we instantiate a2 to their glb:
a2 = Interface2<Object> & Interface1
Every variable now has an instantiation, so resolution has succeeded.

Hence, contrary to the error message, the invocation of DoNothing ought to be applicable. This appears to be a bug in your Java compiler.


All European World Cup semifinal

Question: With Brazil and Uruguay, the only non European teams in the quarter finals of the 2018 World Cup out of the competitions on the first day of the quarter finals, all remaining teams are European. France and Belgium are already in the semi finals matches after beating Uruguay and Brazil respectively. On the second day of the quarter finals, Russia plays Croatia, and England plays Sweden. This guarantees the last 4 teams standing to be from Europe.
Has all semi finalist of a world cup all been from Europe before? Or more generally have all semi finalist qualified from the same continent? Since all other continents get maximum of 5 seeds (and that would have be even less years ago) I'm assuming this could have only happened for European teams before.
Comment: You are right with your final assumption: Europe was always among the semi-finalists. Furthermore, there was at least one European finalist except in 1930 and 1950, AFAIK
Comment: in 1950 world cup there wasn't a final match but it was a final round with Brazil, Uruguay, Spain and Sweden.
Answer: This will be the fifth (5) time that we will have all European semi final in a world cup. Other 4 times are as follows:

1934 FIFA World Cup1: Italy, Austria, Czechoslovakia, Germany
1966 FIFA World Cup2: West Germany, Soviet Union, England, Portugal
1982 FIFA World Cup3: Poland, Italy, West Germany, France
2006 FIFA World Cup4: Germany, Italy, Portugal, France

Note: Haven't manually checked data for all world cup. Answering on the basis of this line in 2006 FIFA World Cup Wikipedia article:

With Argentina and Brazil eliminated in the quarter-finals, an all-European semi-final line up was completed for only the fourth time (after the 1934, 1966 and 1982 tournaments).
Comment: Fun fact: 1934 was All-European from quarter finals. It was a straight knockout competition of 16 teams (started directly as Round of 16) and all 4 non-european teams  lost their first game.

All European World Cup semifinal


Tem uma forma melhor de formatar valor com espaço depois do simbolo da moeda?

Question: Bom dia !
Estou com uma necessidade de formatar o valor com um espaço depois do simbolo da moeda no Oracle, eu consegui usando da forma abaixo:
select to_char('0','L')||' '||ltrim(to_char('1235675430,12','999G999G999G999G999G990D99') ) from dual;

Existe uma forma melhor de fazer, em vez de fazer dessa forma que fiz ?
Answer: Fiz da seguinte forma, utilizando o FM para tirar os espaços:
SELECT 'R$ '||to_char('1235675430,12','FM999G999G999G999D99') FROM DUAL;


Is there any upfront cost for Azure SQL Database Reserve Capacity Monthly Pay option?

Question: Planning to go with Azure reserved capacity for SQL Databases. Azure price calculator not showing any option to get the pricing monthly as it shows like for virtual machines.
Wants to know whether monthly option is available for SQL Databases reserved capacity and is there any upfront cost involved.
Answer: When you sign up for a reservation you select whether you want to pay for it all up front, or on a monthly basis. The price is the same whichever option you choose. If  you choose the monthly option you are committed to paying the monthly fee for 1 or 3 years depending on the length of your reservation.


Atribuir retorno de função a uma variável usando angularjs $promise

Question: Tenho um angular.factory que retorna dados de json. Dentro de um controller invoco o mesmo para pegar os dados, a questão é que ao invocar o mesmo dentro do controller o objeto existe apenas se usar um console.log, se mandar atribuir para uma variável a mesma fica vazia.
Alguém poderia me ajudar?
//Factory
app.factory('dataLoad', function($http, $q) {
     return {
         getContent: function() {
            var deferred = $q.defer();

            $http.get('data-json.php')
            .success(function(data) {
                deferred.resolve(data);
            })
            .error(function() {
                deferred.reject();
            });

            return deferred.promise;
        }
    }
});

Controller:
$scope.node = [];

dataLoad.getContent().then(
    function(data) {
        //Objeto é impresso normalmente
        console.log(data);

        //nulo
        $scope.node = data;
    }
);

console.log($scope.node);

Answer: O que acontece é o seguinte, o seu getContent é uma função assíncrona, então quando você faz o console.log($scope.node) o promise ainda não estava resolvido.
Quando alguma atribuição for feita dentro de um promise ela nunca estará disponível imediatamente mas somente quando o promise for resolvido.
Tente utilizar um $watch para testar e ver o que acontece.
EX:
$scope.node = [];

dataLoad.getContent().then(
  function(data) {
      //Objeto é impresso normalmente
      console.log(data);

      //nulo
      $scope.node = data;
  }
);
$scope.$watch('node', function(new_value, old_value){
  console.log($scope.node, new_value, old_value);
})

Comment: Usei o $watch e os dados agora estão presentes. No caso sempre terei que usar watch para pegar os dados?
Comment: Se você mandar imprimir na view **{{node}}** ele vai funcionar sem o **$watch** porque o angular faz um **bind** dessa propriedade, a questão é que o **console.log** é executado antes do promise ser resolvido. O que você precisa fazer realmente?
Comment: Daniel, preciso atribuir o retorno para uma variavel, pois irei chamar o factory N vezes e com o retorno irei chamar outro método para exibir os dados.
Comment: Acredito que o correto então seria chamar o seu método dentro do **.then** em vez de atribuir a uma variável para depois chamar o método.
Comment: Valeu Daniel. Assunto resolvido com o código que mandou.


Getting a sum via Green's function

Question: Consider the following question:

Consider the real Sturm-Liouville problem
$$
\mathcal{L} y(x)=-\left(p(x) y^{\prime}\right)^{\prime}+q(x) y=\lambda r(x) y
$$
with the boundary conditions $y(a)=y(b)=0$, where $p, q$ and $r$ are continuous and positive on $[a, b]$. Show that, with suitable choices of inner product and normalisation, the eigenfunctions $y_n(x), \quad n=1,2,3 \ldots$, form an orthonormal set.
Hence show that the corresponding Green's function $G(x, \xi)$ satisfying
$$
(\mathcal{L}-\mu r(x)) G(x, \xi)=\delta(x-\xi)
$$
where $\mu$ is not an eigenvalue, is
$$
G(x, \xi)=\sum_{n=1}^{\infty} \frac{y_n(x) y_n(\xi)}{\lambda_n-\mu},
$$
where $\lambda_n$ is the eigenvalue corresponding to $y_n$.
Find the Green's function in the case where
$$
\mathcal{L} y \equiv y^{\prime \prime},
$$
with boundary conditions $y(0)=y(\pi)=0$, and deduce, by suitable choice of $\mu$, that
$$
\sum_{n=0}^{\infty} \frac{1}{(2 n+1)^2}=\frac{\pi^2}{8}
$$

I showed that the desired Green's function is
$$G(x,\xi)= \sum_{n=0}^{\infty} \frac{2}{\pi(-\mu -n)} \cos (n x) \cos (\xi n).$$
However, I am unsure as how to proceed. I tried setting up a problem with
$$
(\mathcal{L} -\mu)y= f(x)
$$
for $f$ being $x,\sin ,\cos$ and then trying to match the analytic solution with the one from Green's function, however, nothing worked. Could someone point me in the right direction?
Comment: I think the eigenfunctions are $\sin$ , not $\cos$ ...
Comment: Also the eigenvalues are going to be $n^2$, not $n$
Comment: Ah ok. I see what's going on. You can set $x=\xi=\pi/2$ and set $\mu=0$ to get $G(\pi/2;\pi/2\mid 0)=\sum_{n=1}^\infty \frac{1}{n^2}$. Using your expression for $G$ you can deduce $G(\pi/2;\pi/2\mid 0)=\sum_{n=1}^\infty \frac{1}{n^2}=\pi^2/6$ from which you can deduce (by splitting into even+odd integers) that $\sum_{n~\text{odd}}\frac{1}{n^2}=\pi^2/8$.
Comment: The problem is quite misleading, because as written it seems like you should be getting $\sum_{k=0}^\infty \frac{1}{(2k+1)^2}$ falling directly out of the problem, when in reality you solve the Basel problem first and then deduce the odd sum by simple algebra.
Comment: Would you mind uploading a picture of the original exercise? Something just seems off about this
Comment: :@K.defaoite of course. This is from an exam paper https://www.maths.cam.ac.uk/undergrad/pastpapers/files/2002/PaperIB_3.pdf . This is question 12 on page 6.
Comment: Hi, I think that you are right. However, I still don't see how to proceed. Any ideas? I will edit the question shortly.
Comment: Unfortunately I am in the same boat, not sure how to proceed. I'll give it some more thought while I'm on the bus.
Comment: I agree, thank you for writing this. Feel free to post it as an answer and I will gladly accept it. Just to clarify, how does one know the value of the sum? I thought that we are supposed to use Green's function to construct a series solution and then match it with a closed form one, by which I mean some standard function that is not expanded.
Comment: Actually no, I was wrong. Notice that $\sin(n\pi / 2)$ is zero for even $n$. So in fact all you get is the odd terms. I will show this in my answer.
Answer: I'll assume from the start that $r=1$.

You know that the Green's function for the linear operator $\mathscr L-\mu$ where
$$(\mathscr L y)(x)=-\mathrm D(py')(x)+qy$$
Is
$$G(x;\xi\mid \mu)=\sum_{n=1}^\infty\frac{y_n(x)y_n(\xi)}{\lambda_n-\mu}$$
I.e, it is the unique solution of the equation
$$(\mathscr Ly)(x)-\mu y(x)=\delta(x-\xi)$$
With homgeneous Dirichlet BCs.
Here $\{(y_n,\lambda_n)\}_{n\in\mathbb N}$ are the nontrivial orthonormal eigenfunctions and eigenvalues of the operator $\mathscr L$, that is they satisfy
$$\mathscr Ly_n=\lambda_ny_n \\ \langle y_m,y_n\rangle=\int_a^by_m(x)y_n(x)\mathrm dx=\delta_{m,n}$$
In the case of $p=1$ and $q=0$, and BCs $y(0)=y(\pi)=0$ you know that the eigenfunctions and eigenvalues are (The scaling is important here!)
$$\lambda_n=n^2 \\ y_n(x)=\sqrt{\frac{2}{\pi}}\sin(nx)$$
Hence, your Green's function is
$$G(x;\xi\mid \mu)=\frac{2}{\pi}\sum_{n=1}^\infty \frac{\sin(nx)\sin(n\xi)}{n^2-\mu}$$
So, we could write
$$\sum_{n=1}^\infty\frac{\sin(n\pi/2)\sin(n\pi/2)}{n^2}=\sum_{n~\text{odd}}\frac{1}{n^2}=\frac{\pi}{2}G(\pi/2;\pi/2\mid 0)$$
However, we also know (link1,link2) that, given functions $u,v$ that nontrivially satisfy the equation $\mathscr L y=0$ with $u(a)=0~,~v(b)=0$ that our Green's function (with $\mu=0$) may be expressed as
$$G(x;\xi)=\begin{cases}\frac{u(x)v(\xi)}{p(\xi)W(\xi)} & x<\xi \\ \frac{v(x)u(\xi)}{p(\xi)W(\xi)} & x>\xi\end{cases}$$
Where $W=uv'-vu'$.
Again in our case taking $p=1,q=0$ we can see that our fundamental solutions are
$$u(x)=x~~,~~v(x)=\pi-x$$
Hence
$$G(x;\xi\mid 0)=\frac{1}{\pi}\begin{cases}x(\pi-\xi) & x<\xi \\ \xi(x-\pi) & x>\xi\end{cases}$$
Therefore
$$\frac{\pi}{2}G(\pi/2;\pi/2\mid 0)  =\frac{\pi}{2}~\frac{1}{\pi}~\frac{\pi}{2}\left(\pi-\frac{\pi}{2}\right)=\pi^2/8$$
Hence
$$\sum_{n~\text{odd}}\frac{1}{n^2}=\frac{\pi^2}{8}$$
Done.

Additionally, this also allows you to work out
$$\sum_{n\in\mathbb N}\frac{1}{n^2}=\sum_{n~\text{even}}\frac{1}{n^2}+\sum_{n~\text{odd}}\frac{1}{n^2} \\ \sum_{n=1}^\infty\frac{1}{n^2}=\sum_{k=1}^\infty \frac{1}{(2k)^2}+\sum_{n~\text{odd}}\frac{1}{n^2} \\ \implies \left(1-\frac{1}{4}\right)\sum_{n=1}^\infty \frac{1}{n^2}=\sum_{n~\text{odd}}\frac{1}{n^2}=\pi^2/8 \\ \implies \sum_{n=1}^\infty\frac{1}{n^2}=\pi^2/6.$$
Comment: Notice that the sum over the integers reduces to a sum over ODD integers because $\sin(n\pi/2)$ is zero when $n$ is odd!
Comment: @MathsWizzard It doesn't make any difference, but good point.\
Comment: Excellent answer! Thank you very much for all the help.
Comment: Just a quick question, when you found the eigen functions is there any specific reason you picked the positive square root?

Getting a sum via Green's function


Minimal polynomial of the element $1+\sqrt[3]{2}+\sqrt[3]{4}$ Over $Q$

Question: I guess $Q(1+\sqrt[3]{2}+\sqrt[3]{4}) = Q(\sqrt[3]{2})$ hence degree of minimal polynomial should be 3. But I am not able to see this.
Comment: https://math.stackexchange.com/questions/95918/minimal-polynomial-of-1-21-3-41-3/95923#95923
Answer: The degree is at most $3$, so the elements $1$, $\alpha$, $\alpha^2$ and $\alpha^3$ are linearly dependent over $\Bbb{Q}$. Compute these powers and find the linear dependence by basic linear algebra.
Alternatively note that
$$(1+\sqrt[3]{2}+\sqrt[3]{4})(\sqrt[3]{2}-1)=1,$$
and the minimal polynomial of $\sqrt[3]{2}-1$ is clearly
$$(x+1)^3-2=x^3+3x^2+3x-1,$$
so the minimal polynomial of your element is
$$-x^3((x^{-1}+1)^3-2)=x^3-3x^2-3x-1.$$
Answer: $1+\sqrt[3]2+\sqrt[3]4$ is an eigenvalue of $A=\pmatrix{1&1&1\\2&1&1\\2&2&1}$.
In fact
$$\pmatrix{1&1&1\\2&1&1\\2&2&1}\pmatrix{1\\\sqrt[3]2\\\sqrt[3]4}
=(1+\sqrt[3]2+\sqrt[3]4)
\pmatrix{1\\\sqrt[3]2\\\sqrt[3]4}.$$
So just compute the characteristic polynomial of $A$ to get the minimum polynomial of
$1+\sqrt[3]2+\sqrt[3]4$.


How to add a udf who's parameter is a table name

Question: I want to add a udf to calcite. The udf's parameter is a table name, and it will return a varchar value. Are there any sample for this? Thanks.
My test sql is:
SELECT MYTEST22(a), MYTEST(a), MYTEST1(a), COUNT(*)
FROM alisis.table1
WHERE a=max_dt(alisis.table1)
GROUP BY MYTEST22(a),MYTEST(a),MYTEST1(a)

max_dt is the function I want to add.
Comment: Please [edit] your question to show [the code you have so far](http://whathaveyoutried.com).  You should include at least an outline (but preferably a [mcve]) of the code that you are having problems with, then we can try to help with the specific problem. You should also read [ask].
Answer: I don't know what your want to do, could you make a clear explanation?
No function can accept table as parameter, the parameters must have certain type, String, Int or others. So constants and columns can be used as parameters. If your meaning is the table name as a parameter, the sql should be as follows:
SELECT MYTEST22(a), MYTEST(a), MYTEST1(a), COUNT(*)
FROM alisis.table1
WHERE a=max_dt('alisis.table1')
GROUP BY MYTEST22(a),MYTEST(a),MYTEST1(a)

As I known, all functions Calcite (version is 1.11) supported are defined at SqlStdOperatorTable. If you want to support other functions, you can implement a class that extends SqlStdOperatorTable, for example:
public class TestOperatorTable extends SqlStdOperatorTable {
  private static volatile TestOperatorTable instance;
  public static TestOperatorTable instance() {
    if (instance == null) {
      synchronized(TestOperatorTable.class) {
        if (instance == null) {
          instance = new TestOperatorTable();
          // Use reflection to register the expressions stored in public fields.
          instance.init();
        }
      }
    }
    return instance;
  }

  /** Follow add your functions */
  public static SqlFunction LTRIM = new SqlTrimFunction("LTRIM");
}

SqlTrimFunction as follows:
public class SqlTrimFunction extends SqlFunction {
  public SqlTrimFunction(String funcName) {
    super(
      funcName,
      SqlKind.OTHER_FUNCTION,
      ReturnTypes.VARCHAR_2000,  // return type is String
      InferTypes.FIRST_KNOWN,
      OperandTypes.STRING,       // parameter type is String
      SqlFunctionCategory.STRING
    );
  }
}

When you create a SqlValidator, for example SqlValidatorImpl, you should use TestOperatorTable as its first parameter.
Comment: Yes, the function I want to support has the table name as a parameter. My test sql has syntax error . I will try to implement the class . Thank you very mach!
Comment: @fei.chen https://stackoverflow.com/a/44962144/1314077 this may be helpful to add UDF, do not extend SqlStdOperatorTable.


nginx: remove string in $host

Question: server {
    server_name *.com.another.com;
    location / {
        root   /var/www/html/$host;
        index  index.html;
    }
}

On above example, if someone make a request to www.jaja.com.another.com, nginx will look in directory /var/www/html/www.jaja.com.another.com
This is what I need: If someone make a request to www.jaja.com.another.com, I want nginx to look in directory /var/www/html/www.jaja.com
In other words, the $host is www.jaja.com.another.com. I need to remove .another.com in the $host
Nginx string replacement is new to me
Answer: server {
    server_name ~^(?<subdomain>.*)\.another\.com$;
    root /var/www/html/$subdomain;
    index index.html index.htm index.php;
    location ~ \.php$ { <...> }
}

Comment: It's better to leave the root directive in the [server context](http://wiki.nginx.org/Pitfalls#Root_inside_Location_Block)
Answer: Based on this answer:
map $host $directory {

    default www;
    ~*^(?P<subdomain>[a-z0-9\-\.]+)\.com\.another\.com$        $subdomain;
}

server {
    server_name *.com.another.com;

    location / {
        root   /var/www/html/$directory;
        index  index.html;
    }

}

nginx: remove string in $host


Send Decipher / Cipher Object (binary data) with request() to API with multer

Question: We have two API's in Node.js. The first one acts as the main hub, while the other one is used to send emails.
Currently I have some files that are encrypted and stored in the file system of the first API. The files get decrypted with the following function:
decryptFile: function (filePath, callback) {
                var fileName = path.basename(filePath);
                var encryptedFilePath = path.dirname(filePath) + '/' + this.encryptText(fileName);
                // input file
                var fileDecipher = encryptionKeys.crypto.createDecipher(encryptionKeys.algorithm, encryptionKeys.password);
                var r = fs.createReadStream(encryptedFilePath);
                // decrypt content
                r.on("error", function (err) {
                    if (err) {
                        callback(err);
                    }
                });
                return callback(null, r.pipe(fileDecipher));

        }

To send the files we use:
utils.files.decryptFile(fullPath, function (err, decryptedFile) {

requestOptions = {
            url: pushAPIURL + 'email/send',
            method: "POST",
            formData: {
               attachments: [decryptedFile]
            },
            headers: {
                authorization: global.PUSHToken
            }
            // json: body
        };
        return request(requestOptions);
});

Due to this we receive:

Error: Part terminated early due to unexpected end of multipart data

on the mail API
Any idea as to what may be missing from the request?
Thanks
Answer: Okay, so after some digging, I had forgotten about the question over here. I posted the solution to my problem inside form-data's GitHub issue's: https://github.com/form-data/form-data/issues/409#issuecomment-432202588
Here is the original answer in case the above is not available anymore:

So the solution to this was thanks to:
  https://github.com/form-data/form-data/issues/356#issue-234978025
It seems indeed related to the missing known length of the stream +
  seemingly some other metadata fields that are missing. On the file
  decryption function, I added the counting of the stream length for
  each chunk:
            let file, length = 0;
            // decrypt content
            r.on("error", function (err) {
                if (err) {
                    callback(err);
                }
            });
            r.on("data", function (chunk) {
                // console.log("data");
                length += chunk.length;
            });
            r.on("end", function () {
                // console.log("end");
                return callback(null, file, fileName, length);
            });
            file = r.pipe(fileDecipher);

Then, on the file that is sending the request we add the following
utils.files.decryptFile(fullPath, function (err, decryptedFile, filename, >length) {
            decryptedFile.httpVersion = "1.0";
            decryptedFile.name = filename;
            decryptedFile.headers = {'content-length': length};
            requestOptions = {
            url: pushAPIURL + 'email/send',
            method: "POST",
            formData: {
               attachments: [decryptedFile]
            },
            headers: {
                authorization: global.PUSHToken
            }
        };
        return request(requestOptions);
    });


Separate digits AB to A and B inside df pandas

Question: I have a df with some data placed in some bytes. I have the problem that inside the frame there are two bits reserved for a toggle function that does not matter to me, but its affecting the final result of my task.
The byte frame looks like this:
Start bit  0 1 2 3 4 5 6 7
    0      A A A A A A A A
    8      A A
   16      B B B B B B B B
   24      B B         C C

C represents the toggle

My df looks like this:
A   A   B   B
BA  00  11  02
BA  00  11  02
BA  00  11  42
BA  00  11  42
BA  00  11  82
BA  00  11  82
BA  00  11  C2
BA  00  11  C2
BA  00  11  02
BA  00  11  02

I can see that from B the 1st part of the second Byte is cycling, meaning that the 2nd digit is the toggle. I guess or am I wrong? Afterward, this digit (2) changes in my df for 1 & then 0.
Is there a way that I can convert, separate or eliminate the 2nd digit or a way to only take the 1st digit (this case 0). eg. 02 --> 0 and 2 just take the 0. My df afterward is a different number than 0 but the 0,4,8 and C is continuos regardless and the 2 also changes later to 1 and then 0. :)
Answer: For those that look for an answer I consulted with my pillow and we agreed to try the following that actually it worked:
So after putting together the bytes like this:
df['A'] = df.iloc[:,1] + '' + df.iloc[:,0]    #Dominant byte is the second position
df['B'] = df.iloc[:,3] + '' + df.iloc[:,2]

Output:
  A       B
00BA    0211
00BA    0211
00BA    4211
00BA    4211
00BA    8211
00BA    8211
00BA    C211
00BA    C211
00BA    0211
00BA    0211

I did the following:
df['B'] = df['B'].str[1:] #Only take the last three digits of the array

Output:
 A       B
00BA    211
00BA    211
00BA    211
00BA    211
00BA    211
00BA    211
00BA    211
00BA    211
00BA    211
00BA    211


Camuflando endereço remetente num e-mail em PHP

Question: Eu não consigo camuflar o endereço do remetente @qualquercoisa.com, eu sou obrigado a usar o do meu domínio, mas no meu script de envio que eu perdi dava para camuflar, porem eu acho que isso é coisa da hospedagem eu uso kinghost, da outra vez eu não usava a kinghost e não passei trabalho para fazer, tanto que botei no meu código lá, só que quando entra na condição da parte de por o nome que eu quiser, se eu por, não aceita, parece que a hospedagem bloqueia o envio do email, deve ser né, ou tem algum método ???
O código de enviar o html é:
function sendmail() {
    if(!isset($_POST[Submit])) die("Não foi recebido nenhum parâmetro");
    /* Medida preventiva para evitar que outros domínios sejam remetente da sua mensagem. */
    if (eregi('tempsite.ws$|locaweb.com.br$|hospedagemdesites.ws$|websiteseguro.com$', $_SERVER[HTTP_HOST])) {
            $emailsender=trim($_POST['emailremetente']);
    } else {
            $emailsender = "noreply@" . $_SERVER[HTTP_HOST];
    }

    /* Verifica qual é o sistema operacional do servidor para ajustar o cabeçalho de forma correta. Não alterar */
    if(PHP_OS == "Linux") $quebra_linha = "\n";
    elseif(PHP_OS == "WINNT") $quebra_linha = "\r\n";
    else die("Incompatibilidade com Sistema Operacional");

    // Passando os dados obtidos pelo formulário para as variáveis abaixo
    $nomeremetente     = $_POST['nomeremetente'];
    $emailremetente    = trim($_POST['emailremetente']);
    $assunto           = $_POST['assunto'];

    $array_emaildestinatario = array();
    $array_emaildestinatario = explode("\n",trim($_POST['emaildestinatario'])); // separa os emails pelas vírgulas em uma array
    foreach($array_emaildestinatario as $elemento) {
        //pra cada email envia
        /* Montando a mensagem a ser enviada no corpo do e-mail. */
        $mensagemHTML = html();

        /* Montando o cabeçalho da mensagem */
        $headers = "MIME-Version: 1.1".$quebra_linha;
        $headers .= "Content-type: text/html; charset=iso-8859-1".$quebra_linha;
        // Perceba que a linha acima contém "text/html", sem essa linha, a mensagem não chegará formatada.
        $headers .= "From: ".$emailsender.$quebra_linha;
        $headers .= "Return-Path: " . $emailsender . $quebra_linha;

        $headers .= "Reply-To: ".$emailremetente.$quebra_linha;
        // Note que o e-mail do remetente será usado no campo Reply-To (Responder Para)

        /* Enviando a mensagem */
        mail($elemento, $assunto, $mensagemHTML, $headers, "-r". $emailsender);
    }
    /* Mostrando na tela as informações enviadas por e-mail */
    ?>

            Enviando <?php echo count($array_emaildestinatario); ?> e-mails, aguarde um instante...

            De:<?php echo $emailsender; ?>

        <?php
        foreach($array_emaildestinatario as $elemento) {
            echo "
$elemento
";
        }
        ?>

<?php
}

Answer: Deverás falar com o suporte técnico da KingHost para obter uma resposta exata à tua pergunta, mas pelo que vejo na FAQ para configuração do email, o envio de emails requer autenticação o que é indicativo do servidor não ser Open Email Relay.
Servidor que não permite Relay
Ao enviar emails, poder-se-á receber uma mensagem de erro a dar conta que o email não pode ser enviado devido a um bloqueio de retransmissão (relay) por parte do servidor SMTP (Simple Mail Transfer Protocol).
A mensagem de erro exata pode variar, dependendo do servidor mas essencialmente diz-me que o servidor não permite relay, sendo necessário autenticação para proceder ao envio do email e/ou estar a utilizar uma conta existente no servidor para esse efeito.
Servidor Open Email Relay
O que tu estás a tentar fazer requer um servidor configurado como Open Email Relay:

An open mail relay is an SMTP server configured in such a way that it allows anyone on the Internet to send e-mail through it.

Que traduzido:

Um open mail relay é um servidor SMTP configurado de tal forma que permite que qualquer pessoa na Internet possa enviar e-mails através dele.

Notas:
De servidor para servidor as configurações mudam significativamente, mas o comum é o Relay não ser permitido pois acarreta muito problema de segurança e SPAM o que baixa a reputação do servidor em si.
Configurações intermédias também se encontram onde o envio dos emails é feito sem consideração ao FROM: mas na fonte da mensagem está bem explicito quem enviou e geralmente segue com firstname.lastname@example.com apesar de aparecer no FROM: email@example.com.


Retornar dados de um JSON ordenando a partir de uma chave

Question: Tenho um arquivo JSON onde nos registros tenho uma chave que define uma data no seguinte formato: "aaaammdd". Preciso retornar os registros existentes neste arquivo mas ordená-los através desta chave. Como seria isso?
UPDATE:
este é meu arquivo
{
  "241019846088038":{
    "start_time":"20140815",
    "name":"Event 3"
    },
  "244875799004498":{
    "start_time":"20141229",
    "name":"Event 8"
    },
  "288519758006296":{
    "start_time":"20140809",
    "name":"Event 1"
    }      ,
  "576146455831402":{
    "start_time":"20140830",
    "name":"Event 14"
    }
  ,
  "1416493345292145":{
    "start_time":"20140920",
    "name":"Event 2"
    }
}

Comment: Você tem algo tipo `{"20140101":{ ... }, "20140102":{ ... }, ...}` e quer retornar uma lista contendo os objetos, essa lista ordenada pela data. É isso?
Comment: Atualizei minha reposta para se adequar ao seu formato de dados. Não mudou quase nada - só tive que acrescentar um critério de ordenação no `sort`.
Answer: O primeiro passo é criar uma lista onde cada par (chave,valor) esteja representada por um array:
var jsonDecoded = { "241019846088038":{ "start_time":"20140815", "name":"Event 3" }, ... };
var pares = [];

for ( var p in jsonDecoded )
    pares.push([p, jsonDecoded[p]]);

// pares == [ ["241019846088038",{ "start_time":"20140815", "name":"Event 3" }], ... ]

Então você pode ordenar essa lista. Por padrão, o JavaScript ordena arrays primeiro olhando o primeiro elemento, depois o segundo, etc. Como datas no formato aaaammdd podem ser ordenadas lexicograficamente, não é necessário usar nenhum parâmetro especial no sort (Edit: de acordo com o update, como a chave é um campo do próprio registro, é necessário sim estabelecer um critério de ordenação de acordo - ainda que esse critério se beneficie do formato utilizado):
function compararDatas(a, b) {
    return a[1].start_time  b[1].start_time ?  1 : 0;
}
pares.sort(compararDatas);

Se quiser, você pode então obter um array só com as chaves, ou só com os valores:
var chaves = [];
var valores = [];

for ( var i = 0 ; i < pares.length ; i++ ) {
    chaves[i] = pares[i][0];
    valores[i] = pares[i][1];
}

Exemplo no jsFiddle.
Essa é uma solução usando JavaScript puro. Se tiver acesso a uma biblioteca tipo underscore.js, essa tarefa pode ficar bem mais fácil:
var pares = _.pairs(jsonDecoded).sort(compararDatas);
var chaves = _.pluck(pares, 0);
var valores = _.pluck(pares, 1);

Exemplo no jsFiddle. Se você só estiver interessado nos valores dos registros (e não nas chaves), então dá pra fazer em uma única linha:
var valores = _.chain(jsonDecoded).pairs().sort(compararDatas).pluck(1).value();


Comparison test for convergence of Improper Integral

Question: The comparison test works for improper integrals $\int_{a}^{\infty} f(x) \ dx$ where $a\geq 0$.
Supposedly i want to find the convergence of $\int_{-\infty}^{\infty} f(x) \ dx = \int_{-\infty}^{a} f(x) \ dx + \int_{a}^{\infty} f(x) \ dx$.
How do i apply comparison test for $\int_{-\infty}^{a} f(x) \ dx$?
Answer: Suppose that $f(x)\geq 0$ in $(-\infty,a]$. If you find a function $g:(-\infty,a]\longrightarrow\mathbb{R}$ such that $$0\leq f(x)\leq g(x)$$ whose improper integral is convergent
$$\int_{-\infty}^{a}g(x)dx<\infty$$
then
$$\int_{-\infty}^{a}f(x)dx\leq\int_{-\infty}^{a}g(x)dx<\infty$$
Resuming:  If $\ 0\leq f(x)\leq g(x)$, then
1) $\ \displaystyle{\int_{-\infty}^{a}f(x)dx=\infty \Longrightarrow \int_{-\infty}^{a}g(x)dx=\infty}$
2) $\ \displaystyle{\int_{-\infty}^{a}g(x)dx<\infty} \Longrightarrow \displaystyle{\int_{-\infty}^{a}f(x)dx<\infty}$


What is the difference between "content type" and "custom content type"?

Question: Can anyone explain to me the difference between content type and custom content type?
Answer: A content type is a type of node. Node types (aka content types) are generally created through the browser UI. However, they can also be created through code, which people refer generally refer to as a custom content type.
Comment: Then again the D8 docs page with a similar title refer to them as those created in YML: https://www.drupal.org/docs/8/api/entity-api/creating-a-custom-content-type-in-drupal-8. So I think the take away is that _custom_ means whatever you want it to mean, and doesn't have particular significance in Drupal
Comment: _Custom content type_ has always meant _content type created by the user_ in my experience. The docs seem to agree: https://www.drupal.org/docs/7/nodes-content-types-and-fields/create-a-custom-content-type
Comment: Yeah, it's not really an official term. Just whatever a person thinks it is when they refer to it.
Comment: But I thought the custom content type WAS the content created in the UI?? I am hearing "content type" and "custom content type" as synonymous phrases which I why I am getting confused. I thought the custom content type is similar to "custom post types" in WordPress. I know you DONT want to give that kind of control to a user/editor generally which is why I'm thinking allowing a user to make a whole other custom content type might be haphazard down the road. Does anybody have any clarity on my thought process?
Comment: Forget WP that'll confuse things more, you just need to get a handle on basic Drupal terminology... _content type_ is a type of content. _Content_ is a piece of content - an instance of a content type. Anywhere you see the word _Custom_ prepended to _content type_, you can pretty much assume it just means _this one was created by a user, not by a core or contributed module_. Whether that happened through the UI or code is largely irrelevant. Drupal doesn't have an official concept of a _custom_ content type, just content types, the prefix comes from the people who are using it to build things
Comment: I have no idea about wordpress, but you wouldn't give editors permission to create content types, but you would give them permission to create content.
Answer: Custom content type can be used with two different meanings:

Any node type (bundle, or entity bundle, in Drupal 8 terminology) created from the user interface (admin/structure/types/add in Drupal 7 and Drupal 8) from users with the right permissions
Any node type implemented from third-party modules

What is not a custom content type is a content type created from a Drupal core module, or a Drupal core profile. For example, the Forum topic content type is created from the Forum module, while the Article content type is created from the Standard profile.
For the rest, there isn't much difference between a custom content type and a content type: Both can be extended with fields.
There could be a difference between a content type created from a module (core module or third-party module) and a content type created through the user interface: the content type fields that aren't created from the user interface made available from the Field UI module. For example, the Forum module adds to the Forum topic content type a reference field for a vocabulary the module created. Similarly, the Standard profile adds a field to attach an image to nodes of the Article content type.


How to calculate percentage of GPA > 3.5 from two tables?

Question: I have two tables tblStudent and tblTranscript. I want to calculate the percentage of students who have a GPA > 3.5. I have created two queries that give the count of total students with a GPA and total students with a GPA > 3.5.
I don't know how to divide these two tables and multiple them by 100 to get the percentage of students who have a GPA > 3.5.
My queries are:
GPA > 3.5
SELECT COUNT (GPA) FROM (
SELECT avg(Grade) as GPA, studentID from tblTranscript
GROUP BY studentID HAVING avg(Grade) > 3.5)

TotalCountWithGPA
SELECT COUNT (GPA) FROM (
SELECT avg(Grade) as GPA, StudentID FROM tblTranscript
GROUP BY StudentID)

SOLUTION:
SELECT

(COUNT (GPA)
/
(SELECT COUNT(GPA) FROM (SELECT avg(Grade) as GPA, StudentID FROM tblTranscript GROUP BY StudentID)) * 100) as PercentageOfStudents

FROM (SELECT avg(Grade) as GPA, studentID from tblTranscript GROUP BY studentID HAVING avg(Grade) > 3.5)

Answer: Try this,
SELECT
(COUNT (studentID)/(SELECT COUNT(studentID) FROM tblTranscript)) as percentageOfStudents
FROM (
        SELECT avg(Grade) as GPA, studentID from tblTranscript
        GROUP BY studentID HAVING avg(Grade) > 3.5)

Hopefully it would work as you are expecting
Comment: **EDIT**: `(COUNT (studentID)/(SELECT COUNT(studentID) FROM tblTranscript) * 100)`
Comment: Hmm this looks okay but it's not quite right. It's not giving the answer I'm looking for. The total students who have a GPA is 500 and the students with a GPA > 3.5 is 14. So 14/500 = .0028 * 100 = 2.8% but this is yielding .09596%
Answer: I understood your problem now. I could not edit my last answer because of page not found error. Anyway, I have edited my last answer and posted. Check if it works,
SELECT
(COUNT(GPA)/(SELECT COUNT(GPA) FROM (SELECT avg(Grade) as GPA, studentID from tblTranscript)) * 100) as percentageOfStudents
FROM (
        SELECT avg(Grade) as GPA, studentID from tblTranscript
        GROUP BY studentID HAVING avg(Grade) > 3.5)

Comment: It says "Your query does not include the specified expression 'studentID' as part of an aggregate function."
Comment: `(COUNT(GPA)/(SELECT COUNT(GPA) FROM (SELECT avg(Grade) as GPA from tblTranscript))  * 100) as percentageOfStudents`. Replace the first line with this
Comment: My two queries I posted in the quest give the numbers, but I don't know how to write an expression that takes those numbers and divides them and multiply that number by 100
Comment: That results with 1400
Comment: SELECT COUNT(GPA) FROM (SELECT avg(Grade) as GPA from tblTranscript)  this expression is resulting with the count of 1 which is not correct
Comment: Because it is taking the average grade of ALL the grades listed on the Transcript table instead of taking the average GPA for each student and since there is only one GPA for all the grades which is like 3.2 or something the count only returns 1
Comment: you want to divide the number with total students who have GPA and then multiply the output with 100 right?
Comment: I just got the answer by tweaking your expression, but for some reason I can't multiple it by 100 to get the percentage.
Comment: SELECT

COUNT (GPA)
/
(SELECT COUNT(GPA) FROM (SELECT avg(Grade) as GPA, StudentID FROM tblTranscript GROUP BY StudentID))

FROM (SELECT avg(Grade) as GPA, studentID from tblTranscript GROUP BY studentID HAVING avg(Grade) > 3.5)
Comment: Got it: SELECT

(COUNT (GPA)
/
(SELECT COUNT(GPA) FROM (SELECT avg(Grade) as GPA, StudentID FROM tblTranscript GROUP BY StudentID)) * 100) as PercentageOfStudents

FROM (SELECT avg(Grade) as GPA, studentID from tblTranscript GROUP BY studentID HAVING avg(Grade) > 3.5)
Comment: Good to know :)
Answer: MySQL or Access ?
For MySQL you can use this:
SELECT COUNT(GPA > 3.5)/COUNT(GPA)*100 as HIGH_GPA_PERC
FROM(SELECT avg(Grade) as GPA, StudentID
     FROM tblTranscript
     GROUP BY StudentID) t

Comment: The last is not for Access, it's T-SQL.
Comment: When I run the first one I keep getting the result of 100. But it should be 14/500 * 100 = 2.8%
Comment: @ChaCol Which RDBMS are you using ?? And unless the grades are below 4, the AVG(grade) will always be > then 3.5 . Are you sure that's the number you wanna use ?
Comment: @Gustav Actually it's ANSI syntax, should work for almost any DBMS, but you are right, Access uses `SWITCH` instead .
Comment: I'm using tables that my professor gave me. There are 500 grades in this table and they range from 2 - 4 (2, 2.5, 3, 3.5, or 4) and there are several grades in this table per one Student.. so a student may have 10-15 grades. So I'm taking the average student grade and trying to find all of those GPAs that are > 3.5
Comment: Sorry there are over 14,000 grades in the table but 500 students with a GPA
Comment: Are you using MySQL ? If you run `SELECT COUNT(GPA > 3.5) as first, COUNT(GPA) as total FROM (select avg(Grade)..........` What do you get ? @ChaCol


Is $\mathbb{Q}(\sqrt3 i) = \mathbb{Q}(\sqrt3, i)$?

Question: Hi I am a little bit confused by extension fields and splitting fields.
I have an exercise that asks me to find the degree of the extension $E/\mathbb{Q}$, where $E$ is the splitting field of the polynomial $x^4 -2x^2 - 3$.
I found $E = \mathbb{Q}(\sqrt3,i)$ because the polynomial has roots $\pm\sqrt3, \pm i$
Now $\mathbb{Q}(\sqrt3)/\mathbb{Q}$ is a degree $2$ extension, since $x^2 - 3$ is irreducible over $\mathbb{Q}$, and since $i \notin \mathbb{Q}(\sqrt3)$ it follows that $\mathbb{Q}(\sqrt3, i)/\mathbb{Q}(\sqrt3)$ is also a degree $2$ extension, since $x^2 + 1$ is irreducible over  $\mathbb{Q}(\sqrt3)$.
So by the tower law, we have $[E : \mathbb{Q}] = [ E :\mathbb{Q}(\sqrt3)][\mathbb{Q}(\sqrt3):\mathbb{Q}] = 2 * 2 = 4$
But why can't I say, that $\mathbb{Q}(\sqrt3,i) = \mathbb{Q}(\sqrt3 i)$?
Comment: Hint: is $\sqrt{3} \in \mathbb{Q}(\sqrt{-3})$?
Comment: is $i\in\Bbb Q(\sqrt{-3})?$
Comment: Er, $X^2 - 2X - 3 = (X - 3)(X + 1)$. Have you got your polynomial wrong? Also, if the polynomial of degree two, you will only find two roots, so $\pm \sqrt 3, \pm \mathrm i$ won't cut it anyway.
Comment: I'm guessing the polynomial should be $x^4-2x^2-3,$ to have tbose four roots.
Answer: You probably meant $x^4 - 2x^2  - 3$.
As to whether $\mathbb{Q}(\sqrt{3}i) = \mathbb{Q}(\sqrt{3},i)$, they aren't the same. One way to look at this is that $\mathbb{Q}(\sqrt{3},i)$ has a subextension $K = \mathbb{Q}(\sqrt{3})$ which satisfies $\mathbb{Q} \subsetneq K \subsetneq \mathbb{R}$, while
$\mathbb{Q}(\sqrt{3}i)$ is an extension of $\mathbb{Q}$ of degree two (it is the splitting field of $x^2 + 3$) and therefore has no subfields containing $\mathbb{Q}$ other than $\mathbb{Q}$ itself.
Answer: Naïvely, elements of $\mathbb{Q}(\sqrt{3}i)$ should be written $a+b\sqrt{3}i$ where $a,b\in \mathbb{Q}$. You can check that this is, in fact, closed under multiplication. It also clearly contains neither $\sqrt{3}$ or $i$.
Alternatively, note that $(x-\sqrt{3}i)(x+\sqrt{3}i)=x^2+3,$ so $\mathbb{Q}(\sqrt{3}i)$ is the splitting field for this polynomial (this tells you why all elements herein must have the above form and also, why the above sub-ring of $\mathbb{C}$ forms a field).
Comment: Well, $\sqrt{3}i\in E$ and $\mathbb{Q}(\sqrt{3}i)$ is universal among such extensions, so yes.
Comment: Okay, but is $\mathbb{Q}(\sqrt3 i)$ then a subextension of $E/\mathbb{Q} $?


How should memory be freed after an exception is thrown in C++?

Question: I apologize if this question is a duplicate - I searched for a while, but it's possible that my Google-fu just isn't up to snuff.
I am modifying a C++ program that calls into a C library.  The C library allocates a bunch of memory (using malloc()), and the C++ program uses it and then frees it.  The catch is that the C++ program can throw an exception midway through execution, causing the allocated memory to never be freed.
As a (rather contrived) example:
/* old_library.c */
char *allocate_lots() {
    char *mem = (char *)malloc(1024);
    return mem;
}

/* my_prog.cpp */
void my_class::my_func () {
    char *mem = allocate_lots();
    bool problem = use(mem);
    if (problem)
        throw my_exception("Oh noes! This will be caught higher up");
    free(mem);  // Never gets called if problem is true
}

My question is: how ought I to deal with this?  My first idea was to wrap the whole thing in a try/catch block, and in the catch just check and free the memory and re-throw the exception, but this seems graceless and clunky to me (and wouldn't work well if I want to actually catch an exception).  Is there a better way to do it?
EDIT: I probably should have mentioned that we're using g++ 4.2.2, from back in 2007 before std::unique_ptr was introduced.  Chalk it up to corporate inertia.
Comment: Use RAII, problem solved.
Comment: Why can't you just free the memory before throwing the exception?
Answer: Use std::unique_ptr with a custom deleter that calls free:
class free_mem {
public:
    void operator()(char *mem) { free(mem); }
};

void my_class::my_func() {
    std::unique_ptr<char, free_mem> mem = allocate_lots();

Comment: Write your own unique_ptr replacement, then explain to your boss why you spent 2 days debugging a basic language tool that you would have gotten for free if they allowed upgrading. Repeat it until they start weighting the time wasted with outdated tools against the time spent upgrading.
Comment: This would probably be the right answer, except that we're using an old version of g++ (see the edit above).
Answer: Wrap that rascal:
struct malloc_deleter {
  template <typename T>
  void operator () (T* p) const {
    free(p);
  }
};

void my_class::my_func () {
    std::unique_ptr<char[],malloc_deleter> mem{allocate_lots()};
    bool problem = use(mem.get());
    if (problem)
        throw my_exception("Oh noes! This will be caught higher up");
}

Comment: Mmm. Can you explain the use of `char[]`?
Comment: `unique_ptr` is a partial specialization that overloads `operator []` instead of `operator ->` and uses `delete[]` by default (obvously not important here).
Comment: I'm eternally confused with that, then. I thought `shared_ptr` had that. But apparently, they forgot to add the same for `shared_ptr`
Comment: Correct. `boost::shared_ptr` has a `T[]` specialization, but it was added after the standard swallowed `shared_ptr` in TR1. (See [this thread](http://boost.2283326.n4.nabble.com/shared-array-Why-not-in-C-11-td4649418.html)).
Comment: This would probably be the right answer, except that we're using an old version of g++ (see the edit above).
Answer: You should make sure that you don't throw until after you have freed the memory - or that you use a suitable smart pointer structure to store the mem, such that when the throw happens, and the stack unwinds, the mem gets freed.
Answer: Since you're using an old compiler version that doesn't have unique_ptr, you can write your RAII wrapper yourself:
class ResourceWrapper {
public:
    ResourceWrapper(char* ptr) : m_ptr(ptr) {}
    ~ResourceWrapper() { free(m_ptr); }
    // whatever getters suit you, at the very least:
    char* get() const { return m_ptr; }
private:
    char* const m_ptr;
};

void my_class::my_func () {
    ResourceWrapper mem(allocate_lots());
    bool problem = use(mem.get());
    if (problem)
        throw my_exception("Oh noes! This will be caught higher up");
}

Just make sure not to allow copy/assignment even implicitly (which is why I made m_ptr const) or you'd risk ending up with double-freeing your memory ("move" semantics à la auto_ptr are best avoided unless you absolutely need it).
Answer: Since you can't use std::unique_ptr, you could create your own deleter class that would control the lifetime of the pointer in RAII fashion. To keep it simple this example doesn't wrap the actual pointer but exists alongside it; a safer approach would be to make a true smart pointer class.
class AutoFree
{
public:
    AutoFree(void* p) : m_p(p)
    {
    }
    ~AutoFree()
    {
        free(m_p);
    }
private:
    void* m_p;
};

void my_class::my_func () {
    char *mem = allocate_lots();
    AutoFree mem_free(mem);
    bool problem = use(mem);
    if (problem)
        throw my_exception("Oh noes! This will be caught higher up");
}

Answer: Is there any reason not to simply free the memory inside the if clause?
if (problem) {
    free (mem);
    throw my_exception ("Drat!");
}

Comment: Duplication of code, although in this specific case the `free` could really be moved before the conditional altogether. Long-term, there's a danger that someone unaware of what's going on here could insert another `throw` or `return` or call to another function that could throw without handling the fragile resource. RAII protects against the next guy being stupid.
Answer: Use unique_ptr: http://coliru.stacked-crooked.com/view?id=cd3f0fc64d99cc07a2350e2ff9686500-542192d2d8aca3c820c7acc656fa0c68
#include <stdexcept>
#include <iostream>

#include <memory>

/* old_library.c */
char *allocate_lots()
{
    return static_cast<char*>(malloc(1024));
}

struct my_exception : virtual std::exception {
    const char* const msg;
    my_exception(const char* const msg) : msg(msg) {}
    const char* what() const noexcept { return msg; }
};

struct my_class
{
    struct Free { void operator() (char* p) const { free(p); } };
    /* my_prog.cpp */
    void my_func()
    {
        std::unique_ptr<char, Free> mem;

        mem.reset(allocate_lots());
        bool problem = use(mem.get());

        if(problem)
        {
            throw my_exception("Oh noes! This will be caught higher up");
        }
    }

    static bool use(char*) { return true; }
};

int main()
{
    my_class prog;
    prog.my_func();
}

Comment: @Dan replace `unique_ptr` by [`boost::scoped_ptr`](http://www.boost.org/doc/libs/1_54_0/libs/smart_ptr/scoped_ptr.htm) if you don't have it


how to add a home button from css in jquery mobile?

Question: I have a jquery mobile site. Its around 50 html pages , and i need to add in my header a simple home button. Is it possible to add this button from the CSS , or i need to open one by one all the html files and add it?
The button is simple as that :
Home

Also how can i make this button appear on the left side? For some reason it appears on the right.
Also how can i change the theme color of my header from the CSS instead of changing it on every file?
Thank you very much
Comment: you have too many questions in one. It's better to separate your questions.
Answer: Working example: http://jsfiddle.net/Gajotres/ZUYmt/
$(document).on('pageinit',  function(){
    $('Home').button().appendTo('[data-role="header"]');
});

No you cant add a button using only CSS but you can do it with jQuery, example can be found in a working example on top.
For button ti be displayed on a left side change button attribute class="ui-btn-right" to class="ui-btn-left"
It can be done like this:
$(document).on('pagebeforecreate',  function(){
    $('[data-role="header"]').attr('data-theme','a');
});

Answer: If your website does not use template files to create the layout and is built page-by-page then your best option is to use jQuery to add a home button to every page. If it does use template files then use these because this would avoid the problem of the buttons not being rendered in javascript-free environments.
With regards to your other questions you will need to show us a little more code and perhaps set up a fiddle.


Como faço para excluir linhas pelo conteúdo especifico da célula no pandas

Question: Estou fazendo o pré-processamento dos meus dados utilizando a biblioteca pandas do Python.
Isto é um projeto para treinar um algorítimo a prever "roles"
Este é o resultado que eu tenho quando executo.
print(vagas.role_name.value_counts())

Security Entry                                                     9300
Retail Entry                                                       6562
Healthcare                                                         5884
Food & Hospitality                                                 2559
Unmatched Role                                                     1922
Security Experienced                                               1481
Education                                                           541
Corporate Experienced                                               538
Retail Experienced                                                  309
Service Technician                                                  188
Transportation                                                      183
Sales                                                               175
Software & Technology                                               148
General Labor                                                       128
Corporate Entry                                                     110
Tire Sales & Service                                                 44
Insurance Sales Agent REFERRAL ONLY                                  33
Test and Referrals ONLY                                              29
Customer Service                                                     28
Insurance Sales Agent In Person                                      18
Insurance Sales Agent REFERRAL ONLY - Reliable Life Insurance        17
Security Officer                                                     12
Security Guard (Road Guard)                                           9
Insurance Sales Agent In Person - Reliable Life Insurance             8
Insurance Sales Agent Phone Interview - Reliable Life Insurance       5
Insurance Sales Agent In Person - Union National Life Insurance       4
Insurance Sales Agent Phone Interview                                 3
Guest Service Call Center Representative - example role only          3
Manager in Training - example role only                               3
Visual Merchandiser at Forever 21                                     2
Sales Associate at Forever 21 LIVE                                    2
DO NOT USE                                                            2
Truck Driver - CDL                                                    1
TRAINING ROLE ONLY                                                    1
Experienced Material Handler MCkesson  (4+years)                      1
Tire service Technician                                               1
Assistant Visual Manager at Forever 21                                1
test role MH                                                          1
Sales & Administration                                                1
Lead of Service - Fashion  LIVE                                       1
Delivery Professional                                                 1
Security Officer - Armed                                              1
Co Manager at Forever 21                                              1
Name: role_name, dtype: int64

Quero remover todas as "roles" que tenham menos de 100 linhas
Comment: Ve se minha resposta resolve o teu problema.
Answer: Pode fazer isso usando groupby com count
df = df.loc[df.groupby('role_name')['role_name'].transform('count') >= 100]


Relation between stability of fixed points of discrete and continuous dynamical systems

Question: Let $f:\mathbb R^d\to\mathbb R^d$ be a diffeomorphism, $x_0$ be a fixed point of $$\frac{\rm d}{{\rm d}t}\varphi_t(x)=f\left(\varphi_t(x)\right)\tag1$$ (i.e. $f(x_0)=0$) and $A:={\rm D}f(x_0)$.
It is a well-known result that if the largest eigenvalue $\lambda_1$ of $A$ is negative, then $x_0$ is asymptotically stable.
Now, on the other hand, if $x_0$ is a fixed point of the discrete system $$x_n=f(x_{n-1})\tag2,$$ we may consider the linearization $$h_n=Ah_{n-1}\tag3$$ and it is well-known that $x_0$ is asymptotically stable if $|\lambda_1|<1$.

How are these stability results related?

I've read that we somehow need to "integrate" $(2)$ over time and then use that if $\lambda$ is an eigenvalue of $A$, then $e^\lambda$ is an eigenvalue of $e^A$, but I neither know how precisely we need to transform $(2)$, nor why $e^A$ is occurring then.
Comment: +1 great question. I have asked this same question of some professors and always had less than completely satisfactory answers.
Answer: The link between the two results comes from linear system analysis.
1. From continuous-time dynamic system(CTDS) to discrete-time dynamic system(DTDS), linear case
Consider the state-space representation of a CTDS,
$\dot{x}=Ax,x(0)=x_0$ where $x,x_0\in\mathbb{R}^d,A\in\mathbb{R}^{d\times d}.$ We can explicitly solve this:
$$x(t)=e^{At}x(0).$$
Let $x_n=x(nT)$ where $T$ is a positive constant, we have
$$x_{n+1}=e^{AT}x_n=e^Te^Ax_n.$$ That is to say, we obtain a DTDS by sampling a CTDS. This is how $e^A$ occurs.
2. Stability and stability criteria of the two linear systems
Let $x_0$ be a fixed point of the CTDS, then $Ax_0=0$. Since $$e^A=\sum_{n=0}^\infty\frac{A^n}{n!},$$ we have that $$e^Ax_0=0.$$
Hence $x_0$ is also a fixed point of the DTDS.
Using the definition for stability, we can easily check that the (in)stability of the CTDS at $x_0$ is equivalent to the (in)stability of the DTDS at $x_0$ and the factor $e^{T}$ doesn't matter.
As you said, if $λ$ is an eigenvalue of $A$, then $e^λ$ is an eigenvalue of $e^A$, therefore all eigenvalue of $A$ is negative is equivalent to all eigenvalue of $e^A$ is inside the unit circle.
3. Linearization keeps the stability invariant
See Hartman–Grobman theorem.

Edit 1:
The full logic goes like this: the stability of a nonlinear system (continuous-case or discrete-case) at some equilibrium point can be partly inferred by analyzing the linear system obtained by linearization at that point (Hartman–Grobman theorem for the continuous-case and Banach fixed-point theorem for the discrete-case). Therefore, we can focus on the linearized version of the two systems, and the stability analysis still holds.
To put it simply, We are actually dealing with four systems here:
$$\dot{x}=f(x),\tag{1}$$
$$\dot{x}=Ax,A:={\textrm D}f(x_0),\tag{1'}$$
$$x_n=f(x_{n-1}),\tag{2}$$
$$x_n=Ax_{n-1},A:={\textrm D}f(x_0),\tag{2'}$$
System (1') and (2') are the linearized version of systems (1) and (2), respectively. As you mentioned, if the largest eigenvalue $\lambda_1$ of $A$ is negative, then (1') and (1) are both asymptotically stable at $x_0$. Similarly, if $|\lambda_1|<1$, then (2') and (2) are both asymptotically stable at $x_0$.
Since (1') is a linear time-invariant system, we can easily explicitly solve it: $x(t)=e^{At}x(0)$. By sampling, we get another DTDS:
$$x_{n+1}=e^Te^Ax_n\tag{3}$$
It is by connecting (1') with (2') using (3) that we get the relationship of the two criteria. The results are shown above.
Comment: Thank you for your answer. Unfortunately, I can't follow. Is your $A$ still the same as in the question, i.e. $A={\rm D}f(x_0)$? How did you obtain "$x(t)=e^{At}x(0)$" then? Note that the CTDS is given by $(1)$; why is $\varphi$ occurring nowhere in your answer? Thank you very much for your effort in advance.
Comment: @0xbadf00d As I said, the link between the results lies in *linear system analysis*, so I left out some details to highlight the important stuff. I just appended some explanation for clarity. Hope that helps!
Comment: Oh, and $\varphi$ is just a notation for *flow* in dynamical systems. You can think of my $x$ as $\varphi_t(x)$
Answer: It seems to me  that you confuse yourself a little by choosing the same $f$ for both continuous and discrete versions.
Let me try to address your question from a slightly different perspective.
Consider continuous dynamical system
$$
\dot x=f(x),
$$
such that $0$ is an equilibrium. Assume that we know that for this equilibrium to be stable all the eigenvalues of linearization $Df(0)$ must have negative real parts.
Now together with continuous system consider its discretization
$$
x'=x+hf(x),
$$
which clearly has the same equilibrium $0$. You can consider this discretization as the simplest numerical method to solve ODE system.
Now, linearization of the discrete system is
$$
I+h Df(0),
$$
whose eigenvalues are $1+h\lambda$ if $\lambda$ is an eigenvalue of $Df(0)$.
For 0 to be stable in discrete version one must have
$$
|1+h\lambda|<1
$$
i.e., lie in the disk with the center at $-1/h$ and radius $1/h$.
Hence, to answer

How are these stability results related?

we can say that the stability condition for the discrete version is more restrictive compare to the continuous one. If 0 is stable for the continuous system, it will be stable for the discrete version only if $h$ sufficiently small. If 0 is a center for the linearization of continuous system, it will be unstable for the discrete version no matter the size of $h$, although it still could be asymptotically stable for the continuous system.


Multi Direction Bullets[read]

Question: Been trying to code something for a while for a project im still working on for school, even though it's done.
I want to make a grenade that shoots out bullets on enemies colliding with it, but what I need help with atm is making 8 bullets shoots in all different directions at once.
here's the code my teacher gave me to do it(I asked him for help)
if (mouse.LeftButton == ButtonState.Pressed)
            {
                Texture2D pewTexture;
                pewTexture = game.Content.Load<Texture2D>("pew");
                game.firingSound.Play();
                //Tweak pews to shoot at mouse, rather than just going straight on the y axis.
                pew = new CPew(game, pewTexture);
                pew.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 10f + spriteVelocity;
                pew.position = position + pew.velocity * 5;

                //easy cheesy way:
                //pew.position = position;
                //pew.position.X += 15f;
                //pew.position.Y -= 20f;

                //super awesome cool way for cool people and celebrities
                pew.position = position +
                    new Vector2(
                        texture.Width * .2f - pew.texture.Width * .2f,
                        -pew.texture.Height);

                game.pews.Add(pew);

                myFiringDelay = 10;

            }
            else
            {
                if (mouse.RightButton == ButtonState.Pressed)
                {
                    float pi2 = (float)Math.PI * 2.0f;
                    int numShots = 10;
                    float pi2overnum = pi2 / numShots;

                    for (int i = 0; i < numShots; i++)
                    {
                        Vector2 direction = PiToVec2(pi2overnum * i);

                        //particles[i].reset(position,direction, vector2.zero, 6);
                        game.pews[i].Reset(pew.position, direction, Vector2.Zero);

                    }

           Vector2 PiToVec2(float piT)
           {
              return new Vector2((float)Math.Sin(piT), (float)Math.Cos(piT));

           }

apparently this will make it shoot in every direction on mouse right click but every time I try it and my game crashes straight up
Then we have a pew class which is bullets and thats what I want to be shot in those directions at the same time
you guys may not be able to help with the code i've shown you, i've spent a while looking for a way to do this but i can't seem to find anything
A former example and or source code would be really helpful, just at least another way to look at this thanks.
Showingme when it crashed, it tells me index goes out of range or is negative, if you guys could just show me base code for multidirectional bullets id be happy
Comment: If your game is crashing it would be really helpful to get the relevant output/errors from the debugger for us to be able to help you out with this
Comment: exactly put a try catch over the entire method and see what error is being thrown. Also depending on the error we will likely need to know what pews[] is. Also it is a bad idea to load your texture on every click, you may want to set this up as a reference
Comment: What line does it go out of range? What that means is if there are only 6 "pews" , you cant do pew[7]. So from what I see, when you right click it loops through 10 pews, What is there isnt 10?
Comment: look at the stacktrace and tell us what went out of range.
Comment: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Answer: The problem your having is that when you try and loop through your game.pews collection you are trying to call Reset() on the first 10 items in the collection. However there appear to not be 10 pews in there. So when you get to the end and try to access the next one, that's where you get the "Index out of range" error.
For your 8 bullets from a grenade part of the question, I think you want to do something like this.
//Once a grenade has collided with an enemy
float pi2 = (float)Math.PI * 2.0f;
int numShots = 8;
float pi2overnum = pi2 / numShots;

for (int i = 0; i < numShots; i++)
{
   Vector2 direction = PiToVec2(pi2overnum * i);

   pew = new CPew(game, pewTexture);

   pew.velocity = new Vector2((float)Math.Cos(rotation), (float)Math.Sin(rotation)) * 10f + spriteVelocity;

   //Set the position based off of the grenades last position.
   //Set the direction.
   //Set any other attributes needed.

   game.pews.Add(pew);
}

Now you have eight bullets moving in different directions from where the grenade exploded.
To update them and draw them I would recommend using a foreach loop so you don't have to worry about "Index out of range" errors.
foreach CPew pew in game.pews
{
   pew.Update();
}

Comment: I changed what i had in my player class, I put the foreach loop in my game.cs because it wouldnt work in player.cs and i kept getting this, Collection was modified; enumeration operation may not execute., does it matter that i shoot pews regularly on left click?, and if anyone could, a full example of the grenade thing from scratch would be helpful, thanks!

Multi Direction Bullets[read]


Using the Orbit-Stabiliser Theorem to prove a set of matrices is a subgroup of $\operatorname{GL}_2(\mathbb{R})$

Question: I'm working on an unassessed course problem,

Use the Orbit-Stabiliser Theorem to show that the set of matrices $$
M = \begin{pmatrix}
a&b \\ c&d
\end{pmatrix}
\in \operatorname{GL}_2(\mathbb{R})
$$
with $a+c=b+d=1$ form a subgroup of $\operatorname{GL}_2(\mathbb{R})$.

I've written,

Let $$G=\operatorname{GL}_2(\mathbb{R}), \quad B=\begin{pmatrix}e&f\\ g&h\end{pmatrix}\in G, \quad A=\begin{pmatrix}a&b\\ c&d\end{pmatrix}\in M;$$ clearly $G$ acts on $M$ by matrix multiplication and $$
BA = \begin{pmatrix}e&f\\ g&h\end{pmatrix} \begin{pmatrix}a&b\\ c&d\end{pmatrix}  = \begin{pmatrix}ea+fc& eb+fd \\ ga+hc&ga+hd\end{pmatrix}.
$$
Now, clearly $\operatorname{orb}_G(A)=G$, and
\begin{align}
& \begin{aligned}[t]
& (ea+fc)+(ga+hc) = (e+g)a+(f+h)c, \\
& (eb+fd)+(ga+hd) = (e+g)b+(f+h)d
\end{aligned} \\[0.5em]
\therefore \; & \begin{aligned}[t] & \operatorname{stab}_G(A) = \{B\in G \text{ s.t. } e+g=f+h=1\}=M, \\[0.5em]
\end{aligned}
\end{align}
so, by the Orbit-Stabiliser Theorem, we have
$$\infty = |\operatorname{orb}_G(A)| = \frac{|G|}{|\operatorname{stab}_G(A)|} = \frac{\infty}{\infty} \text{ or something.}$$

Is there a way to finish this argument validly?
Comment: The orbit-stabilizer theorem is no so much about cardinalities (which can be infinite), but about $G$-set isomorphisms $X\approx G/H$, where $H$ is the stabilizer of some point in $X$, and $G$ acts transitively. You can show directly that the stabilizer (and also pointwise-fixer) of _any_ group action is always a group.
Comment: Unless there's some larger context... you do not need to invoke anything like the orbit-stabilizer theorem to understand that the subgroup fixing some set (on which the larger group acts) is a subgroup.
Comment: @paulgarrett If I understand you right, to show that $M\leq G$ it's enough to show that $\text{stab}_G(A)=M\subseteq G$; but I don't see how that uses the OST. Any idea what the "Use the Orbit-Stabiliser Theorem to show" instruction is getting at?
Comment: @paulgarrett OK, thanks. The comments are enough for me, but if you care to make it an answer I'll be happy to accept. [This answer](https://math.stackexchange.com/a/265967/596895) contains a handy proof of the stabiliser-subgroup property you mention, in case anyone reading this finds it useful.
Answer: I don't see a way to use the orbit-stabilizer theorem, which is about a bijection between an orbit and the coset of a stabilizer of a point in that orbit, to prove that something is a (sub)group. However, perhaps the real intent here was to use that stabilizers of a group action are subgroups. With this, the proof is easy:
The group $\operatorname{GL}_2(\mathbb{R})$ acts on $\mathbb{R}^2$ from the right via
$$
(x\quad y) \cdot \begin{pmatrix}
a&b \\ c&d
\end{pmatrix}
= (ax+cy\quad bx+dy).
$$
Now the stabilizer of the vector $(1\quad 1)$ with respect to this action is the set of matrices you are considering.


Fixar o rodapé de uma página html e acompanhar o conteúdo da página

Question: Eu preciso fixar a tag footer no final da página html, mas quando o conteúdo exceder a página a tag footer deve acompanhar o conteúdo e não ficar fixa.
Veja o código CSS é o código HTML que estou usando para isso.

    header {
        min-height: 55px; /* original era 255px mudei para caber no snippet */
        background-color: blue;
    }
    article {
        padding-bottom: 60px;
        width: 900px;
        margin: 0 auto;
    }
    footer {
        position: absolute;
        bottom: 0px;
        width: 100%;
        height: 60px;
        background-color: green;
    }

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

O problema é que a tag footer com a propriedade position com o valor fixed deixa o rodapé fixo.
Quando mudo a propriedade position para absolute a tag footer fica flutuando e não acompanha o conteúdo.
Answer: Para browsers recentes você pode adicionar isto ao seu CSS:
html {
    position: relative;
    min-height: 100%;
}
body {
    margin: 0 0 60px; /* altura do seu footer */
}

Segundo o criador da solução, functiona com: IE8+, Chrome / Safari, Firefox e Opera.
A maior vantagem desta solução sobre as outras é que você não precisa criar wrappers em volta do seu conteúdo. Ela utiliza o próprio body como wrapper.
Exemplo: Com muito conteúdo - Sem muito conteúdo
(O mesmo código foi utilizado para os dois exemplos, só o conteúdo que muda.)
Answer: Da para fazer usando flex no body.
Primeiro vc precisa definir o body com display: flex, depois coloca a ordem como column, para que a "orientação" do grid fique na vertical (mais ou menos como o comportamento padrão das divs). Depois no main que vai receber o conteúdo vc coloca flex-grow: 1; e coloca position:sticky na nav para ela ficar fixa no topo. Dessa forma o main vai sempre ocupar todo o espaço disponível, "empurrando" o footer sempre pro final da página independente da quantidade de conteúdo.

Veja o código usado para ter o resultado da imagem acima:
Exipa também como "Página toda" para ver melhor o resultado!

html, body {
 width: 100%;
 height: 100%;
 margin: 0;
 padding: 0;
}
body {
 display: flex;
 flex-direction: column;
 background-color: #ddd;
}
nav,
footer {
 width: 100%;
 min-height: 50px;
 background-color: #f00;
 text-align: center;
 color: #ddd;
}
nav {
 position: sticky;
 top: 0;
}
main {
 width: 100%;
 background-color: turquoise;
 flex-grow: 1;
}
NAV

Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur voluptates reprehenderit magni molestias iure unde id minima voluptatem laudantium ipsum. Nam reprehenderit iusto consectetur ipsum natus doloremque laudantium illum quod delectus perferendis! Quam explicabo laudantium suscipit reprehenderit harum quo nostrum porro fugit natus. Eius sequi odit sunt, aut eveniet similique dicta mollitia reprehenderit incidunt, molestiae quod amet esse facere vero perspiciatis dignissimos voluptatum eligendi laborum dolorum asperiores inventore, ipsum est. Obcaecati dolores perspiciatis dignissimos. Consequuntur soluta quaerat, asperiores sed earum non impedit. Tempora dicta dolorum quas id asperiores laboriosam delectus velit perferendis veniam blanditiis ea exercitationem ullam, ab consequuntur incidunt ipsa est voluptate suscipit cumque non ipsum praesentium minima aliquam. Tempore ratione dolore aut saepe sint. Eos vel facilis minima nostruoloremque reprehenderit nisi sunt inventore maxime quisquam quaerat, totam perspiciatis. Quidem in sint debitis perspiciatis labore, eaque nam quis doloremque blanditiis ipsum architecto temporibus sunt tempore voluptates? Voluptatem, dolorum unde ut facilis quasi eligendi officia earum in. Nemo impedit pariatur itaque soluta non minus. Minima vel maiores aliquid officiis accusamus optio excepturi praesentium in doloremque, similique necessitatibus! Iure asperiores necess nemo ipsa laborum velit optio

FOOTER

OBS: O Flex funciona do IE10 pra cima https://caniuse.com/#search=flex aténde
Answer: Uma solução simples e responsiva seria assim.

footer{
position: relative;
background-color: red;
width:100%;
height:48px;
left:0;
bottom:0;
}

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Comment: Se houver pouco conteúdo na página, o rodapé não ficará fixado na parte de baixo: https://jsfiddle.net/b8gze2ta/
Comment: Acrescente no css

left: 0;
bottom: 0;

Assim:

`footer{
position: absolute;
background-color: red;
width:100%;
height:48px;
left: 0;
bottom: 0;
}`
Answer: Para que o  Caso tenha pouco conteúdo na pagina não se desloque para acompanhar o conteúdo use  {left: 0; bottom: 0;}

footer{
position: relative;
background-color: red;
width:100%;
height:48px;
}

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Conteúdo

Comment: Seu código não está legal, basta vc executar ai e fazer um scroll que vc vai ver que o Footer fica no meio da página e o conteúdo continua após ele
Comment: Foi porque havia me esquecido de ajustar o position. Quando o conteúdo for grande não use o `left:` ou `bottom`. Quando o Conteúdo for curto ou pouco use-os assim `left:0; bottom:0` `positon`  deve ser **relative**


Do I need to refresh or restart anything after I add/update a crontab in Ubuntu Server 8.04?

Question: When you change something in Apache you need to reload or restart apache. Does anything need to be refreshed or restarted in Ubuntu Server 8.04 after I add/update the crontab? Thanks a bunch for your help.
Answer: No. As long as you use the crontab -e command to edit the file, when you save it, you'll get a 'New Crontab Installed' message. That's it.
Comment: But what if you did not use `crontab -e` to edit the file?
Comment: The same applies to `crontab ` -- and to `crontab -r`, for that matter.
Comment: It should still work if you edited the file directly, assuming you had permissions to do so. It's still recommended to use the crontab command.
Comment: @user5359531 If you want to restart cron for whatever reason (which will force reloading of crontab files) see this SO question: https://stackoverflow.com/questions/10193788/restarting-cron-after-changing-crontab-file
Answer: The usual thing is to use crontab -e to edit the tables. The changes will be applied when you exit the editor. Otherwise the rules for re-reading changed crontabs are in the cron(8) man page. They will be re-read eventually, you don't need to do anything.
Comment: The change is not applied when you only save the file.
Answer: It's important that you elaborate on HOW/WHERE you are adding crons.  But I think the following addresses any situation.
Yes, cron needs to be made aware that you made changes, but no, you don't necessarily need to explicitly do anything to update it.
I'm paraphrasing the cron manual here for the short version:
As mentioned, crontab -e, the preferred method, will notify cron that something changed.
However, cron "wakes up" every minute to see if it has tasks for that minute. It also scans /var/spool/cron/crontabs and will reload any files with an updated 'mtime' (modified time, meaning the file contents must have been updated).
So theoretically, if you do nothing, cron will "wake up" and see you made changes to anything directly in /var/spool/cron/crontabs.
But if you can, use crontab -e.  When you are done editing, it even gives you feedback that it was updated, it says:
    crontab: installing new crontab

Specifically, this means that it refreshed its copy in memory for the file you just edited via crontab.
Here's a quote from the manual CRON(8) :
    cron searches its spool area (/var/spool/cron/crontabs) for
    crontab files (which are named after accounts in /etc/passwd);
    crontabs found are loaded into memory.  Note that crontabs in this
    directory should not be accessed directly - the crontab command
    should be used to access and update them.


drupal_goto() usage

Question: I did some research about using drupal_goto('page'), and I noticed that the parameters of the function can be only the path of the destination page.
I want to use this function in a form submission handler. Can I take the submitted values and use them with drupal_goto() as in the following code?
function my_module_form_submit($form, &$form_state) {
  $database_name = $form_state['values']['databasename'];
  drupal_goto('page', $database_name);
}

Answer: In a form submission handler, there is no need to use drupal_goto(), and it should be avoided, since it stops the other form submission handlers from being called.
If you need to redirect the users to a page, you should use $form_state['redirect'], which accepts the same parameters used by drupal_goto(). In particular, the following code will redirect the users to node/123?foo=bar#baz, if other modules don't alter the redirection, and other conditions are met.
$form_state['redirect'] = array(
  'node/123',
  array(
    'query' => array(
      'foo' => 'bar',
    ),
    'fragment' => 'baz',
  ),
);

As for passing the values contained in the array $array to the redirection URL, that is easily done with the following code.
$form_state['redirect'] = array(
  // Se the values you need.
);

$form_state['redirect']['query'] = drupal_get_query_parameters($array, array());

If then the need is just to pass data from a page to another, there are better solutions, such as passing the data into the session data. I would rather use that, since theoretically there isn't a limit to that data stored as session data, while a URL cannot be longer than X characters.
Reference

drupal_build_form()
drupal_redirect_form()
drupal_get_query_parameters()
Comment: Thenk for your answer but I still need to send an array from the first page to the second page with the use of $form_state['redirect']
Comment: Do you need the next page to have access to php data from the prior page? if so, you may need to look into `$_SESSION` variables.

drupal_goto() usage


plm function in R: Order of input for index changes results when model = within?

Question: I am only slightly familiar with the plm() function in R, and I get this odd phenomenon.
When my input is this:
summary(plm(trust ~ u*SAP*euro, data = thesis, index = c("wave", "country"), model = "within"))

My coefficients look like this:
Coefficients:
              Estimate Std. Error t-value Pr(>|t|)
u            -0.032216   0.218323 -0.1476 0.882746
SAP1          3.822850  11.030372  0.3466 0.729046
euro1         3.132854   2.815987  1.1125 0.266409
u:SAP1       -0.203725   0.738879 -0.2757 0.782868
u:euro1      -0.822703   0.272390 -3.0203 0.002645 **
SAP1:euro1   -8.547847  12.728400 -0.6716 0.502153
u:SAP1:euro1 -0.106580   0.823753 -0.1294 0.897103

However, when I change index = c("wave", "country") to index = c("country", "wave"), that influences all the estimates by a lot:
Coefficients:
              Estimate Std. Error t-value  Pr(>|t|)
u             -0.61203    0.20672 -2.9606  0.003205 **
SAP1          11.00945    9.57049  1.1504  0.250504
euro1          4.57873    3.09121  1.4812  0.139130
u:SAP1        -0.51587    0.65099 -0.7924  0.428454
u:euro1       -1.08519    0.27065 -4.0096 6.934e-05 ***
SAP1:euro1   -21.59497   10.68735 -2.0206  0.043810 *
u:SAP1:euro1   0.68574    0.70375  0.9744  0.330288

Why is this? Shouldn't the plm() function run the exact same regression with two-way fixed effects regardless of the order in which I put in my two fixed effects categories (country and wave)? Which results should I use?
Answer: My understanding of the order when using PLM is that what you put first as the index specifies what you want fixed effects on.
Here is case fixed effects.
library(plm)
p.vdem <- pdata.frame(vdem, index=c("country_id", "year"), row.names=FALSE)

caseFE <- plm(v2x_polyarchy ~ e_reserves_billions, model="within", data=p.vdem)

Here is time fixed effects.
p.vdem <- pdata.frame(vdem, index=c("year", "country_id"), row.names=FALSE)

timeFE <- plm(v2x_polyarchy ~ e_reserves_billions, model="within", data=p.vdem)
summary(timeFE)

Two-way fixed effects are obtained by setting both variables to factor and generating dummy variables.
twowayFE.dummy <- lm(v2x_polyarchy ~ e_reserves_billions + factor(country_id) + factor(year), data=vdem)
summary(twowayFE.dummy)

Comment: Thank you so much for your answer! That would make a lot more sense. I had actually already done an lm() regression like yours, and already found it odd that the results were different when using the plm function. There is no way to do two-way fixed effects using the within estimator then?
Comment: @John Stud: Rwo-way fixed effects can be estimated evene without creating dummy variables directly with plm: use argument `effect = "twoways"`. Similarly, as long as the indexes are correctly set, one can perform individual (case) and time fixed effects separately, whithout switching the index variables, use `effect = "individual"` or `effect = "time"`. It is all documented, btw. First variable in index should be the individual (case) dimension, otherwise interpretation of `effect` switches.


Firebase functions GET request with query params returns 400 error

Question: I have a function called base which runs and returns a 200 status fine with the expected payload when I do a GET via postman to: http://localhost:5001/api-name/region/base.
But when I add a get parameter to the URL, the request fails, i.e. http://localhost:5001/api-name/region/base?origin=localhost. I get a 400 Bad Request error. The interesting thing is while postman reports the 400 Bad Request almost immediately, the firebase emulator acts like it is still running the function and times out after 60s.
I have function runtime options to set the request at 300s (because it's a big query and takes a while, this works as expected too without the params), so it seems like it's not even being routed to the correct function or anywhere at all.
Answer: I had the same issue. The solution was to update to the latest version of firebase-tools.
If using npm:
npm install -g firebase-tools@latest
This was a bug fixed in v9.2.1. More info here: https://github.com/firebase/firebase-tools/releases/tag/v9.2.1


First hat-trick in T-20 international

Question: Who is the first bowler to take hat-trick in T-20 international?
Answer: Brett Lee is the first bowler to take a hat-trick in T20I matches. He took against Bangladesh at Cape Town in World T20 2007. See the scoreboard.
From the match report:

Another Twenty20 first
After the first Twenty20 century, by Chris Gayle against South Africa, this match brought the first hat-trick in the international version. Brett Lee was the man with the honour as his pace proved too much for the middle order...

Here is the list of the hat-trick in T20I matches.

First hat-trick in T-20 international


How to get rid of a scratch on my strat

Question: I know that it's possible to rub out a  scratch on my cars finish using rubbing and polishing compound. Does the same thing work on a guitars finish if the scratch is not to deep?
Comment: Assuming the finish is cellulose, and it may well be - ask Fender, with model and s.n. then the process is the same as with car paintwork (when they used celly paint !  Or - leave it, and when it gathers many more, and you're famous, Fender will make copies to sell at ridiculous prices...
Comment: Your comment implies when my guitar gets scratched up, I'll be famous.  :)
Comment: The two things have been known to happen in that order!
Answer: to answer your question, yes you can use car scratch remover, but go gently. In addition, try it on a hidden area first.

How to get rid of a scratch on my strat


Multiple regression analysis - using all possible interactions

Question: I have data on about 8000 persons and I am trying to find independent predictors of a health outcome variable (yvar). The predictor variables are age, gender, height, city and 3 other predictor variables (xvar1, xvar2, xvar3). Some are continuous while others are categorical. The categorical variables are kept as such and not converted to numbers (e.g. 'M' and 'F' are levels in gender). The outcome variable (yvar) is continuous.
If I use following code in R (applying all interactions):
lm(yvar~age+gender+heigth+city+xvar1+xvar2+xvar3)

I get 5 of these 7 to be with $p<0.05$ (many are much less than 0.05) and overall $R^2$ of 0.11
On using following code:
lm(yvar~age*gender*heigth*city*xvar1*xvar2*xvar3)

I get $R^2$ of 0.18 but NONE of the predictors has $p<0.05$
What do I conclude from this? Should I or should I not use interactions? What is the best way to analyze such data?
Also, should I use one of above formats or following format:
lm(yvar~(age+gender+heigth+city+xvar1+xvar2+xvar3)*(age+gender+heigth+city+xvar1+xvar2+xvar3) )

These produce only 2-way interactions and not all combination interactions as in second format.
Comment: Terminology tip: The word "parameter" used to mean just index or  measure or property or variable clashes with its established statistical use as meaning a unknown constant you are estimating.
Comment: I changed from 'parameter' to 'outcome variable' in the question.
Answer: The approach you are using is devoid of input from subject-matter knowledge.  This is usually a recipe for trouble.  Using $P$-values to guide model specification is fraught with statistical problems.  And you may be using the wrong statistical tests as the basis for your concern, i.e., you may be trying to define a main effect in the presence of an interaction effect.  The appropriate tests to use are combined tests of main effects + interaction effects.  But more importantly having 7th-order interactions in your model is a huge overkill resulting in estimation of far too many parameters, making everything unstable.  It would be better to stick to second-order interactions (in R (a + b + c)^2) but this approach is still a bit dangerous and you have not included all the original variables as main effects, which will give you a false impression of importance of interactions.
Try to think of a statistical analysis not as a fishing expedition but rather through reasoned model specification.
Comment: I would add that this kind of high-order interactions would be impossible to interpret and would have a high potential for overfitting.
Answer: If I understand you correctly, you have a number of explanatory variables but not much clue which of them could be relevant and which not. Here are a few ways to proceed:

Try out all possible subsets of variables and pick the one that gives a regression with the smallest Bayesian information criterion (BIC) value. See e.g here for relevant R functions. In you want to allow for interactions, too, then either define new regressors by multiplying the existing ones in a pairwise fashion or look for an existing function to do that for you.  Using BIC will help strike the right balance between possible overfitting and underfitting. If you intend to use your model for forecasting rather than explanation, use Akaike information criterion (AIC) instead of BIC.
Forward or backward stepwise selection: start from a small model and add regressors one by one based on their relevance (broadly speaking) or start from a general model and remove regressors one by one, again based on their relevance.
Shrinkage methods (LASSO, ridge regression, elastic net, principal components regression, partial least squares): if you want to reduce the mean squared error of your model and do not care exclusively about the unbiasedness of your estimates, you might want to allow for some bias to gain a decrease in variance. This makes sense if you intend to forecast but not so much if your study is explanatory.

See Hastie et. al "The Elements of Statistical Learning" chapter 3 subsections 3.3-3.7 for a more detailed overview.
To address your concern about p-values: they are not sacred and many say they are given too much importance. Sometimes (when there is a lot of data) even irrelevant variables become statistically significant, but the magnitudes of their coefficients are small and substantively negligible. Sometimes two or more variables are jointly significant but not so individually. Thus you have to interpret them carefully and not just mechanically.
Comment: It's a tough problem.  Throughout my career I've never found exploratory interaction searching to be close to reliable.  So it remains necessary to narrow potential interactions to include in the model.  Ask the question "could we explain this interaction were it to be found important?"
Comment: Note that some of these are more controversial than others. #2 is widely considered a very bad idea, for reasons well explained by Frank Harrell, a contributor here, in his book _Regression modeling strategies_ (New York: Springer, 2001). I'd want to add 0. Consist subject-matter experts if you lack subject-matter expertise to consider what kinds of relationships are likely to be of interest or importance.
Comment: #1 is also a *very* bad idea.
Comment: No.  It is important to fully understand the assumptions made and the performance characteristics of any method for model development.
Comment: This has been studied extensively and shown to fail.  See for example my [RMS course notes](https://hbiostat.org/rms).  Among the problems: overfitting/poor validation, ruined standard errors, bias, instability, ruined confidence interval coverage.
Comment: I tried and found bestglm very easy to use. Simple command "bestglm(mydata)" uses default options and gives me the best model. Is it fair to use in most situations?
Comment: I checked and found that in most studies interactions are not used at all. Only different independent variables are put in multiple regression using '+' (and not '*') and significant ones are reported. Is this safe to follow when interactions are not obvious?
Comment: This is where you need some subject matter knowledge. Statistical learning / machine learning techniques that I proposed are but tools that can be useful but that have to be used wisely dependent on the context. I am no expert in the area of health modelling, so I cannot advise you in this question.
Comment: Using multiple regression analysis with only'+', I am getting age, gender, height and two more variables as significant. On the other hand, if I use bestglm(mydata) only age and gender are shown in best model. What do I conclude?
Comment: Parameter significance as assessed by p-values is not the best indicator of which variables to include. This has been claimed multiple times, see e.g. [here](http://robjhyndman.com/hyndsight/tests2/). Better look at BIC values for the different models to see which one is more relevant.
Comment: The command bestglm(mydata) gives me Df,  Sum Sq, Mean Sq, F value and Pr(>F) of best model only. How do I get 'BIC values for different models'?
Comment: You should be able to calculate BIC manually given Sum sq and the number of parameters estimated in the model (you could use total number of observation minus Df to obtain those). Hint: take a look at BIC formula and find out how log likelihood can be expressed as a function of Sum sq (this holds for normally distributed errors, not sure if it holds universally).
Comment: @FrankHarrell Why is #1 a very bad idea? Is it because of (i) trying out all possible subsets of variables, or (ii) using the BIC as the measure of relevancy?
Comment: @FrankHarrell So how do we decide what variables/interactions to use in the model if both 1) and 2) are bad? Subject matter knowledge is not going to help in the very common situation in which we have no pre-existing knowledge of whether a particular interaction effect is present in nature and we are relying on the information in the data itself. Suppose we have the predictors - age, gender, height, weight, experience, IQ - and the response variable salary. How do we decide what interaction effects to include/not include?
Comment: I have turned the above comment into a post as I have not found good info on this anywhere so I think it could be useful to the community in general - https://stats.stackexchange.com/questions/493027/how-to-systematically-choose-which-interactions-to-include-in-a-multiple-regress
Comment: Thanks, its good to know that somehow narrowing the interactions is fundamentally important. And I will keep that question in mind any time I run into this type of situation in future.


jar file not working for imports in Eclipse

Question: I am following a tutorial from AndroidHive on how to login to Twitter from my app.
The tutorial uses the twitter4j library, so I download it from here and save the zip file to my desktop. In my project I drag the twitter4j zip file into my projects libs folder. Then I Refactor -> Rename the file from a zip to a jar (only changing the extension)
However, when I want to import the classes into my project, it does not seem to be working. I try to do
import twitter4j.Twitter;

But this option is not available. See screen grab.
Can anyone please tell me where I am going wrong with this?
Also, as per the tutorial I have also just added the twitter4j-core file to the project but still imports wont seem to work.

Answer: The tutorial clearly says "Download and Extract" That does not mean "Download and Rename". It means download the file and then Use a file compress/uncompress utility to extract the zipped files format. Search in the extracted files to find the relevant jar file and import that file.
1. Download & extract twitter4j library from twitter4j-android-2.2.6.zip (slimmed version for Android platform). Here is the direct link

If you uncompressed correctly then do the following
Right sure that the folder where you copied the twitter library shows up in the Lib path for the project. Right click on the project --> Select 'Properties' ---> Select 'Java Build Path' From the Left hand Menu ---> Select Libraries Tab. Review List of Libraries(expand if needed ) to see if the twitter jar files show up here.
If not Select 'Add Jar' browse to the Jar file. Add it. Refresh your project. Clean it and build. You should now be able to import twitter components.
Comment: Sorry, should have mentioned that I did that as well. Downloaded, extracted and then added the jar files from twitter4j-core but still does not work.
Comment: Ok found the problem. Was looking in the wrong place. The correct path to the twitter4j core is /twitter4j/libs/twitter-core-XXX