Scrape Google News with lxml and python

Question: I'm trying to scrape Google News using python and lxml. Everything is going well but when I try to print each div data using a for loop everything mess up.
Here my code:
# -*- coding: utf-8 -*-

from stem import Signal
from stem.control import Controller
from lxml import html
from lxml import cssselect
from lxml import etree
import requests

proxies = {
    'http' : 'http://127.0.0.1:8123'
}

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}

url = "https://www.google.it/search?hl=en&tbm=nws&as_occt=any&tbs=cdr:1,cd_min:9/1/2014,cd_max:9/1/2014,sbd:1&as_nsrc=Daily%20Mail&start=0"

page = requests.get(url,proxies=proxies,headers=headers)
tree = html.fromstring(page.content)
results = tree.xpath('//div[@class="_cnc"]')

for div in results:
    print(div)

I get this output:
<Element div at 0x7f4154df9470>
<Element div at 0x7f4154df94c8>
<Element div at 0x7f4154df9520>
<Element div at 0x7f4154df9578>
<Element div at 0x7f4154df95d0>
<Element div at 0x7f4154df9628>
<Element div at 0x7f4154df9680>
<Element div at 0x7f4154df96d8>
<Element div at 0x7f4154df9730>
<Element div at 0x7f4154df9788>

I would like to extract from each div -> title, href and snippet, with something like this:
....

for div in results:
    title = div.xpath('//a[@class="l _HId"]/text()')
    href = div.xpath('//a[@class="l _HId"]/@href')
    snippet = div.xpath('//div[@class="st"]/text()')
    #for example
    print(title)
....

When I try to print I get same multiple output:
['Pro-Russian rebels lower demands in peace talks', "'If I want to I can take Kiev in a fortnight': Putin's threat to Europe ", 'Showing a yen for business: PM Modi and Japanese premier Abe ', 'Modi visit draws pledges of support from Japan', 'The spectre of the Army rises again over Pakistan', 'Protesters briefly storm Pakistan state TV station', 'Anti-government protesters storm Pakistan state television station ', 'Austerity debate flares as Europe recovery fades', 'Inquiries begin into nude celebrity photo leaks', 'He tried to sell intimate pictures of Jennifer Lawrence in return for ']
['Pro-Russian rebels lower demands in peace talks', "'If I want to I can take Kiev in a fortnight': Putin's threat to Europe ", 'Showing a yen for business: PM Modi and Japanese premier Abe ', 'Modi visit draws pledges of support from Japan', 'The spectre of the Army rises again over Pakistan', 'Protesters briefly storm Pakistan state TV station', 'Anti-government protesters storm Pakistan state television station ', 'Austerity debate flares as Europe recovery fades', 'Inquiries begin into nude celebrity photo leaks', 'He tried to sell intimate pictures of Jennifer Lawrence in return for ']
['Pro-Russian rebels lower demands in peace talks', "'If I want to I can take Kiev in a fortnight': Putin's threat to Europe ", 'Showing a yen for business: PM Modi and Japanese premier Abe ', 'Modi visit draws pledges of support from Japan', 'The spectre of the Army rises again over Pakistan', 'Protesters briefly storm Pakistan state TV station', 'Anti-government protesters storm Pakistan state television station ', 'Austerity debate flares as Europe recovery fades', 'Inquiries begin into nude celebrity photo leaks', 'He tried to sell intimate pictures of Jennifer Lawrence in return for ']
['Pro-Russian rebels lower demands in peace talks', "'If I want to I can take Kiev in a fortnight': Putin's threat to Europe ", 'Showing a yen for business: PM Modi and Japanese premier Abe ', 'Modi visit draws pledges of support from Japan', 'The spectre of the Army rises again over Pakistan', 'Protesters briefly storm Pakistan state TV station', 'Anti-government protesters storm Pakistan state television station ', 'Austerity debate flares as Europe recovery fades', 'Inquiries begin into nude celebrity photo leaks', 'He tried to sell intimate pictures of Jennifer Lawrence in return for ']
['Pro-Russian rebels lower demands in peace talks', "'If I want to I can take Kiev in a fortnight': Putin's threat to Europe ", 'Showing a yen for business: PM Modi and Japanese premier Abe ', 'Modi visit draws pledges of support from Japan', 'The spectre of the Army rises again over Pakistan', 'Protesters briefly storm Pakistan state TV station', 'Anti-government protesters storm Pakistan state television station ', 'Austerity debate flares as Europe recovery fades', 'Inquiries begin into nude celebrity photo leaks', 'He tried to sell intimate pictures of Jennifer Lawrence in return for ']
['Pro-Russian rebels lower demands in peace talks', "'If I want to I can take Kiev in a fortnight': Putin's threat to Europe ", 'Showing a yen for business: PM Modi and Japanese premier Abe ', 'Modi visit draws pledges of support from Japan', 'The spectre of the Army rises again over Pakistan', 'Protesters briefly storm Pakistan state TV station', 'Anti-government protesters storm Pakistan state television station ', 'Austerity debate flares as Europe recovery fades', 'Inquiries begin into nude celebrity photo leaks', 'He tried to sell intimate pictures of Jennifer Lawrence in return for ']
['Pro-Russian rebels lower demands in peace talks', "'If I want to I can take Kiev in a fortnight': Putin's threat to Europe ", 'Showing a yen for business: PM Modi and Japanese premier Abe ', 'Modi visit draws pledges of support from Japan', 'The spectre of the Army rises again over Pakistan', 'Protesters briefly storm Pakistan state TV station', 'Anti-government protesters storm Pakistan state television station ', 'Austerity debate flares as Europe recovery fades', 'Inquiries begin into nude celebrity photo leaks', 'He tried to sell intimate pictures of Jennifer Lawrence in return for ']
['Pro-Russian rebels lower demands in peace talks', "'If I want to I can take Kiev in a fortnight': Putin's threat to Europe ", 'Showing a yen for business: PM Modi and Japanese premier Abe ', 'Modi visit draws pledges of support from Japan', 'The spectre of the Army rises again over Pakistan', 'Protesters briefly storm Pakistan state TV station', 'Anti-government protesters storm Pakistan state television station ', 'Austerity debate flares as Europe recovery fades', 'Inquiries begin into nude celebrity photo leaks', 'He tried to sell intimate pictures of Jennifer Lawrence in return for ']
['Pro-Russian rebels lower demands in peace talks', "'If I want to I can take Kiev in a fortnight': Putin's threat to Europe ", 'Showing a yen for business: PM Modi and Japanese premier Abe ', 'Modi visit draws pledges of support from Japan', 'The spectre of the Army rises again over Pakistan', 'Protesters briefly storm Pakistan state TV station', 'Anti-government protesters storm Pakistan state television station ', 'Austerity debate flares as Europe recovery fades', 'Inquiries begin into nude celebrity photo leaks', 'He tried to sell intimate pictures of Jennifer Lawrence in return for ']
['Pro-Russian rebels lower demands in peace talks', "'If I want to I can take Kiev in a fortnight': Putin's threat to Europe ", 'Showing a yen for business: PM Modi and Japanese premier Abe ', 'Modi visit draws pledges of support from Japan', 'The spectre of the Army rises again over Pakistan', 'Protesters briefly storm Pakistan state TV station', 'Anti-government protesters storm Pakistan state television station ', 'Austerity debate flares as Europe recovery fades', 'Inquiries begin into nude celebrity photo leaks', 'He tried to sell intimate pictures of Jennifer Lawrence in return for ']

Does anyone know what's wrong with my code?
Answer: You are almost there - just prepend the dots to the inner XPath expressions to make them specific to the context of the current node:
for div in results:
    title = div.xpath('.//a[@class="l _HId"]/text()')
    href = div.xpath('.//a[@class="l _HId"]/@href')
    snippet = div.xpath('.//div[@class="st"]/text()')
    #for example
    print(title)

Scrape Google News with lxml and python


How to increase the lower bound on possible counter-examples to the Collatz Conjecture?

Question: According to Wikipedia, all positive integers up to $2^{60}$ have been tested and follow the Collatz Conjecture. This got me thinking, could one write a program that tests integers of the form $2^{60} +n$? Because obviously, if all integers below $2^{60}$ follow the conjecture, then if repeated iterations of the Collatz function to numbers of the form $2^{60}+n$ yields a number smaller than this bound, then that number automatically must also follow the conjecture, right?
For example, take the number $2^{60} +1$. It is clearly an odd number, so
 $3(2^{60}+1) +1= 3*2^{60}+4$
This number is clearly even, so
$(3*2^{60}+4)/4=3*2^{58}+1$
This number is obviously smaller than $2^{60}$, so therefore $2^{60}+1$ must follow the conjecture! Could one write a program to do this rapidly, increasing this bound?
Comment: But isn't this exactly how they got to 2^60 in the first place?
Comment: Is it? I didn't read very deep in the article. Well its a very sensible method anyway, lol
Comment: Uh, $2^{60}$ is a very large number. Looping over $10^9$ takes about a second, even if you only run a single i++ assembly instruction [Much less iterating Collatz]. So just trying to increase the bound to $2^{61}$ will take another $10^9$ seconds (30 years) if you throw it in a for loop.
Answer: What you have observed is that $2^{k}+n$ follows the same path as $n$, at least for a little bit. In fact, $2^{k}+n$ and $n$ take the same patterns of "divide by $2$", "$3n+1$", but with every division you decrease $k$ by $1$. This means that eventually your power of two becomes $1$, and you lose all your predictive power. If this happened sufficiently slowly, it would actually be enough to give a proof by induction of the conjecture! Unfortunately, there are several forms of numbers which will always beat you - On example is $2^{k}-1$. Note that this maps as $2^{k}-1 \to 3\cdot 2^{k}-4 \to 3\cdot 2^{k-1}-1>2^{k}-1$, and this sequence will clearly not decrease until your power of two is exhausted. There are a few other patterns; if you want to explore them, have a look at cycles of negative numbers under the collatz iteration.


4D plot in python matplotlib

Question: I am quite new with python programming so I am a bit lost with it.
I am trying to create a scatter3D plot which plots X, Y, Z coordinates for time position and use the color as 4 dimension to plot the value.
The problem I am facing is that... it seems impossible to me to add the variable as colour and add a colorbar for help.
I explain the background here: I have created a meshgrid for X, Y, Z and an array for computing the value in each position for X, Y, Z coordinates (which is an trimensional array).
It follows an loop for filling the array with the values for each X,Y,Z combination and then i try to create the graph.
x = np.linspace(0, 15, 15)
y = np.linspace(0, 30, 15)
z = np.linspace(5, 45, 15)

X, Y, Z = np.meshgrid(x, y, z)

sumatorio = np.zeros(shape=(len(X[0, :, 0]), len(Y[:, 0, 0])))

sumatorio_1 = np.zeros(shape=(len(Y[:, 0, 0]), len(Z[0, 0, :])))

sum_total = np.zeros(shape=(len(X[:, 0, 0]), len(Y[0, :, 0]), len(Z[0, 0,
:])))

c = np.array([])

for i in range(len(X[0, :, 0])):
    for j in range(len(Y[:, 0, 0])):
        sum_1 = X[0, i, 0] + Y[j, 0, 0]
        sumatorio[i, j] = sum_1
            for k in range(len(Z[0, 0, :])):
            sum_2 = sum_1 ** 2.0 + Z[0, 0, k] + X[0, i, 0]
            sumatorio_1[j, k] = sum_2
            sum_total[i, j, k] = sumatorio[i, j] + sumatorio_1[j, k]
fig = plt.figure(figsize=(50.0, 50.0))
ax = fig.add_subplot(111, projection='3d')

ax.scatter3D(X, Y, Z, c=sum_total, cmap='coolwarm', depthshade=0)
fig.colorbar(sum_total)

plt.title("DV at departure from Earth")
ax.set_xlabel("Beginning")
ax.set_ylabel("Time of flight")
ax.set_zlabel("Time of flight 2")

plt.show()

When I execute the code, the following error comes into view:

'c' argument has 15 elements, which is not acceptable for use with 'x' with size 3375, 'y' with size 3375.

It seems when I put the array sum_total here, it did not recognize the shape of it.
I try to add the color as c=np.ravel(sum_total) which returns me the graphic with color, but I think it is not given the appropiate color to each point.
Also, when I create the graphic with np.ravel(sum_total), the colorbar gives the following error:

'numpy.ndarray' object has no attribute 'get_array'
Comment: Is the indentation around the for loop over Z correct?
Comment: Yes! It seems to work properly when i checked it out
Answer: I've gone over your code, and changed a couple things.
Firstly, I've added the imports I guessed you wanted to use:
import matplotlib
matplotlib.use('Agg')

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

I've also added some variables to make everything slightly easier to read and less likely to cause bugs:
x = np.linspace(0, 15, 15)
y = np.linspace(0, 30, 15)
z = np.linspace(5, 45, 15)

X, Y, Z = np.meshgrid(x, y, z)

lenX = len(X[0, :, 0])
lenY = len(Y[:, 0, 0])
lenZ = len(Z[0, 0, :])

And implemented these variables in the code:
sumatorio = np.zeros(shape=(lenX, lenY))
sumatorio_1 = np.zeros(shape=(lenY, lenZ))
sum_total = np. zeros(shape=(lenX, lenY, lenZ))
c = np.array([])

for i in range(lenX):
    for j in range(lenY):
       sum_1 = X[0, i, 0] + Y[j, 0, 0]
       sumatorio[i, j] = sum_1
       sum_1_2 = sum_1 * sum_1

I changed the indentation of the 'k for loop':
        for k in range(lenZ):
            sum_2 = sum_1_2 + Z[0, 0, k] + X[0, i, 0]
            sum_total[i, j, k] = sumatorio[i, j] + sumatorio_1[j, k]

fig = plt.figure(figsize=(50.0, 50.0))
ax = fig.add_subplot(111, projection='3d')

ax.scatter3D(X, Y, Z, c=sum_total, cmap='coolwarm', depthshade=0)

The fig.colorbar didn't really make sense to me, I'm not quite sure what you're hoping to achieve with this, so I commented it out.
#fig.colorbar(sum_total)

plt.title("DV at departure from Earth")
ax.set_xlabel("Beginning")
ax.set_ylabel("Time of flight")
ax.set_zlabel("Time of flight 2")

plt.show()

This code runs fine for me. I don't really understand what it does, but I'm sure you know more about that.

4D plot in python matplotlib


Help setting up a Bayes rule problem

Question: I am relatively new to using Bayes rules for continuous variables and am having trouble setting up part of the formula and am looking for help. The example I am trying to work through is the following:
Suppose there are two numbers x and y that were chosen at random. We have a prior belief that x and y were chosen from a standard multivariate normal distribution. We are then given the following piece of information: x+y=1.0.
The question that I am interested in is how this should change our posterior belief about the values of x and y. From Bayes rule:
posterior distribution is proportional to  P(x+y=1 | prior) * P(prior)
What I am stuck on is figuring out what to enter in the formula for P(x+y=1 | prior), would someone be willing to point me in the right direction?
My first thought was that it should be 0, because the volume of a line is zero but then the problem doesn't make much sense. But then I got to thinking that if I had a second such piece of information, say x+2y=5, then I could figure out x and y exactly and it wouldn't make sense for Bayes rule not to be able to make use of this kind of information. Thank you for your help.
Comment: If x and y are mutlivariate, then x+y cannot be one. At the very least, it has to be a multivariate vector of ones, in which case the answer may depend on the dimension. The probability that x+y equals any given value is zero, and that may be another technical difficulty that you may be encountering.
Answer: You should write the problem as:
$$
x \sim {\cal N}(0,1)
\\
y \sim {\cal N}(0,1)
\\
z = x+y
$$
Now condition on the event $z=1$.  The conditional distribution of $z$ is $p(z | x, y) = \delta(z - (x+y))$ where $\delta$ is the Dirac delta function.  In this problem it helps to think of the Dirac delta function as the limit of a Gaussian whose variance is going to zero:
$$
p(z | x,y) = \lim_{v \rightarrow 0} {\cal N}(z; x+y,v)
$$

Help setting up a Bayes rule problem


JavaFx: about quartz scheduler

Question: Hello I have a problem in a routine using quartz scheduler I need to shutdown my Scheduler method:
javafx stop
I can't declare my scheduler out of my stage start:
@Override
    public void start(Stage stage) throws Exception {
        Scheduler s = StdSchedulerFactory.getDefaultScheduler();
        JobDetail j = JobBuilder.newJob(ChecarJob.class).build();
        Trigger t = TriggerBuilder.newTrigger().withIdentity("CroneTrigger")
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(60).repeatForever()).build();
        try {
        s.start();
        try {
            s.scheduleJob(j,t);
        } catch (Exception e) {
             e.printStackTrace();
        }
        } catch (SchedulerException se) {
        se.printStackTrace();
        }
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Principal.fxml")); //carrega fxml
        Scene scene = new Scene(root); //coloca o fxml em uma cena
        stage.setScene(scene); // coloca a cena em uma janela
        stage.show(); //abre a janela
        setStage(stage);

    }

and I need to declare it was outside my start to be able to use shutdown inside stop ()
@Override
    public void stop() {
        UsuarioDAO u = new UsuarioDAO();
                    u.setOffiline();
                    s.shutdown();
                    Platform.exit();
                    System.exit(0);
    }

if I do that I did above I have an error because my Scheduler was created inside a method and is not global
And the scheduler doesn't allow me to create it at global scope for some reason
my code:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import dao.UsuarioDAO;
import dao.qtdRegistrosDAO;
import rotinas.BackupJob;
import rotinas.ChecarJob;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.swing.JOptionPane;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

/**
 * FXML Controller class
 *
 * @author SpiriT
 */
public class Principal extends Application {

    private static Stage stage; //uma janela
    private static qtdRegistrosDAO aQtdRegistrosDAO;
    public Principal() {
    }

    private void blockMultiInstance() {
        try {
            ServerSocket serverSocket = new ServerSocket(9581);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Software já está aberto!", "Atenção", JOptionPane.WARNING_MESSAGE);
            System.exit(0);
        }
    }

    private void backup (){
        try {
            Scheduler sx = StdSchedulerFactory.getDefaultScheduler();
            JobDetail jx = JobBuilder.newJob(BackupJob.class).build();
            Trigger tx = TriggerBuilder.newTrigger().withIdentity("CroneTrigger2")
                    .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(60).repeatForever()).build();
            try {
                sx.start();
                try {
                    sx.scheduleJob(jx,tx);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (SchedulerException se) {
                se.printStackTrace();
            }
        } catch (SchedulerException ex) {
            Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
        public void stop() {
            UsuarioDAO u = new UsuarioDAO();
                        u.setOffiline();
                        s.shutdown();
                        Platform.exit();
                        System.exit(0);
        }

    @Override
    public void start(Stage stage) throws Exception {
        Scheduler s = StdSchedulerFactory.getDefaultScheduler();
        JobDetail j = JobBuilder.newJob(ChecarJob.class).build();
        Trigger t = TriggerBuilder.newTrigger().withIdentity("CroneTrigger")
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(60).repeatForever()).build();
        try {
        s.start();
        try {
            s.scheduleJob(j,t);
        } catch (Exception e) {
             e.printStackTrace();
        }
        } catch (SchedulerException se) {
        se.printStackTrace();
        }
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/Principal.fxml")); //carrega fxml
        Scene scene = new Scene(root); //coloca o fxml em uma cena
        stage.setScene(scene); // coloca a cena em uma janela
        stage.show(); //abre a janela
        setStage(stage);
    }

    public static Stage getStage() {
        return stage;
    }

    public static void setStage(Stage stage) {
        Principal.stage = stage;
    }

    public static void main(String[] args) {
        launch(args);
    }

}

If I raise her out of my start stage I can't

Scheduler s = StdSchedulerFactory.getDefaultScheduler();
JobDetail j = JobBuilder.newJob(ChecarJob.class).build();
Trigger t = TriggerBuilder.newTrigger().withIdentity("CroneTrigger"

Answer:
Define a reference to the scheduler as a member of the Application
class.
Assign the scheduler reference in your start method.
When the application is stopped, call the appropriate method on the scheduler to safely shut it down.

Sample code
public class Principal extends Application {
    private Scheduler s;

    public void start(Stage stage) throws Exception {
        s = StdSchedulerFactory.getDefaultScheduler();
        // other work ...
    }

    public void stop() {
        if (s != null) {
            // pass true as a parameter if you want to wait
            // for scheduled jobs to complete
            // (though it will hang UI if you do that on FX thread).
            s.shutdown();
        }
    }
}

There may be other issues with your code (I haven't checked), and I don't know if this answer will solve the core of your problem, but it will allow you to define a Scheduler instance as a reference in your application, which seems to be something you are asking for.
Comment: Hello i thought it would solve but not when i close the stage is still open
Comment: @Override
    public void stop() {
        if (s != null) {
            // pass true as a parameter if you want to wait
            // for scheduled jobs to complete
            // (though it will hang UI if you do that on FX thread).
            try {
                UsuarioDAO u = new UsuarioDAO();
                u.setOffiline();
                s.shutdown();
                Platform.exit();
                System.exit(0);
   } catch (SchedulerException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
        }
    }
Comment: I can't understand why
Comment: Code I provided should be sufficient to request the Quartz scheduler to shutdown.  Likely you have other issues with your code than the scheduler shutdown request.  Without all of the code to replicate the issue (a [mcve], emphasis on minimal) it may be hard for you to get help.
Comment: You do not need to call `Platform.exit()` and `System.exit(0)` (though that is not the root cause of your issue).  Likely you have a non-daemon thread running (https://stackoverflow.com/questions/19505682/java-daemon-thread-and-non-daemon-thread) which prevents shutdown, or an unexpected exception being thrown which you aren't handling gracefully, or a long running scheduled job which never exits.  You can break your app into minimal parts get it to a state which allows a clean exit, then gradually re-enable services.  [jvisualvm](https://visualvm.github.io) might help.

JavaFx: about quartz scheduler


Estimate mean of a population with multiple samples when the individual sample mean is biased

Question: I am working with datasets of grades going ~15 years back for different classes. I am trying to determine if there is a difference in the average grade for odd years compared to even years. There is a big event going on for several weeks during the exam period every even year close to the university, and I want to see if this affects the students grades.
I am only experienced with working with single samples from a population and estimating mean, variance etc.
My initial though was to find the mean/variance for each year, then estimate the total mean/variance using an unbiased linear estimator weighted by sample size (number of students taking the class that year).
However, I suspect this is not correct because the relative difficulty of the exam changes, this would of course affect every grade for that year. How do I adjust for this bias in the individual sample mean, which I assume is independent from the fact that it is an odd/even year?
Comment: sounds like what you're looking for is a random effects model
Answer: Here is one elementary way to view this question. [It assumes scores in the past few odd years have not differed greatly over time, and similarly for the even numbered years. If you think exams year-to-year may have differed substantially, you could check that by doing a one-way ANOVA for Odd years (and separately) another ANOVA for Even years. If those differences are larger than the difference between Odd and Even, then you'd need to decide what more complicated analysis might untangle the two effects.]
Data. Suppose you  have 8 odd years and 7 even years and about 50 students each year. Make a list of grades $X_i$ in odd years, for $i = 1, 2,\dots, n_1;$ also a list of grades $Y_i$ in even years, for
$i = 1, 2, \dots, n_2.$
Here are summaries of some fake data generated in R to use as an example:
summary(x); length(x); sd(x)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  77.00   83.00   85.00   84.99   87.00   95.00
## 401      # n_1 number of students in odd years
## 3.326394 # SD of odd-year scores

summary(y); length(y); sd(y)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  64.00   71.00   73.00   73.64   76.00   85.00
## 348      # n_2 nr in even yrs
## 3.897763 # SD for even years

Two-sample Welch t test. Then do a Welch (separate-variances) t test to see whether the mean $\mu_1$ for odd years is equal to the mean $\mu_2$ for even years (null hypothesis) or not equal (alternative hypothesis). You can find the formula for the Welch t statistic and for its degrees of freedom in a basic statistics text or online.
Here results of the Welch test from R:
t.test(x, y)

        Welch Two Sample t-test

data:  x and y
t = 42.507, df = 686.39, p-value < 2.2e-16
alternative hypothesis:
  true difference in means is not equal to 0
95 percent confidence interval:
 10.82226 11.87044
sample estimates:
 mean of x mean of y
  84.99002  73.64368

For my fake data, there is a highly significant difference between the sample means $\bar X = 84.99$
and $\bar Y = 73.64,$ as shown by the very small P-value.
[That is because I simulated the data to have different population means $\mu_1 = 85, \mu_2 = 74,$ as shown below---also, to have somewhat different standard deviations.]
set.seed(514)  # for reproducibility
x = round(rnorm(401, 85, 3))
y = round(rnorm(348, 74, 4))


Pergunta Múltipla escolha

Question: Tenho que desenvolver um quiz com javascript, a primeira parte já desenvolvi que são para pegar a resposta de perguntas com apenas 1 resposta correta, mas não estou conseguindo fazer a segunda parte que são as perguntas com mais de uma resposta correta, pensei em utilizar o checkbox, mas não funcionou,vou colocar o código que fiz para uma resposta correta

<input type="radio" name="questao" value="A">resposta 1

<input type="radio" name="questao" value="B">resposta 2

<input type="radio" name="questao" value="C">resposta 3

<input type="radio" name="questao" value="D">resposta 4

var resposta = "D"; // Resposta correta
$("input[name=questao]").on("click", function() {
    var value = $(this).val();
    var mensagem = "";
    resposta == value ? mensagem = "Parabéns, Acertou!" : mensagem = "Resposta errada, tente novamente";
    $("#mensagem").html("" + mensagem + "");
});

Comment: você quer poder selecionar mais de uma opção? ou apenas permitir que seja escolhido uma das respostas corretas?
Comment: Se são mais de uma resposta correta, você **deverá** utilizar o *checkbox*. Poderia [edit] a pergunta e adicionar como fez com esses elementos para entendermos o porquê de não ter funcionado?
Comment: Poder selecionar mais de uma opção e na hora já aparecer se está certo ou errado a resposta
Comment: @Thi100 tente postar mais informações do seu código
Comment: @Thi100 Poseti um código utilizando checkbox para resolver o problema
Answer: Acho que o mais indicado aí seria utilizar radio e usar um if/else e pegar as duas respostas que forem certas:

$("input[name=questao]").on("click", function() {
  var value = $(this).val();

  if(value == 'A' || value == 'D') {
    $("#mensagem").text("Parabéns, Acertou!");
  }
  else {
    $("#mensagem").text("Resposta errada, tente novamente");
  }
});

<input type="radio" name="questao" value="A">resposta 1

<input type="radio" name="questao" value="B">resposta 2

<input type="radio" name="questao" value="C">resposta 3

<input type="radio" name="questao" value="D">resposta 4

Answer: Pode fazer desta forma, que inclusive servirá tanto para radio quanto para checkbox. Só precisa colocar as opções certas em ordem alfabética na variável resposta quando for checkbox com mais de uma opção correta. Por exemplo, se as opções corretas forem A e D: var resposta = "AD";

var resposta = "AD"; // Respostas corretas
$("input[name=questao]").on("click", function() {
    var value = "";
    // seleciona apenas o que foi checado
    var resps = $("input[name=questao]:checked");
    if(resps.length){

       resps.each(function(){
          // concatena os values
          value += $(this).val();
       });

       var mensagem = "";
       resposta == value ? mensagem = "Parabéns, Acertou!" : mensagem = "Resposta errada, tente novamente";
       $("#mensagem").html("" + mensagem + "");
    }else{
       // esvazia a div de mensagem
       $("#mensagem").empty();
    }
});

Opções corretas: A e D

A) <input type="checkbox" name="questao" value="A">resposta 1

B) <input type="checkbox" name="questao" value="B">resposta 2

C) <input type="checkbox" name="questao" value="C">resposta 3

D) <input type="checkbox" name="questao" value="D">resposta 4

Usando radio com o mesmo script acima:

var resposta = "D"; // Respostas corretas
$("input[name=questao]").on("click", function() {
    var value = "";
    // seleciona apenas o que foi checado
    var resps = $("input[name=questao]:checked");
    if(resps.length){

       resps.each(function(){
          // concatena os values
          value += $(this).val();
       });

       var mensagem = "";
       resposta == value ? mensagem = "Parabéns, Acertou!" : mensagem = "Resposta errada, tente novamente";
       $("#mensagem").html("" + mensagem + "");
    }else{
       // esvazia a div de mensagem
       $("#mensagem").empty();
    }
});

Resposta correta: D

A) <input type="radio" name="questao" value="A">resposta 1

B) <input type="radio" name="questao" value="B">resposta 2

C) <input type="radio" name="questao" value="C">resposta 3

D) <input type="radio" name="questao" value="D">resposta 4

Answer: Creio que exista um erro em como você esta utilizando o operador ternário:
  resposta == value ? mensagem = "Parabéns, Acertou!" : mensagem = "Resposta errada, tente novamente";

Tente trocar isso para:
  mesagem = resposta == value ? 'Parabéns, Acertou!' : 'Resposta errada, tente novamente';

Além disso, vocẽ deverá usar <input type='checkbox'> para multipla escolha, e para as respostas certas, voce pode usar um array, seu HTML pode ser assim:

<input type="checkbox" name="questao" value="A">resposta 1

<input type="checkbox" name="questao" value="B">resposta 2

<input type="checkbox" name="questao" value="C">resposta 3

<input type="checkbox" name="questao" value="D">resposta 4

Com isso, seu JS pode mudar para:
var respostasCertas = ['A', 'D'];
var respostasEscolhidas = [];
$('input[name="questao"]').on('change', function() {
    if(this.checked) {
        respostasEscolhidas.push($(this).val());
    } else {
        removeA(respostasEscolhidas, $(this).val());
    }
});

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}

Acima, utilizo uma função de outra pergunta, para remover posição do array pelo valor
Para checkar a resposta voce pode adicioar um  ou um submit
Checar resposta

E, finalmente, criar uma função que checa a resposta:
 function checkResponse() {
    if (respostasCertas.length === respostasEscolhidas.length && respostasCertas.sort().every(function(value, index) { return value === respostasEscolhidas.sort()[index]})) {
        $('#mensagem').text('VOCE ACERTOU');
    } else {
        $('#mensagem').text('TENTE NOVAMENTE');
    }

}

A função acima, foi retirada dessa pergunta
Testei esse código e acho que é exatamente o que procura, espero ter ajudado!
Answer: Mais uma opção

let respostasCorretas = ["D", "A"];

$("#btnConfirmar").on("click", function() {

  let selecionadas = $("input[name='questao']:checked");
  let corretas = 0

  $("input[name='questao']").attr('disabled', 'disabled')

  $.each(selecionadas, function() {
    let resposta = $(this);

    if (respostasCorretas.includes(resposta.val())) {
      resposta.closest('p').addClass('correta');
      corretas++;
    } else {
      resposta.closest('p').addClass('errada');
    }

  });
  let mensagem = "";

  if (corretas == 0)
    mensagem = "Você errou todas as alternativas"
  else if (corretas > 0)
    mensagem = "Você acertou epenas " + corretas + " das alternativas.";

  if (corretas == respostasCorretas.length)
    mensagem = "Parabéns, você acertou todas as alternativas";

  $("#mensagem").html(mensagem);
  $(this).addClass('escondido');
  $("#btnReset").removeClass('escondido');
  $("#mensagem").removeClass('escondido');
});

$("#btnReset").on('click', function() {
  $(this).addClass('escondido');
  $('p').removeClass('correta');
  $('p').removeClass('errada');
  $("input[name='questao']").removeAttr('disabled');
  $("input[name='questao']").prop('checked', false);
  $("#btnConfirmar").removeClass('escondido');
  $("#mensagem").toggleClass('escondido');

});
.correta {
  color: green;
  font-weight: bold;
}

.errada {
  color: red;
  text-decoration: line-through;
}

#mensagem {
  font-weight: bold;
}

.escondido {
  display: none;
}

 Selecione as duas alternativas corretas:

<input type="checkbox" name="questao" value="A"> resposta 1

<input type="checkbox" name="questao" value="B"> resposta 2

<input type="checkbox" name="questao" value="C"> resposta 3

<input type="checkbox" name="questao" value="D"> resposta 4

  <input type="button" id="btnConfirmar" value="Confirmar Resposta" />
  <input type="button" id="btnReset" class="escondido" value="Tentar Novamente" />

Pergunta Múltipla escolha


Is it possible to find out which hash algorithm was used in these strings?

Question: I don't want to reverse it. I just want to be sure what hash algorithm was used on these strings (I'm not sure if it's md5):
<code>d27918bcc2a8562dc4549c2c00111e66
889f071e04755db26579a19f4303654e
47a21a13ee822c1450155bd0033b0f1d
</code>
Is there a way to do it?
One of the source for the strings above is certainly: '9915757678'
Comment: @Acacio Nerull: if you mean the original string is `9915757678`, this is the MD5 hash: `cd182d8bef0540595c9c4abb3e4d6557` which isn't any of those listed in your question...
Comment: Do you have the original strings?
Comment: Not that you'll be able to reliably 'reverse' them either... also, they do look like MD5 checksums, but I could be wrong.
Comment: Do you know what the original text was.  If so just try it.
Comment: I don't have the original text for all of them. But the source for one of these strings should be '9915757678'.
Comment: I'm not going to ask where you got these numbers from, but I *will* point out that any half-competent programmer is going to salt the plaintext, precisely to defeat the sort of attack you're attempting.  Give up.
Answer: They're each 32 characters, so 128 bits. So it could be MD5.
However, there is no way to tell. Any hash function worth its salt will spread the hash values evenly throughout the entire output space, so if you have just a bunch of outputs, there's no way to tell hash functions apart.
Unless you can make some reasonable guesses about the input, and do some brute-forcing, of course.
Comment: "Any hash function worth its salt" - pun intended?
Answer: It fits MD5() hash form (length-wise) but it could be just as well SHA1 hash stored in CHAR(32) field. As others have said - unless you have an example of input value. Then you could use a tool like this:
http://www.insidepro.com/hashes.php
to generate hashes using several diffrent algorithms and try to find if any one fits.
You're even more out of luck, if there was salt added before hashing.
Answer: No certain way, but this looks like MD5.
Comment: @neoneye The decryptor I used was somehow weird, I removed the edit.
Answer: Based on size, these could be one of ntlm or md4 or md5.
I know I'm too late here!, but posting this as I didn't see this possible answer.


Turning off encryption with OpenVPN

Question: I want to run a local OpenVPN for localhost access (loopback), so local encryption is a complete waste of time. So how do I turn off the whole thing? I'm using OpenVPN 2.4.7.
Comment: Then why bother with the VPN in the first place?
Comment: Sandboxes don't usually have a good way to expose a sandbox instance to the internet on its own IP(v6) address with full IP(v6) capabilities. Instead I just get an outbound TCP connection. OpenVPN would allow sandboxes to have public IPv6.
Answer: I believe the following options in your config should do the trick:
<code>cipher none
auth none
</code>
Note: I haven't tried it though.

Turning off encryption with OpenVPN


typescript with require-js how to avoid specifing full path to file in require()

Question: I have 2 files:
baseVM.ts(in bases folder):
class BaseVM {
    a: string;
    data: any;
    constructor() {
        this.data = {};
    }
    getData() {
        return "Hi bros";
    }
}
export = BaseVM;

Example.ts(in someFolder)
import BaseVM = require("baseVM");
class Example extends BaseVM {
    controlModule: KnockoutObservable<Module>;
    data: PolicyOrderDTO;
    constructor() {
        super();
    }
}
export = Example;

and I have also configured require-config(require-config.ts):
requirejs.config({
    baseUrl: "Scripts/app",
    paths: {
        "baseModel": "/bases/baseVM",
        "Example":"/someFolder/Example"
    }
});

require(["Example"], (Example)=>{
   var example = new Example();
   example.getData();
});

But it dont build and show the error in Example.ts in line import BaseVM = require("baseVM");. It says that he cant find file, but to write always the full path is a bit annoying. Thanks in advance.
Answer:
but to write always the full path is a bit annoying

Sadly you need to specify full paths at the moment. IDEs can make it easier : https://github.com/TypeStrong/atom-typescript#relative-paths
Also there is typescript issue tracking this : https://github.com/Microsoft/TypeScript/issues/2338
Comment: It is sad that after 3 years of typescript development there is still no normal integration with AMD... :(


Pickup Upgrade on Les Paul Special II

Question: I live in India and have been playing guitar for the past two years or so.
I have an Epiphone Les Paul Special II connected to a Marshall MG10CF. So its a very simple and a basic rig. I wont be buying a new guitar for a few years as I want to be good with my playing as well sounding good tonally and technically. Hence I need to upgrade my pickups and I have a small budget of about 200 dollars.
I like to play metal, blues, funk and acoustic/pop songs. I love the Stratocaster's bright neck sound and want a similar feel for the les Paul or close to it as much as possible and a very heavy sounding fat bridge like a regular les Paul.
I have shortlisted emg hz h4 and h4a and Seymour Duncan JB sh4 and Jazz neck sh2n.
I don't want to put active pickups as my guitar doesn't have space to put a battery in the cavity.
So guys should I keep it stock or research for alternative brands or any other suggestions.
I will be grateful for your inputs and advice.
Thanks.
Comment: This is more of an opinion question, but honestly: spend the money on a single simple gain booster set to maybe +10db and then a wah pedal, and never turn off the wah (leave it at 75%). For the btight-neck sound, you can add a simple toggle to "coil tap" or split the coils. This is a 5 minute job that requires a toggle, a drill, a soldering iron, and 4 inches of wire. Super simple and you can then toggle between humbucker and single-coil mode. I did this with my HSS strat.
Answer: Why don't you just buy a Strat?   It's much simpler.   It might be equal to the cost of buying new pickups and getting them installed on your Les Paul.   Buying an affordable guitar will allow you to experiment with the sonic possibilities of each instrument and have a spare guitar when strings break.
Answer: Strats and Les Pauls have 2 different scale lengths. The Fender gets a lot of it's "bright neck sound" from it's longer scale length (25.5 inch). The Les Paul has a shorter scale length (24.75 inches) and will sound "warmer". The scale length also dictates the string tension, which, for me, has a huge impact on my playing.
Answer: Yorik's comment has hit this squarely on the head. There is absolutely no need to upgrade the pickups from stock on that guitar. It is just fine for beginners, and fine for experienced players.
Get a gain booster and some form of tone shaper - a wah is simple and cheap, as Yorik mentioned, or you could go with any form of graphic or parametric EQ. These will give you the ability to lift and shape your tone to fit what you want per song.
Answer: You will get MUCH better results with a new $200 amp instead of new pickups. For $200 you can get a very good modeling amp that will be loud enough to gig with. If you don't want to get a new amp you could pick up some pedals instead. Like a nice overdrive or EQ pedal would be good. I don't know if you can get them in India but Tone City pedals are very well priced and they have lots of options, look around!

Pickup Upgrade on Les Paul Special II


$G(t)\leq ct^A$ implies $G(t)\leq c_\epsilon t^{A+\epsilon}$?

Question: Suppose that $G:[0,1]\to [0,\infty]$ is a strictly convex function with $G(0)=0$ and $G\in C^2$. Suppose also that for some $A>1$, whenever $c>0$, we have that $$G(t)\leq  ct^A$$
in some interval $[0,s_c]$, where $s_c$ is a value depending on $c$. Can we find some $\epsilon>0$ and some $c_\epsilon>0$ such that $$G(t)\leq c_\epsilon t^{A+\epsilon}$$
in some interval $[0,s_{c_\epsilon}]$?
Thank you.
Answer: No. Consider for example
$$
G(t)=\frac{t^p}{1+\log(1/t)},\quad p\ge2.
$$
$G$ is $C^2$ and strictly convex on $[\,0,1\,]$. Take $A=p$. Given $c>0$,
$$
G(t)\le c\,t^A,\quad 0\le t\le e^{1-1/c}.
$$
However for any $\epsilon>0$ and $s>0$
$$
\sup_{0\le t\le s}\frac{G(t)}{t^{A+\epsilon}}=\sup_{0\le t\le s}\frac{1}{(1+\log(1/t))t^{\epsilon}}=\infty.
$$
Comment: For any $p\ge2$ and $C>0$: $G(t)-C\,t^{p+\epsilon}=t^p(((1+\log(1/t))^{-1}-C\,t^\epsilon)$. As $t\to0^+$, both terms inside the parenthesis converge to $0$,but $t^\epsilon$ much faster than $((1+\log(1/t))^{-1}$, since $\lim_{t\to0^+}t^\epsilon(1+\log(1/t))=0$. This means that for any $\delta>0$ there exists $T_\delta>0$ such that $t^\epsilon(1+\log(1/t))\le\delta$ on $[0,T_\delta]$, that is $((1+\log(1/t))^{-1}\ge t^\epsilon/\delta$. What happens is that $T_\delta$ is extremely small.
Comment: I am confused @Julian. Let $p=2$ and $f(t)=G(t)-2t^{2+.001}$. Then $f(0)=0$ and $f'(t)\leq 0$ near the origin. Are my calculations wrong?
Comment: Ok thank you @julian.


Number of original toys found after buying $k+1$ packs of milk.

Question: I was trying to play around with the Coupon Collector's Problem and got to solve this related problem:
There is a promotion in the store: you get a free random toy per 1 pack of milk. The collector wants these toys however he can buy only $k+1$ packs of milk. There are $n$ amount of toys in total. How many original toys does he get on average after buying $k+1$ pack of milk?
So let's try to get that expected value.
Obviously, on the very first pack - he gets an original toy. That means that we can set it as a starting point in our imaginary graph: $k$ packs of milk left to consider. And here is my helping chain where each vertex represents current amount of original toys and each edge represents buying next pack of milk:

From this point, after all other packs of milk he will get these amounts of original toys with corresponding probabilities:

$p = 1$ original toy with $\left(\frac{1}{n}\right)^{k}$ probability - he got $k$ same toys and never went upper in this pictured chain.
$p = 2$ original toys with $\sum_{i,j=0}^{i+j=k-1}\left(\frac{1}{n}\right)^{i}\left(\frac{n-1}{n}\right)\left(\frac{2}{n}\right)^{j}=\left(\frac{n-1}{n}\right)\sum_{i,j=0}^{i+j=k-1}\left(\frac{1}{n}\right)^{i}\left(\frac{2}{n}\right)^{j}$ probability because he needs to find another original toy with $\frac{n-1}{n}$ chance and to have $k-1$ horizontal edges in order to stay on the same level.
$p = 3$ original toys with $\sum_{i,j,m=0}^{i+j+m=k-2}\left(\frac{1}{n}\right)^{i}\left(\frac{n-1}{n}\right)\left(\frac{2}{n}\right)^{j}\left(\frac{n-2}{n}\right)\left(\frac{3}{n}\right)^{m}$ for same reasoning.
...
$p = p$ original toys with
$$
f(p)=\sum_{i_1,i_2,\dots,i_p=0}^{i_1+i_2+\dots+i_p=k-p+1}
\left(\frac{1}{n}\right)^{i_1}\left(\frac{n-1}{n}\right)
\left(\frac{2}{n}\right)^{i_2}\left(\frac{n-2}{n}\right)\cdot\cdots
\left(\frac{p-1}{n}\right)^{i_{p-1}}\left(\frac{n-(p-1)}{n}\right)
\left(\frac{p}{n}\right)^{i_{p}}
$$

Now for the expected value we should do:
$$
E = \sum_{p=1}^{n} p f(p) = \sum_{p=1}^{n} p \sum_{i_1,i_2,\dots,i_p=0}^{i_1+i_2+\dots+i_p=k-p+1}
\left(\frac{1}{n}\right)^{i_1}\left(\frac{n-1}{n}\right)
\left(\frac{2}{n}\right)^{i_2}\left(\frac{n-2}{n}\right)\cdot\cdots
\left(\frac{p-1}{n}\right)^{i_{p-1}}\left(\frac{n-(p-1)}{n}\right)
\left(\frac{p}{n}\right)^{i_{p}}
$$
after some transformations I get this:
$$
E = \sum_{p=1}^{n} pf(p) = \sum_{p=1}^{n} \left(\frac{n!}{(n-(p-1))!}\right)\frac{p}{n^k}
\sum_{i_1,i_2,\dots,i_p=0}^{i_1+i_2+\dots+i_p=k-p+1}
1^{i_1} 2^{i_2}\cdot\cdots (p-1)^{i_{p-1}}p^{i_{p}}
$$
And for now, I really can't understand what I should do with this statement next... Help!
Answer: This can also be done using  Stirling numbers. Suppose $m$ coupons are
drawn, then we have from first principles
$$\frac{1}{n^m} \sum_{q=0}^n q {n\choose q}
q! {m\brace q}
= \frac{1}{n^m} \sum_{q=1}^n q {n\choose q}
m! [z^m] (\exp(z)-1)^q
\\ = n \frac{m!}{n^m} [z^m] \sum_{q=1}^n {n-1\choose q-1}
(\exp(z)-1)^q
= n \frac{m!}{n^m} [z^m]
(\exp(z)-1) \exp((n-1)z)
\\ = n\frac{1}{n^m} (n^m - (n-1)^m).$$
This is
$$\bbox[5px,border:2px solid #00A000]{
n \left(1 - \left(1-\frac{1}{n}\right)^m\right)}$$
confirming linarity of  expectation from the answer that  was first to
be posted. This formula has appeared on various occasions..
Answer: Let $X_i$, be a random variable whose value is $1$ if prize number $i$ is found, and $0$ if it is not, for $i=1,2,\dots n$.  You want to compute $$E\left(\sum_{i=1}^n X_i\right)=\sum_{i=1}^nE(X_i)$$ by linearity of expectation.
Can you take it from here?
P.S.  I felt sure that this question must have been asked before, but I couldn't find it.
Comment: so the answer is $ n \left( 1 - \left(\frac{n-1}{n}\right)^k\right) $ ? Oh my god, I can't believe the solution was so simple... It will be even crazier if my final sum somehow can be reduced to this (if I didnt do any mistakes in my chain-approach).
Comment: @Lust_For_Love Shouldn't the exponent be $k+1$ if he buys $k+1$ cartons?
Comment: Oups,you are right.


Improve the quality of an image when I put it into a pdf using reportlab

Question: I'm trying to put an JPG image into a PDF using reportlab like follow, in python language.
<code>
   p = canvas.Canvas(buffer)
   p.drawImage(filename_jpg_image,x,y)
</code>
The problem here is that the image displayed in the pdf does not have the same quality as the original one. I want to know if there are a way to specify the quality in this context, or improve it anyway. Anybody can help me?
Answer: Unfortunately, most tools that put JPEGs into PDFs will uncompress and then (badly) recompress the JPEG.
img2pdf can wrap many (most?) JPEG images into PDFs without changing the compression (without decompressing at all, in fact).
Then you can use pdfrw to pull that PDF onto the reportlab canvas as a form xObject (similar to an image).  There are a few examples in the pdfrw/examples/rl1 directory that show how to do this.
Disclaimer: I am the pdfrw author.


Symmetric PDF proof

Question: If F(xu) = u, then show that if f(-x) = f(x), then x1-u=-xu where:
F is CDF
f is PDF.
In my mind, I understand why this is the case, but I'm having trouble writing a proof to show it.
Thanks
Answer: Suppose $\int_{-\infty}^af(x)dx=u$, and define $I:=\int_{-\infty}^{-a}f(x)dx$. By $x\mapsto -x$, $I=\int_a^\infty f(-x)dx$. Since $f$ is symmetric (or even, if you prefer that term),$$I=\int_a^\infty f(x)dx=\int_{-\infty}^\infty f(x)dx-\int_{-\infty}^af(x)dx=1-u.$$
Comment: It seems as though in this proof that you're under the assumption that $\int_{-\infty}^{-a}f(x)dx=1-u$ at the start. How do you actually get to this point though? I understand the step where you replace x with -x, but it seems as though you're just replacing -u with $\int_{-\infty}^af(x)dx$ in the last step because of the assumption you made in your first statement which you didn't prove.
Comment: Never mind, I figured it out on my own. The proof you wrote was just out of order. It makes more sense to me, and it might make more sense to others in this order.

1. $\int_{-\infty}^af(x)dx=u$
2. $\int_{-\infty}^\infty f(x)dx=1$
3. $\int_a^\infty f(x)dx = 1-u$
4.  $\int_{-\infty}^{-a} f(-x)dx=1-u$.
Comment: @SD'Anc I've rearranged it a little.

Symmetric PDF proof


Is there a way to trace PHP errors logged from Rules?

Question: Occasionally I'm seeing an error in the error_log
<code>[10-Apr-2015 10:16:45 America] PHP Parse error:  syntax error, unexpected 'Some text' (T_STRING) in /home/simulab1/public_html/profiles/commerce_kickstart/modules/contrib/rules/modules/php.eval.inc(146) : eval()'d code on line 1
</code>
This could be coming from any number of Rules we have. Is there any way to pin this down to the specific Rule in question?
TIA
Answer: If Xdebug is installed in the machine, it dumps a stack trace to your Apache logs. That might give you a better hint at the context.
If that fails, look at all your Commerce rules and try to find the one with a execute PHP action.


Como deserializar JSON com C#

Question: Eu tenho esse JSON
[{
"new_as_cod": "0010955",
"as_nome": "NAME",
"as_cpf": "1212121212",
"as_email": "firstname.lastname@example.com",
"as_cep": "88.025-200",
"igr_nome": "1\u00aa IGREJA BATISTA - FLORIANOPOLIS",
"id": "2781",
"valor": "50.00",
"pg_tipo_id": "CC",
"status": "Ativo",
"idstatus": "1"
}]

a classe foi gerada a partir daqui
 public class RootObject
{
    public string new_as_cod { get; set; }
    public string as_nome { get; set; }
    public string as_cpf { get; set; }
    public string as_email { get; set; }
    public string as_cep { get; set; }
    public string igr_nome { get; set; }
    public string id { get; set; }
    public string valor { get; set; }
    public string pg_tipo_id { get; set; }
    public string status { get; set; }
    public string idstatus { get; set; }
}

Tenho tentado usar essa expressão.
RootObject data = JsonConvert.DeserializeObject<RootObject>(stringdate);
as_nome.Text = data.as_nome.ToString();
as_cpf.Text = data.as_cpf.ToString();

Mas está dando este erro.

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.DLL but was not handled in user code Additional information:
  Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'HelloWorldWP.MainPage+RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Comment: Cara, coloca o texto da exception e não um print dela.
Comment: Henrique, clique em [edit] para editar a sua pergunta. Você pode tirar a imagem e colocar o texto da exception, veja a resposta do @OnoSendai, ela está correta. Aliás, bem vindo ao [pt.so]. Veja o [tour] e visite a [help] para poder entender melhor como funciona o site.
Comment: An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.DLL but was not handled in user code

Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'HelloWorldWP.MainPage+RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Answer: Seu JSON é uma coleção contendo um item apenas:
[{..}]

Você deve então deserializá-lo para uma coleção:
List<RootObject> data = JsonConvert.DeserializeObject<List<RootObject>>(stringdate);

Comment: Ele é uma coleção quando tem os colchetes `[...]` @HenriqueAlbuquerque
Comment: @MarconcilioSouza https://www.nuget.org/packages/Newtonsoft.Json/
Comment: Primeiramente obrigado por responder.

Entendi, então esse tipo de JSON é uma coleção.
coloquei essa expressão que você me falou

JsonConvert.DeserializeObject>(stringdate);

continua dando o erro, mas agora nem compila. Não sei se ta faltando algum import. Pois ja coloquei e instalei aquele newtonsoft.json
Comment: Cannot implicitly convert type 'System.Collections.Generic.List' to 'HelloWorldWP.MainPage.RootObject'.
Comment: entendi, ficarei ligado nos tipos de json da proxima vez @jbueno
Comment: @HenriqueAlbuquerque desculpe, meu exemplo continha um erro. Eu corrigi a última linha.
Comment: @OnoSendai eu que peço desculpas por perturbar haha, desculpe, agora que eu entendi que meu JSON é uma lista, na hora de atribuir ele não esta encontrando o as_nome, por exemplo. data.as_nome.ToString();... acho que esta faltando alguma coisa entre a variavel data e o as_nome, ficando dessa forma data.?????.as_nome.ToString();
Comment: @HenriqueAlbuquerque nem estressa, é um prazer ajudar. =) Sua variável `data` agora é uma coleção: Tente, por exemplo, `data[0].as_nome.ToString();` onde zero é o índice do objeto dentro da coleção.
Comment: @OnoSendai GG! rodou legalzinho, valeu mesmo! Estou começando ae com C# e com webservices.
Comment: @HenriqueAlbuquerque legal ler isso! São tecnologias interessantes. Sinta-se à vontade para postar mais perguntas no caso de qualquer dúvida.
Comment: @HenriqueAlbuquerque, JsonConvert faz parte de qual Namespace, não encontrei aqui a ddl nem para referenciar.
Comment: @MarconcilioSouza vc tem que ir no nuget packages e proccurar por json.net, apos instalar... using newtonsoft.json.. que aí funciona.
Comment: @OnoSendai , obrigado!

Como deserializar JSON com C#


Divisibility of a certain two variable polynomial by $x$

Question: Let $F,G \in \mathbb{C}[x,y]$.
(We do not know if $F$ and $G$ have a common zero or not).
Assume that there exists $H(x,y) \in \mathbb{C}[x,y]$ with $H(0,0)=0$,
such that $x$ divides $H(Fy, Gy)$.

When (= under which additional conditions) $x$ divides both $F$ and $G$?

A special case: $H(x,y)=\lambda x+\mu y$. Then $H(Fy, Gy)= \lambda Fy +\mu Gy= y(\lambda F + \mu G)$. Then $x$ divides $\lambda F + \mu G$.
However, it may happen that $x$ does not divide either $F$ or $G$, for example, $\lambda=\mu=1$, $F=x+1$, $G=x-1$.
If $x$ divides $F$, then $x$ also divides $G$, and vice versa.
Any hints and comments are welcome!
Comment: Also, is there a reason you switch back and forth between variables $x$ and $y$ and $X$ and $Y$, or are they the same?
Comment: @Servaes - how is $F(x,y)yG(F(x,y)y, G(x,y)y) - G(x,y)yF(F(x,y)y, G(x,y)y)$ always divisible by $x$? Besides which, it doesn't matter if such an $H$ always exists are not. The question is what additional conditions must $H$ satisfy to guarantee that $x$ also divides both $F$ and $G$.
Comment: @PaulSinclair I guess the mixed use of upper- and lowercase variables tripped me up; I first thought of $H(X,Y)=XG-YF$, but then adjusted this to $H(X,Y)=XG(X,Y)-YF(X,Y)$ which certainly isn't always divisible by $x$. My comment doesn't make sense, I'll delete it and wait for clarification on the matter.
Comment: Are you considering conditions on $H$ alone, or also on $F$ and $G$?
Comment: @user237522 - I took the liberty of removing the variables $X, Y$ and functions $U, V$ from the post. I also found them more confusing than helpful. If you are not satisfied with the change, please feel free to change it back, and I apologize for it.
Comment: @PaulSinclair, thank you, your edit is good (you are right that there is no need for $U$ and $V$, and writing just $Fy$ and $Gy$ is better).
Comment: @Servaes, thanks for your comment; $\{x,y\}$ and $\{X,Y\}$ are indeed the same variables; I apologize for not being clear enough. "Are you considering conditions on $H$ alone, or also on $F$ and $G$?": Any conditions on $\{H,F,G\}$ are welcome.
Answer: Fix the value of $y$ used in $F, G$, and just consider them functions of $x$ only, and include the $y$ multiples in the definitions of these functions instead of listing it separately. So $F = F(x), G = G(x)$ and we are given that $H(0,0) = 0$ and that $H(F(0), G(0)) = 0$, and want conditions so that this implies that $F(0) = 0$ and $G(0) = 0$.
This makes it obvious: the only such condition on $H$ alone is that $H$ can have only one root, namely the given one: $(0,0)$. If it has any other root, then we can choose $F, G$ so that $(F(0), G(0))$ is this root.
But this is impossible. By the fundamental theorem of algebra, for each $y$, either $H(x,y)$ is constant with respect to $x$, or else it has at least one root $x_y$, so $H(x_y, y) = 0$. But if $H$ is constant with respect to $x$ for all $y \ne 0$, then $H$ does not depend on $x$ at all, and therefore $H(F(0), G(0)) = 0$ would not imply that $F(0) = 0$.
So there is no condition on $H$ that will work. The only conditions on $F, G$ that could be added are that $(F(0), G(0))$ must miss the other roots of $H$.
Comment: Thank you very much! Please, could you elaborate more on your last sentence about conditions on $F$ and $G$?
Comment: If you restrict $H$ so that there is some subset of $\Bbb C^2$ guaranteed to have no roots of $H$ other than $(0,0)$, and you restrict the choice of $F, G$ so that $(F(0), G(0))$ has to be in this set, then $H(F(0), G(0)) = 0$ will then imply $(F(0), G(0)) = (0,0)$.
Comment: Thank you! Please, I am not sure if I understand: Is it possible to find such a subset of $S \subsetneq \mathbb{C}^2$? (namely, $(0,0) \in S$ is the only root of $H$, and $(F(0),G(0)) \in S$).
Comment: Sure - you can even define $S = \{(0,0)\} \cup \{(x,y) \mid H(x,y) \ne 0\}$. Then you place the restriction on $F,G$ that $(F(0), G(0)) \in S$. However, it seems to me that this is unlikely to be useful to you. I was just noting the concept against the rare case that something similar would be useful.
Comment: Thank you again.


Precedence while overloading operators C++

Question: I have a class, in which I have overloaded some operators. My code is like this:
myClass << 12 << 14 << 21 << 44

This works well, firstly runs myClass << 12, then myClass << 14.
But I have a problem if I try to do something like this:
myClass << 12 << 14+18 << 36 << 14 << 47

The operator + is overloaded too, and the problem is that 14+18 runs before myClass << 12. I really need to execute firstly myClass << 12 and then 14+18. How can I achieve this?
Edit:
I want to put some numbers and arrays of numbers into a stream. The part of the numbers is solved. As for the arrays of numbers, I was doing something like this:
myClass << 12 << myClass(array,10) << 21 << 19

Where operator () is overloaded, array is the array of numbers and 10 is the length of the array. I'm doing this because I need some way of keeping the length of the array, but the problem is that myClass(array,10) is executed before myClass << 12 . So, in this case, I want firstly to put 12 into the stream and then my arrays of numbers, and I need to know its length.
And, I don't want to use this solution:
myClass << 12
myClass << myClass(array,10)

Because I want to use my code as a library, so my intention is that the end user has flexibility to write everything in a line.
Comment: Have you tried using parenthesis to force evaluation order?  Such as `myClass << 12 << (14 + 18) << 36 << 14 << 47`.  This is the suggested coding style when outputting to standard streams.
Comment: @Mooing Duck It's not a constructor (I thought it was at first too, until I reread the question about 3-4 times), it's `operator()` and presumably instead of returning a string representing the array it immediately writes to the stream.
Comment: You can't overload `operator+` for two ints. What does your *real* code look like?
Comment: Yes, I'm sorry, I'm not using the operator+ like that. It just was an example.
Comment: Why is it a problem that `myClass(array,10)` is executed first?  What does that constructor _do_ exactly?
Comment: Yes, I want to write it to the stream. The problem is that it's executed before `myClass << 12`.
Comment: @MarkB: Is it viable for `operator()` to return a temporary instead of writing directly?
Answer: OK so let's simplify and break down what's going on here. The first part of your call evaluates to something like this:
myClass << 12 << myClass(array,10) becomes myClass.operator<<(12).operator<<(myClass(array, 12) which when notionally spelling out the implicit this parameter becomes something like operator<<(operator<<(myClass, 12), myClass(array, 10))
Now the only thing the standard says about the order of executing operator<<(myClass, 12) and myClass(array, 10) is that both will be executed before the outermost operator<< is called. In your case, it elected to execute the operator() first.
Now, how do we achieve the result you want? First, you could put the parts of the single statement into multiple statements to force the order you desire.
Alternately, you could process the array totally differently. I'd suggest a format_array function:
std::string format_array(array, 10)
{
    // Do stuff
    return string representation of array
}

myClass << 12 << format_array(array,10) << 21 << 19

Original answer based on a different question phrasing:
Since you can't overload operator+(int, int) my psychic question reading skills tell me that your class has both operator<< and operator+ and that the operator+ is some sort of a state-manipulator on your class, that you want to happen after you insert 12 and 14 into the stream.
In that case....don't do that. That's NOT what operator+ is for and why standard streams use manipulators.
But if you absolutely insist: (myClass << 12 << 14) +18 << 36 << 14 << 47
Comment: Thanks. I've editted my question.I hope it's better explained.
Answer: You are running into an issue with sequence  points.  If you want to run the insertions in a guaranteed order then you would have to use
myClass << 12;
myClass << 14+18;
myClass << 36;
myClass << 14;
myClass << 47;

Comment: No, because the function arguments must be calculated before the function can be called.
Comment: Thanks, but I don't want to do that. I want to use my code as a library, so I want that the end user has the flexibility to write all in a line.


Likert scale coding

Question: I have a question on coding a Likert scale in SPSS.
Assuming we have a 7-point Likert scale, a "well-being" score may rank from 1 through 7.
While doing some reading on multi-variate analysis, I've come across a reference that suggests a "deviation score".   That is, it's ranging from [-3, -2, -1, 0, 1, 2, 3].
For later analysis of survey results, which method ("well-being score" vs. "deviation score") will serve me best?    Or are these "apples and oranges"?
Thanks,
EEH
Answer: More like apples and apples.
For most purposes, it won't make any difference in the results, only in how they are interpreted. That can be important. One exception is if you wanted to add a quadratic of the Likert scale.
If you tell us more about what you are doing (e.g. is this the dependent variable? Independent variable? Or just something you are describing (e.g. with frequencies, median, etc) we will be able to give more detailed advice.
Comment: It's more important when it's the DV, I think. When it's the IV in a regression, you are mostly interested in how a change affects the DV.
Comment: All "extent" question are referenced to the independent variables.   There will be a few question for the dependent variables; however, I won't apply Likert scales for the DV-related questions.   Based on the answers from the IV questions, I'd like to proof/disproof the hypotheses.   Did that help?
Comment: Sure, that makes me more sure that my answer applies to your case.
Comment: Thanks... could you please elaborate on "... only in how they are interpreted.  That can be important."?

Likert scale coding


Splash Screen não aparece no app flutter

Question: Olá, estou tendo problemas em mostrar o Splash Screen no meu aplicativo flutter e gostaria de ajuda. Ao abrir o aplicativo ele aparece, mas só fica visível por 1 segundo, mesmo eu colocando um timer de 3 segundos. Isso ocorreu aparentemente depois de ter adicionado o SharedPreferences.
Segue o código:
main.dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<UserModel>(
      create: (context) => UserModel(),
      child: Consumer<UserModel>(
        builder: (context, value, child) {
          return MaterialApp(
            title: 'Onde Está?',
            debugShowCheckedModeBanner: false,

            home: SplashPage(),
          );
        },
      ),
    );
  }
}

splash_page.dart
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:onde_esta/app/share/constant.dart';
import 'package:onde_esta/app/views/list_object.dart';
import 'package:onde_esta/app/widgets/home_page.dart';

String finalEmail;

class SplashPage extends StatefulWidget {
  @override
  SplashPageState createState() => SplashPageState();
}

class SplashPageState extends State<SplashPage> {
  Future getValidationDate() async {
    final SharedPreferences sharedPreferences =
        await SharedPreferences.getInstance();
    var obtainedEmail = sharedPreferences.getString('email');
    setState(() {
      finalEmail = obtainedEmail;
    });
    print('$finalEmail');
  }

  @override
  void initState() {
    getValidationDate().whenComplete(() async {
      Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) {
        return finalEmail == null ? HomePage() : ObjectListScreen();
      }));
    });
    super.initState();
    Timer(
      Duration(seconds: 3),
      () => Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => HomePage()),
      ),
    );
  }

  @override
  Widget build...

Erro no console:
E/flutter (11382): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter (11382): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.
E/flutter (11382): #0      State.context.<anonymous closure>
package:flutter/…/widgets/framework.dart:1088
E/flutter (11382): #1      State.context
package:flutter/…/widgets/framework.dart:1094
E/flutter (11382): #2      SplashPageState.initState.<anonymous closure>
package:onde_esta/…/widgets/splash_page.dart:37
E/flutter (11382): #3      _rootRun  (dart:async/zone.dart:1346:47)
E/flutter (11382): #4      _CustomZone.run  (dart:async/zone.dart:1258:19)
E/flutter (11382): #5      _CustomZone.runGuarded  (dart:async/zone.dart:1162:7)
E/flutter (11382): #6      _CustomZone.bindCallbackGuarded.<anonymous closure>  (dart:async/zone.dart:1202:23)
E/flutter (11382): #7      _rootRun  (dart:async/zone.dart:1354:13)
E/flutter (11382): #8      _CustomZone.run  (dart:async/zone.dart:1258:19)
E/flutter (11382): #9      _CustomZone.bindCallback.<anonymous closure>  (dart:async/zone.dart:1186:23)
E/flutter (11382): #10     Timer._createTimer.<anonymous closure>  (dart:async-patch/timer_patch.dart:18:15)
E/flutter (11382): #11     _Timer._runTimers  (dart:isolate-patch/timer_impl.dart:395:19)
E/flutter (11382): #12     _Timer._handleMessage  (dart:isolate-patch/timer_impl.dart:426:5)
E/flutter (11382): #13     _RawReceivePortImpl._handleMessage  (dart:isolate-patch/isolate_patch.dart:184:12)

Answer: O erro está ocorrendo porque o método getValidationDate() está sendo executado antes da tela ser construída e por isso não tem como atualizar a tela com o setState antes da tela ser construída.
Em vez de usar o Timer, utilize o Future.delayed.
Comment: Obrigada! Funcionou para mim!


Unit testing Typescript in Visual Studio

Question: I have been searching for a way to test Typescript in Visual Studio for 2 days now. It seems that there is an issue in doing this. I have tried using different frameworks i just cannot get this to work in a separate project. Does anyone have any suggestions on how to get this to work in a separate project? Do I need to create a web interface where this can be run?
Thank you.
Answer: Most TypeScript unit testing frameworks run on the command line.
To integrate these with Visual Studio, you can use a Task Runner like Gulp.
Once you have your gulpfile.js set up to run the tests, it will be visible in the Visual Studio "Task Runner Explorer" window CTRL + ALT + Backspace.
You can set a task to run whenever you build your solution by right-clicking it in Task Runner Explorer and selecting "Bindings -> After Build".
Example Gulp file for Karma:
/// <binding AfterBuild='test' />
var gulp = require('gulp');
var Server = require('karma').Server;

gulp.task('test', function (done) {
  new Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});


Finding angles between two planes

Question:
Find the angle between the planes:
  $$\pi_1 : x − 2y + 2z = 1$$
  and
  $$\pi_2 : \begin{pmatrix}
        x \\
        y  \\
        z  \\
        \end{pmatrix} = \begin{pmatrix}
        1 \\
        1  \\
        1  \\
        \end{pmatrix} + \lambda\begin{pmatrix}
        3 \\
        0  \\
        1  \\
        \end{pmatrix} + \mu\begin{pmatrix}
        0 \\
        2  \\
        -1  \\
        \end{pmatrix} ,\ \lambda, \mu \in\mathbb{R}.$$

I'm not sure how to start with this problem and I really can't visualize the angle between the two planes.
So far I've tried visualizing the problem and finding out the vectors of the two planes, but haven't managed to get far.
Comment: The angle between two planes is defined as the angle of their normal vectors.  So the main task is to find a normal vector for the second plane.
Answer: The normal vector to $\pi_1$ is $\begin{pmatrix}1\\-2\\2\end{pmatrix}$.
The normal vector to $\pi_2$ is
$\begin{pmatrix}3\\0\\1\end{pmatrix}\times\begin{pmatrix}0\\2\\-1\end{pmatrix}=\begin{pmatrix}-2\\3\\6\end{pmatrix}$.
The cosine of the angle between these two normals is their dot product divided by the product of their lengths.

Finding angles between two planes


SONAR: config duplicate line for java project

Question: Maybe it is a stupid question, but I cannot find out where can I config the minimal lines of code for duplication check in SONAR. In project settings there is only a switch to turn on cross project check. Any ideas?
B.R.
Answer: We have an open ticket on this: http://jira.codehaus.org/browse/SONARJAVA-91
As a background: Sonar has been using its own duplication detection mechanism since end of 2011 (from Sonar 2.11 IIRC). At that time, a decision was made that the number of lines or the number of tokens should not be configurable, in order to prevent the possibility to fool the engine. However, as the detection mechanism has not reached perfection yet ;-), we will allow to set "sonar.cpd.java.minimumLines" property in the mean time.
Comment: Thanks Fabrice. That means as long as I add sonar.cpd.java.minimumLines property in the maven pom file, it should be working for java project currently. Right?
Comment: No, this means that it currently does not work for Java but will once SONARJAVA-91 is fixed.
Comment: Thanks a lot for the classification.
Answer: this feature is only available for languages other than Java ( http://docs.codehaus.org/display/SONAR/Analysis+Parameters#AnalysisParameters-Duplications )


Duplicação de evento jQuery

Question: Cenário teste
index
<!DOCTYPE html>

    <title></title>

        <button onclick="carregar()">Carregar</button>

inc.php

    <button onclick="clone()">Clonar</button>

Elemento

Simulação
O index, tem um botão que chama por Ajax o conteúdo de inc.php, onde tem uma função que clona o elemento com id="el" pelo botão "clonar" ou por atalho de teclas "Alt+C".
O que acontece é que, cada vez que "recarrega" o conteúdo de inc.php pelo botão "carregar" do index, ele adiciona +1 clone somente pelo atalho, mas não pelo botão, como abaixo:

Dúvida

Por que isso acontece somente com o "atalho" definido?
Comment: @Sam verdade! Valeu!! Kkk
Comment: **1.** Sempre que o evento `keydown` é utilizado no *jQuery*, ele é adicionado (e não substituído). Ou seja, toda vez que a página `inc.php` for carregada, uma nova ação será adicionada no evento supramencionado. **2.** Isso não ocorre com o botão "clonar", pois a função `onclick` sempre terá apenas um comando e a função será substituída. Não sei se deu para entender (qualquer coisa monto um *gif*).
Comment: Creio que vc inverteu no texto (no título está ok): quem duplica é o atalho e não o botão :D
Answer: Isso acontece porque cada vez que você carrega, é criado um novo event listener $(document).keydown na memória, e vai acumulando. No caso do botão isso não ocorre porque ele chama uma função que não duplica no carregamento.
O que você tem que fazer é impedir que o $(document).keydown seja executado a cada carregamento, ou seja, que ele entre apenas 1 vez na memória.
Uma sugestão é criar uma variável (chamei de flag) inicialmente false e colocar o $(document).keydown dentro de um if e alterar o valor da variável para true. Assim, o trecho dentro do if só será executado na primeira vez, evitando duplicar o $(document).keydown:
var flag;

if(!flag){
   flag = true;
   $(document).keydown(function (e) {
      if (e.altKey && e.keyCode == 67) {
         clone();
      }
   });
}

function clone() {
   const template = $('#elementos > #el').last();
   const novo = template.clone();
   $('#elementos').append(novo);
}

Comment: Pode testar. Vai funcionar como uma luva. ;?)
Comment: 100%! Valeuuu! ✌

Duplicação de evento jQuery


Virtual PC on XP

Question: Is there a version of Virtual PC 6 that i can run on XP? And where can i download it from?
Like thisone: http://www.microsoft.com/windows/virtual-pc/default.aspx, but this is only for windows 7.
Comment: This should have been asked at SU, not at SO.
Answer: It's available on Microsoft's website
This site has an archived version.
Answer: Try Virtual Box or VMWare.
Virtual Box is free, you can download it from: http://www.virtualbox.org/
Answer: Yes, there is a version of Virtual PC 6 which runs on XP, although it looks like it was removed from microsoft.com download area. But you can still try to download it from here.

Virtual PC on XP


Installation of SSDs in R610

Question: I am about to order a Dell R610. I have also ordered SATA Intel 730 SSD's for it. Is there anything I need apart from drive trays (G176J) for installation? Ie is there any other back plane this or that which is needed? This seems like a really simple question and maybe the SSD is just screwed into a tray like this And that is the end of it, or maybe there are other adaptors or parts needed? I have tried surfing around but maybe it is so obvious that it is not even stated? Can someone who has done this before tell me?
Thanks,
   Jas
Comment: **Summary Answer**: _Only the drive trays and the SSDs are needed._
Answer: Unless you bought a jank-tastic model that's been unreasonably stripped down, you only need the tray. The drive slides into the SATA ports on the backplane as its guided by the grooves that the tray fits in.

I have tried surfing around but maybe it is so obvious that it is not even stated?

I wasn't going to say anything, but since you brought the topic up... =)
Comment: I agree, but only thing @sysjas must make sure is the SSD drive is supported by the controller. I seen a lot of thread that the some drives are not recognized in the controller. As it seem to be bougth by another source than Dell.
Comment: Thanks for the comments. I guess there are standard holes on the standard tray and you just need to make sure the back of the SSD is flush with the end of the tray? Then when you insert the tray the distance to the back plane is exactly correct. If that is correct, then that is all I need to know... Thanks!
Comment: @sysjas There's no holes in the back of the tray, it's just an open backed holder that you screw into the hard drive. The screws will line up just right and you won't have to worry about if anything is flush with anything else.
Comment: @Wesley, Ahh. Great. I had thought that might be the case that the distances are all standard and there is no way to "stuff it up". Good to know. Thanks!
Comment: @sysjas Your project trackabus looks interesting. Let me know if you need any consulting. It's what I do; contact details in my profile. =)
Comment: @yagmoth555, thanks for the comment. Yes I searched around a lot before settling on the Intel 730 SSDs. From what I have read they have the best chance of being compatible while being in normal pricing territory (i.e. not the 2 to 3 times more expensive for enterprise level drives). The Intel 730s appear to be very similar to their enterprise cousins the S3500/S3700 series see [anandtech](http://www.anandtech.com/show/7803/intel-ssd-730-480gb-review) they have power-loss protection, the same controller, etc.

Installation of SSDs in R610


Identifiable but has no consistent estimator

Question: Let $P_\theta$ denote the distribution of the random variable $X$. The distribution depends on the parameter $\theta$ that lies in some parameter space $\Theta$. Consider a function $f(\theta)$ of $\theta$.
We say that $f(\theta)$ is identifiable if $f(\theta_1)\neq f(\theta_2)$ implies $P_{\theta_1}\neq P_{\theta_2}$ for every $\theta_1,\theta_2$ in $\Theta$. We say that $f(\theta)$ is estimable if $E_\theta g(X)=f(\theta)$ for all $\theta$ in $\Theta$ for some function $g$, where $E_\theta$ denotes the expected value computed from $P_\theta$.
It is easy to show that if $f(\theta)$ is estimable then it is identifiable. One can also find counterexamples where the converse is false. For example, suppose $X$ follows a Bernoulli distribution $P_\theta$ with parameter $\theta=P(X=1)\in(0,1)$, then nonlinear functions of $\theta$ are not estimable.
Can someone provide a simple example where a parameter is identifiable but has no estimator that is consistent for it? In the above example $\sqrt{\theta}$ has a consistent estimator, namely $\sqrt{n^{-1}\sum_{i=1}^nx_i}$ for a random sample $\{x_i\}_{i=1}^n$ from $P_\theta$.
Comment: Also, I do not see the "error". The definition seems equivalent to the one on Wikipedia in the "Identifiability" article. https://en.wikipedia.org/wiki/Identifiability
Comment: @whuber Do you want to argue that I misunderstand what is written in the above quote?
Comment: You have given an inverse definition of identifiability and it corresponds to a tautology, since your description is equivalent to part of the definition of parameter: namely, a parameter has to be a definite property of the distribution.  The remarks about estimability appear to be irrelevant to the question, making them somewhat puzzling.  Please check over your post to verify that it correctly reflects what you want to ask.
Comment: @whuber Thank you for your comment I made a few changes to my original post. What do you think now? The definitions are from "Statistical Models: Theory and Practice (Revised Edition)" by David A. Freedman from 2009. I do not see the tautology and in any case this is the question I want to ask. If someone believes the question itself does not make sense, then please do explain.
Comment: I doubt such an error would have appeared in any of Freedman's books, so you might want to re-read your source carefully.
Comment: @whuber On page 125 he writes: "Suppose $P_\theta$ is the probability distribution that governs $X$. The distribution depends on the parameter $\theta$. Think of $X$ as observable, so $P_\theta$ is something we can determine. The function $f(\theta)$ is identifiable if $f(\theta_1)\neq f(\theta_2)$ implies $P_{\theta_1}\neq P_{\theta_2}$ for every pair $(\theta_1,\theta_2)$ of parameter values ... the function $f(\theta)$ is estimable if there is a function $g$ with $E_\theta[g(X)]=f(\theta)$ for all values of $\theta$, where $E_\theta$ stands for the expected value computed from $P_\theta$"
Comment: Maybe (probably) I am misunderstanding your notation.  The difficulty I run into is that only two concepts are relevant here--distribution $P$ and quantity $f$ (the "estimand")--but your characterization introduces a third parameter.  An estimand is *identifiable* when the association between distribution and estimand is one-to-one.  Any other parameters, like $\theta,$ that might be floating around are irrelevant (and, as I am finding, confusing!). This is relevant because any non-consistent estimator must (therefore) be unable to distinguish two distinct distributions asymptotically.
Comment: There are probably discontinuous examples. Eg with your Bernoulli example, consider $f(x)=x$ for $x<\frac12$, $f(x)=2+x$ for $x>\frac12$, and $f(\frac12)=1$. So $f(\frac12)$ is  not the average of its left-hand and right-hand limits, and I doubt that $f$ has an everywhere-consistent estimator.
Answer: Denote the following:
$$\theta\in \Theta= [0,1] \qquad x_1,...,x_n\underset{iid}{\sim}P_\theta(x)$$
$$P_\theta(x)=(1-\theta)\frac{1}{\delta(\theta)}\left(1-\frac{|x-\theta|}{\delta(\theta)}\right)I_{\{ |x-\theta|\le \delta(\theta) \}}+\frac{\theta}{2}I_{\left\{ |x|\le 1 \right\}}$$
where $\delta(\theta)$ is a continuous decreasing function of $\theta$ with $\delta(0)=1$ and $0<\delta(\theta)\le 1-\theta$. For example, we can take $\delta(\theta)=(1-\theta)\exp\left( -(1-\theta)^{-4}+1 \right)$:

The model is indeed identifiable (it's different for every $\theta$, check and see) and the MLE $\hat{\theta}_n$ exists: The density is positive and continuous in $\Theta$ for any $x$, the log-likelihood function $\ell_n(\theta)=\sum_{m=1}^{n}{\log{P_\theta(x_m)}}$ is continuous and gets a maximum on $[0,1]$.
However, it can be shown (with some effort, going through maximizers and Borell-Cantelli) that the MLE $\hat{\theta}_n$ converges almost-surely to 1 for any $\theta_0\in\Theta$, hence the MLE is inconsistent.
Comment: (+1) Thanks! Interesting example. But, in general, that the MLE is inconsistent does not imply that there is no other estimator that is consistent. Maybe my original question is too general.
Comment: You've asked for an example of an identifiable estimator which is inconsistent - there it is. It doesn't imply that all estimators would behave like that, and in general we have to find really pathological cases for such violations of a thumb rule.
Comment: My original question was: "Can someone provide a simple example where a parameter is identifiable but has no estimator that is consistent for it?" I did not specifically ask for an identifiable estimator which is inconsistent. (Of course, if a parameter is identifiable but has no consistent estimator, then any estimator provided will be inconsistent, inclduing the MLE.) If you disagree, then perhaps I don't understand English properly. Nevertheless, I appreciate your answer.


Integral of pdf

Question: I need to find the integral for this pdf but I don't know if I need to, or can, take the integral of two variables at the same time.
$$
f(x;\theta)=\frac{x}{\theta^2} e^{-x^2/(2\theta^2)} ,\quad x>0;
$$
$$
f(x;\theta)= 0,\text{ otherwise}.
$$
I'm guessing you just do piecewise integration for $x$ and forget $\theta$ but I want to be sure.
Answer: $$
\int_0^x \frac u \theta e^{-(u/\theta)^2/2} \, \frac{du}\theta = \int _0^{x/\theta} v e^{-v^2/2}\, dv = \int _0^{x/\theta} e^{-v^2/2}\Big( v\, dv\Big) = \int_0^{x^2/(2\theta^2)} e^{-w} \, dw = \cdots\cdots
$$
Answer: $\theta$ is a parameter in this density function (the random variable is called a Rayleigh random variable). If you want to find the CDF, it is $$F_X(t;\theta) = \int_0^t \frac{x}{\theta^2} e^{-x^2/(2\theta^2)}\,\mathrm dx$$ where the antiderivative of the integrand is known. Figure it out for yourself by computing
the derivative of $\exp(-x^2/2\theta^2)$. The end result is
$F_X(t;\theta) = (1-\exp(-t^2/2\theta^2))\mathbf 1_{t \geq 0}$

Integral of pdf


Set of Sylow subgroups of a finite group

Question: Let $G$ be a finite group, $p$ a prime dividing the order of $G$, and let $S=\{ P: P \text{ is a Sylow }p \text{-subgroup of }G\}$. Let $x\in G.$ Then $S=S^{x}.$
Proof. Since the elements of $S^{x}$ are Sylow subgroups of $G$, then $S^{x} \subseteq S$ .Define the function $f:S \rightarrow S^{x}$ by $f(P)=P^{x}$. Let $P_{1}, P_{2}$ be elements of $S$.
$f$ is well defined.
If $P_{1}=P_{2}$, then $P_{1}^{x}=P_{2}^{x}$ and so $f(P_{1})=f(P_{2})$.
$f$ is one-to-one.
If $f(P_{1})=f(P_{2})$, then $P_{1}^{x}=P_{2}^{x}$ and so $P_{1}=P_{2}$.
$f$ is onto.
Let $P^{x} \in S^{x}$. Then we have $P \in S$ such that $f(P)=P^{x}$.
Thus $S=S^{x}$
Is the above true?
Comment: To me it seems that you have shown that $S$ and $S^x$ have the same cardinality (same number of elements) by constructing a bijection between $S$ and $S^x$, but this is not enough (and not needed at all for the proof) for the equality $S = S^x$. What you need to show is that every element of $S$ is in $S^x$ and conversely, every element of $S^x$ is in $S$. Then the two sets are equal.
Comment: Another approach is to map $S^x$ back to $S$ by the map taking any $P$ to $P^{x^{-1}}$, which is inverse to the map taking $P$ to $P^x$.
Comment: @m.k.: Since the elements of $S^{x}$ are Sylow subgroups of $G$, then $S^{x}\subseteq S$. By the above proof $|S^{x}|=|S|$ and so we must have $S^{x}=S$.
Answer: Well, because of the finiteness, if you have a bijection and $S^x\subseteq S$ then it indeed follows that $S^x=S$.
Probably, it's simpler to argue further that $S^{x^{-1}}\subseteq S$, and now using your bijection $f$, we get $S=\big(S^{x^{-1}}\big)^x \subseteq S^x\subseteq S$.


Ler uma SMS recebida

Question: Um App recebe um SMS e a partir do texto executa uma função.
Para isso é necessário ler a SMS e efetuar a comparação no APP, mas para isso deve-se
ler, palavra por palavra, linha por linha ou fazer uma comparação se contém tal palavra nessa SMS.
A SMS vai ter o seguinte conteúdo.
Caso ocorra uma mudança de estado:
MONIT-110
E05-ATI
E06-DES
E a de todas as saídas:
STATUS-110
E01-DES
E02-DES
E03-DES
E04-DES
E05-DES
E06-DES
E07-DES
E08-DES
E09-DES
E10-DES
E11-DES
S01-DES
S02-DES
S03-DES
S04-DES
S05-DES
S06-DES
Para cada uma dessas linhas tem um comando diferente a ser executado.
Código responsável pela MSG recebida:
public class ReceberSms extends BroadcastReceiver {
    private static final String CATEGORIA = "acqua";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i(CATEGORIA, ">" + intent.getAction());

        Sms sms = new Sms();
        //Lê a mensagem
        SmsMessage msg = sms.receberMensagem(intent);
        String celular = msg.getDisplayOriginatingAddress();
        String mensagem = msg.getDisplayMessageBody();
        //pegar essa msg e jogar nas configurações

        String texto = "ReceberSms: recebeu sms[" + celular + "] -> " + mensagem;
        Log.i(CATEGORIA, texto);
        Toast.makeText(context, texto, Toast.LENGTH_SHORT).show();
}

}//fim

Comment: Vendo que você já tem o texto completo, acho que basta chamar o método `split`, passando o separador dos comandos. Seria legal talvez incluir um exemplo pra ajudar a encontrar a solução.
Comment: Não entendi bem qual é a dúvida... Mas acredito que seja como quebrar o texto em *tokens*?
Comment: A sms que recebo contem comandos a duvida é como posso ler o conteúdo da sms para identificar os comandos que estão nela. Acho que seria como quebrar o texto em tokens mas não sei como fazer isso.
Answer: Talves seja necessário que seja construído através de um vetor de objeto. Observe este código:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ReceiveSMSActivity extends Activity{

    static TextView messageBox;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        messageBox=(TextView)findViewById(R.id.messageBox);
    }

    public static void updateMessageBox(String msg)
    {
        messageBox.append(msg);
    }

}

Esta aqui detecta e processa a mensagem:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class TextMessageReceiver extends BroadcastReceiver{

    public void onReceive(Context context, Intent intent)
    {
        Bundle bundle=intent.getExtras();

        Object[] messages=(Object[])bundle.get("pdus");
        SmsMessage[] sms=new SmsMessage[messages.length];

        for(int n=0;n<messages.length;n++){
            sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
        }

        for(SmsMessage msg:sms){
            ReceiveSMSActivity.updateMessageBox("\nFrom: "+msg.getOriginatingAddress()+"\n"+
                    "Message: "+msg.getMessageBody()+"\n");
        }
    }
}

Acho que falta como outro usuário disse, um comando, veja se consegue com este modelo acima.
Answer: Se a string la do final do seu codigo ja contem fim de linha, mensagem, que vc leu na linha abaixo:
String mensagem = msg.getDisplayMessageBody();

Você pode utilizar o Split, como já citado pelo @Wakim, pela quebra de linhas e dopois pelo '-', e por ultimo um Switch para executar os comandos, ficaria algo assim:
String[] linhas = mensagem.split("\n"); // Veja qual o seu caracter de fim de linha.

for (String l : linhas){
   switch (l) {
         case "E01-DES":
             ...
             break;
         case "E02-DES":
             ...
         case ...

             break;
         default:
             Log.i("ALERTA","Sinal recebido não suportado: " + l);
     }
}

Observe que este código é apenas um exemplo, eu faria esta função com o Switch fora do FOR, ou ainda separaria cada linha em duas novas Strings, e faria talvez uma função genérica para executar cada uma das ações. Mas precisaria de mais informações do seu código para isso.

Ler uma SMS recebida


Using SSE to speed up lower_bound function

Question:
In a project I'm currently working on I often need to find the lowest possible index in a sorted array at which an element can be inserted (like std::lower_bound in C++).
It seems pretty attractive to me to use SSE to speed up my algorithm since I'm working with uint32 arrays which size is typically the size of a processor cache line.
I've never used SSE instructions before, so I can't manage to figure out what an SSE implementation of this function would looks like. Please give hints to help me write it out optimally wtih SSE.
Comment: Take time to do some research. Then think about it and perhaps try a few things to get a "feel" of how it works. Then ask a more directed question -- there is no question here.
Comment: I found the pcmpled which compare 4 32bits packed integers with a 32bit operand, but I cannot managed to find how to get the result of this instruction. Maybe you could point out a good reference on how to use this instruction (or the corresponding intrinsic) if you have one?
Comment: Seems like I was wrong; pcmpled compare two vector4 of 32bit integers and fill a vec4 with 0 and 1 depending on the result of the comparison. Nothing exploitable for me. Seems like Billy ONeal is right, SSE will be no use for me.
Answer: Nothing like std::lower_bound is going to scale well using SSE. The reason SSE makes things faster is that it allows you to do several calculations at once. For example, a single SSE instruction might result in 4 multiply operations going on at once. However, the way std::lower_bound operates cannot be parallelized, because each step in the algorithm requires the comparison results of previous steps. Plus, it's already O(lg n), and as a result unlikely to be a bottleneck.
Moreover, before moving to inline assembly, you should know that whenever you use inline assembly, you defeat most compiler optimizations that might occur on that section of your program, and often as a result your program will be slower -- compilers usually write better assembler than us humans do.
If you want to use SSE, you are better off using intrinsics -- special "functions" or keywords provided by the compiler, which call the SSE instruction but otherwise allow optimizations to occur. Such intrinsics are available in Microsoft's Visual C++, as well as the GNU Compiler Collection. (And probably most any compiler. Consult your compiler's documentation)
Rather than trying to speed up std::lower_bound using SSE, you should try to not need to call it in the first place. For example, if you're constantly inserting elements into the vector using lower_bound, you should know what you've effectively created is insertion sort, and a poor insertion sort at that, which will require quadradic time. You would likely be better off simply putting your new elements on the end of the vector, and then sorting the vector when you need it sorted, which reduces things to an O(n lg n) sort. If your data access patterns are such that you would be resorting too often then you should use something like a std::set instead, which provides O(lg n) operations for insertions, rather than the O(n + lg n) insertions you're currently getting with the vectors.
And of course, remember to benchmark :)


How to use BitmapData.fillRect()?

Question: When I use it, the only thing that is filled is a white rectangle, doesn't matter the parameter.
This is what I do:
var map:Bitmap = new Bitmap (new BitmapData(200,200))
map.bitmapData.fillRect(new Rectangle(0,0,100,100),0xFF0000)

A 100x100 rectangle is added to the bitmap, but it is always a white shape. I want it to be red, as set in the parameter (0xFF0000).
Answer: The color argument should be in ARGB format, meaning the first value is the alpha. Not sure what happens when you send in a 3 byte value instead of a 4. Try 0xFFFF0000 instead.
Hope that helps!
Comment: My experience is it treats `0xFF0000` like `0x00FF0000`, which is 0% opacity red, ie nothing. How he got white out of that I'm unsure.
Answer: map.bitmapData.fillRect(new Rectangle(0,0,100,100),0xFFFF0000)

Answer: Discovered the answer already. I was parsing a RGB parameter for the color, while I should be passing an ARGB.
Thus, because I want red, I should write 0xFFFF0000, instead of 0xFF0000
var map:Bitmap = new Bitmap (new BitmapData(200,200))
map.bitmapData.fillRect(new Rectangle(0,0,100,100),0xFFFF0000)

Answer: import gs.TweenMax;
import fl.transitions.easing.*;
import flash.display.Bitmap;
import flash.display.BitmapData;
var container:Sprite = new Sprite();
var b:Box = new Box();
b.x = b.y = 0;
container.addChild(b);
var bmd:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
var bmp:Bitmap = new Bitmap(bmd);
this.addChild(bmp);
TweenMax.to(b, 1.5, {x: 525, y: 375, ease: Regular.easeOut, onComplete: doComplete});
function doComplete():void
{
    this.removeEventListener(Event.ENTER_FRAME, drawAnimation);
}
this.addEventListener(Event.ENTER_FRAME, drawAnimation);
function drawAnimation(evt:Event):void
{
    bmd.fillRect(bmd.rect, 0);
    bmd.draw(container);
}

bmd.fillRect(bmd.rect, 0);
it basically fill's the area of the BitmapData object with a transparency by using the size of the BitmapData's rectangle to define the area to fill. A VERY handy little trick to know when working with BitmapData. If you take out this line of code you will see that the box is still moving across but leaving "streaks" behind it.
for more information you can go here
http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000787.html
Answer: If you use a BitmapData that is not transparent you can define the color with a regular hex number.
var map:Bitmap = new Bitmap (new BitmapData(200,200,false))
map.bitmapData.fillRect(new Rectangle(0,0,100,100),0xFF0000)

But if you use a transparent BitmapData you must use the ARGB format:
var map:Bitmap = new Bitmap (new BitmapData(200,200))
map.bitmapData.fillRect(new Rectangle(0,0,100,100),0xFFFF0000)

How to use BitmapData.fillRect()?