Which is the most reliable means of copying archives using binary deltas across Windows SMB shares?

Question: I've been searching for the quickest way to copy some WAR and JAR files for huge software deployments between Windows systems. Clearly, multithreaded robocopy or any rsync protocol implementation will offer some increase in performance, but I'd like to know if there's a better option.
I am not looking for some GUI backup solution that mangles filenames or copies the files into incremental backup archives.
I'm interested if anyone has experience with copying across Windows network shares between domains via binary deltas or diffs. I've been looking at such technologies as DFS replication and rdiff-backup (which I believe lacks the ability to handle archives on Windows). I'd like to hear from others who have evaluated these types of technologies for copying between Windows systems. I need to learn which binary delta copy solution is the most viable and whether you would trust it for critical software deployments where every bit must match.
Answer: Theoretically there is no assurance that you can transfer a message and it was not changed. No hashing/signing algorithm can offer 100% certainty that the data was not tempered. However, you can have a probability that is close to 100% that the data is intact if you use a good hashing algorithm.
So the larger the files are the more data you transfer, you have greater chances for some data to change without breaking the hash.
Practically you will see more problems from human mistakes - like programming errors, than changed files that have the same hash.
Comment: That wasn't the question I asked. I'm specifically looking for copy mechanisms that will synchronize a binary archive between two Windows servers by transferring only the binary deltas. The hashing algorithm isn't the issue, unless we want to verify the data was copied accurately.

I only want to know which binary delta-based copy mechanisms are reliable for Windows servers, if any.
Comment: The integrity of data depends on the hashing algorithm used and, may be, on the software bugs.
Comment: Well, it's more the software bugs that concern me. A lot of tribal knowledge around here says that Windows DFS replication used to be flaky in the 2000-2003 timeframe. In Windows Server 2003 R2, remote differential compression (RDC) was added to speed transfers. This satisfies our need for copying only the binary bits that changed in a large WAR archive, but I have no knowledge whether the service reliability issues were also fixed at that point. Clearly, choice of hashing technology has an impact, but it's not our highest concern.
Comment: You will always face uncertainty when using computers. Even if they are supposed to be predictable. You just have to be prepared for the edge cases too.
Answer: If it is about software deployment and you want to transfer binary deltas in a situation where you know the previous state, you might take a look at xdelta - it's not GUI and it's not a transfer protocol, but it does create binary deltas very efficiently and may be used in a software distribution scenario.
Comment: This is helpful, but xdelta won't transfer binary deltas for compressed archives on Windows. We're mostly copying WARs and JARs, so it doesn't yet have the necessary functionality. We're now looking at a commercial product like Repliweb R-1.
Comment: xdelta would create binary deltas for everything. Files compressed with an adaptive algorithm are usually not very good at being *deltaed*, but this is a different problem - mainly the one of the archiver. There are gzip patches to be "rsync-friendly" (i.e. give up some of the adaptive characteristics to improve the ability to get deltas), possibly there is something similar for ZIPs too. Without that, you would need to decompress before taking deltas / applying them - annoying, but doable, especially if you do not cryptosign your archives.


Import for custom product prices for customer groups?

Question: I work for a company that has a concept of pricing rules for our different customers, or in other words different prices for certain customers for certain products. I have found that it is possible to add customer-group product-level fixed cost adjustments, but in order to do that someone would manually have to type in the products and fill in the fixed price values, and that would be very time consuming for thousands of products for all of the different customers.
So I am wondering if there is some way to import fixed price values for products for a specific customer group? Or even if there is a faster way at all than going in and clicking one at a time on all of the different products.
Answer: If your store is on BigCommerce Enterprise, we have an upcoming feature called Price Lists that might be able to help you.
I'd be happy to get you guys into the beta if you're on the appropriate plan.


When are two morphisms of sheaves the same?

Question: Suppose I have two morphism $\phi_1, \phi_2 : F \rightarrow G$, where
$F$ and $G$ are sheaves of sets on $X$.
Is it enough to show that $\phi_1(X) = \phi_2(X)$ (i.e. as maps
from $F(X)$ to $G(X)$) to show that the two morphisms between sheaves are the same?
Thanks!
Comment: You can well have $F(X)=G(X)=0$, and in that case your condition does not give much!
Comment: Thank you very much for all the helpful comments and answers!
Answer: $F$ may have literally no global sections at all. For example, if $F$ is any connected non-trivial cover of the circle, then $F$ has no global sections but nonetheless has non-trivial automorphisms.
However, it is true that two morphisms of sheaves (on a topological space) are equal if and only if the induced morphisms of stalks are equal.
Comment: I think the last statement can be strengthened if we allow $F$ to be a presheaf: So let $X$ be a topological space, $\mathscr{F}$ a presheaf and $\mathscr{G}$ a sheaf on $X$, and $\varphi$, $\psi:\mathscr{F}\to \mathscr{G}$ two morphisms of presheaves. Then $\varphi=\psi$ if and only if $\varphi_x=\psi_x$ for all $x\in X$. Is that true?
Comment: Yes, that's right. Besides, any such morphisms factor through the sheafification.
Answer: For example, pick any non-zero $F$ with no non-zero global sections, and look at the identity map $F\to F$ and at the zero map $F\to F$.
Comment: If you add hypotheses, you'll get more lucky: flasque or soft or...
Comment: Notice that Tom's question is about sheaves of sets. But you refer to sheaves of abelian groups. (Of course this doesn't change much.)
Comment: Sheaves of abelian groups are sheaves of sets!
Comment: No, they have underlying sheaves of sets. It doesn't make sense to say that a sheaf of sets is zero or not. The term "zero" is not defined ... of course you all know this. My comment is for Tom.
Comment: A sheaf of groups is an abelian group object in the category of sheaves of sets, Martin. As I am talking to humans, the "underlying" part is essentially just noise.
Comment: I don't understand how this example solves the problem. I mean in order to show that the correct answer to Toms question is "No!" we have to find two different morphisms $\phi_1$ and $\phi_2$ with ${\phi_1}_X={\phi_2}_X$. In your example ${\phi_1}_X$ is the identity map and ${\phi_2}_X$ is the zero map. So we don't have ${\phi_1}_X={\phi_2}_X$. So how does it help us?
Comment: $\phi_{1,X}$ is the identity map of the zero abelian group, which happens to coincide with the zero map from the zero abelian group to itself.
Comment: Oh, I misread "with no non-zero global sections". I read "with non-zero global sections", so what you mean is only one global section.


Hint for getting started on $L_1$-norm question

Question: Let $X$ be equipped with $L_1$-norm, how do I show that the set $X$ is dense in $L_1$, where $X$ is the set with all elements ${x\in{L^1}}$ such that $${\sum^{\infty}_{n=1}n{|}x_n{|}<\infty}?$$
Answer: Let $(y_n) \in L^1$ be arbitrary. Given a small $\varepsilon > 0$, we want to find $(x_n) \in X$ such that
$$
\|(x_n) - (y_n)\|_{L^1} = \sum_{n = 1}^\infty |x_n - y_n| < \varepsilon.
$$
Here's a hint. Note that the head sequence $(z_n) := (y_1, \dots, y_N, 0, 0, \dots)$ is an element of $X$. What do you get if you compute $\|(z_n) - (y_n)\|_{L^1}$?


How to solve/factor polynomials with coefficients that are dot products?

Question: I need to solve the following equation:
$$
4\left(\vec{a}\cdot\vec{a}\right)t^3+6\left(\vec{a}\cdot\vec{v}\right)t^2+\left(2\vec{v}\cdot\vec{v}+4\vec{a}\cdot\vec{s}\right)t+2\left(\vec{v}\cdot\vec{s}\right)  = 0
$$
for $t$, where $\vec{a}, \vec{v}, \vec{s}$ are known vectors. I managed to obtain the following factorization:
$$
\left(2\vec{a}t^2+2\vec{v}t+2\vec{s}\right)\left(2\vec{a}t+\vec{v}\right) = 0
$$
However, I run into a problem when actually finding $t$ using this factorization. For instance, one solution would be where the second factor is $0$:
$$ t = \frac{-\vec{v}}{2\vec{a}} $$
But how would you divide two vectors? I have a similar problem when using the quadratic formula with the first factor. The factorization seems correct to me but clearly I am doing something wrong. Is there a way to factor the equation while preserving dot products or perhaps another method to resolve my issue? Thanks!
Also, for context, I am trying to solve the Closest Point of Approach problem with two bodies moving with constant acceleration rather than constant velocity, which is what most resources I have found assume. I can use a solver to find the necessary $t$ values but an analytical solution would be great for computational purposes.
I found a similar question asked here before but it does not look like anyone found an analytical solution. It's an old question and I am not sure how to contact the author to see if he found a solution. Here's a link: https://stackoverflow.com/questions/24244432/collision-detection-between-two-accelerating-spheres-with-no-initial-velocity
Comment: IMHO, unfortunately, your factorization does not provide a way to have an analytical solution better than to look directly for an analytical solution using Cardano's formulas for a third degree equation.
Comment: Are your vectors $\vec{a},\vec{v},\vec{s}$ coplanar ?
Comment: Pay attention, a dot product $\vec{U} \cdot \vec{V}$ is zero if either $\vec{U}=0$ or $\vec{V}=0$ (particular cases) $ \ \color{red}{O}\color{red}{R}: \ \ \vec{U} \perp \vec{V}$, the latter being the general case.
Answer: Here is a clarification of your find-a-root problem, transforming it into a minimization problem that can be tackled with different, efficient tools (though not with analytical formulas), explaining what you call the (equivalent) "Closest point approach".
First of all, let it be clear that a dot product $\vec{U} \cdot \vec{V}$ is zero if

either $\vec{U}=0$ or $\vec{V}=0$
$\color{red}{O}\color{red}{R}: \ \ \vec{U} \perp \vec{V}$,

the latter being the general case.
Your equation deserves to be written in the following way :
$$\tag{1}2 \underbrace{\left(\vec{a}t^2+\vec{v}t+\vec{s}\right)}_{\vec{P(t)}}
 \cdot \underbrace{\left(2\vec{a}t+\vec{v}\right)}_{\vec{P'(t)}} = 0$$
where $\vec{P'(t)}$ is plainly the derivative of $\vec{P(t)}$ with respect to $t$.
But in  (1), i.e., in $2 \vec{P(t)} \cdot  \vec {P'(t)}=0$ we recognize the following differentiation :
$$\tag{2} \tfrac{d}{dt}\vec{\|P(t)\|^2} = 0$$
Thus (2), which expresses that a certain derivative is zero, is equivalent to find an extremum of function $\vec{\|P(t)\|^2}$ (in fact a minimum due to the convexity of the issue)
This function (of $t$) describes a curve, which is in fact a parabola (nothing surprizing for a move with constant acceleration!).
Thus our issue is to find the point of this curve that is closest to the origin.
If we assume that vectors $\vec{a},\vec{v},\vec{s}$ are coplanar, all the information is gathered in the figure below.
Consider the cyan circle as the limit position of a circle centered at the origin that has been inflated till it comes in contact with the parabola. The contact point corresponds to a particular value $t_0$ of $t$. The directing vector of the common tangent to the parabola and to the limit circle at this point is represented with a magenta color;  in particular, it is orthogonal to the corresponding radius of the circle (the other magenta vector).
Edit : Why is parametric curve
$$\tag{3}\vec{P(t)}:=\vec{s}+t\vec{v}+t^2\vec{a}$$
a parabola ? Here is an explanation. First, let us define a new axes' origin $\Omega$ by setting $\vec{s}=\vec{0\Omega}$. It means that with respect to this new origin, (3) can be written $\vec{\tilde P(t)}=t\vec{v}+t^2\vec{a}$. Now, with this new origin $\Omega$, taking "slant axes" defined by $\vec{v}$ and $\vec{a}$ one gets equation $y=x^2$, the simplest possible equation for a parabola.
Comment: You haven't answered my question about coplanarity of vectors $\vec{a},\vec{v},\vec{s}$. Besides, could you say if you have understood my solution or if some points are obscure ? (I have added some explanations at the end). Think that Math SE is done for promoting interactions between people.
Comment: Apologize for not responding earlier and thank you for the answer! Yes they are coplanar. The geometric intuition is great and something I did not see at all. But I mainly wish to find an analytic solution as I will be using a computer program to solve this equation for hundreds of vectors
Comment: For a computer, an iterative solution is a good alternative.


How do you program a custom hypothesis test in R?

Question: There are a number of interesting hypothesis tests programmed in R, where the output of the test appears in a nice user-friendly format.  For example, here is the output of Welch's T-test using the t.test function in the stats package.
#Run a T-test on some example data
X <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
Y <- c(19, 20, 44, 45, 8, 29, 26, 59, 35, 50);
TEST <- stats::t.test(X,Y);

#Print the TEST object
TEST;

        Welch Two Sample t-test

data:  X and Y
t = -0.13444, df = 10.204, p-value = 0.8957
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -12.27046  10.87046
sample estimates:
mean of x mean of y
     32.8      33.5

As you can see, the output for this test is in a user-friendly format that gives all the required information relating to the output of the test.  It gives this output in a format that is different to the standard output when you call an R object.

Question: Suppose you encounter a type of hypothesis test that is not in any of the existing R packages, and you want to program this test as a function so that you can run it easily on new data, and get a nice user-friendly output like the one above.  How do you program this?
Comment: This thread will be useful to many visitors to CV but it's not on topic--it really belongs on [SO].
Answer: Here's what you need to do in general
Hypothesis testing functions in R create and output a list object of class h.test.  This type of object has a specific set of required components set out in its documentation, and it also has a special method of printing under the print.htest setting in the global environment.  That printing method draws out information from the list, but prints it in the user-friendly way you see in the output in the question.  The list should contain the components set out below, including naming several of the objects with a names attribute.  (You are some other optional components shown in the linked documentation.)

Textual description of test

method: A character string giving the name of the hypothesis test.  This will appear as the first sentence of the print output.

data.name: A character string giving a description of the data, which usually includes reference to the names of the data vectors used in the test.  For this part it is useful to use the substitute and deparse functions to extract the names of the user inputs to the function as the appropriate names (example shown below).

Specification of hypotheses

null.value: A numeric variable giving the value of the parameter under the null hypothesis (with a names attribute).

alternative: A character string set to greater, less or two-sided, to specify the direction of the alternative hypothesis relative to the null value.

Test statistic and p-value

estimate: The estimated value of the parameter (with a names attribute).  This value will be a function of the data inputs for the testing function.

statistic: The value of the test statistic (with a names attribute).  This value will either be a direct function of the data inputs for the testing function, or a function of the parameter estimate.

p.value: The p-value for the test (which should be a number between zero and one).  This value will be a function of the test statistic.

Confidence interval (optional)

conf.int: A confidence interval represented by a vector with two elements, where the first is the lower bound and the second is the upper bound (with a conf.level attribute giving the confidence level).  If you are using this component, it is desirable to require the function to take a significance level as an input, in order to specify the desired confidence level.

In order to create a custom hypothesis-testing function, you will need to create a function that produces a list containing the required components shown above, customised to your particular test.  For the substantive parts of the test (i.e., the estimate, test statistic, p-value, and confidence interval), you will need to use the appropriate formulae for your particular test.  Note that you can put these elements in any order in your list, so long as all the required elements are there.
You can also add other components to the list if you wish.  It is good practice to add an initial part of your function to check the inputs to the function, to ensure that they are of the correct form, and to stop the function and give error messages if the input is defective in some way.  Once your list is created, you set the class of the object to h.test and output the object at the end of the function.

Here's an example of implementation for a particular test
In a related question I gave an example of code for a hypothesis test taken from Tarone (1979).  Below is a slightly modified version of that code that serves as an example for how you can program a function for a custom hypothesis test.
Observe that the code first checks the inputs, and then builds up each of the required components of the test, using the appropriate names and formulae for that specific test.  Once these components have been computed, we create a list object called TEST, composed of these elements, and we set its class to h.test.  We output this object at the end of the function.  (It is also worth observing the code for data.name, which extracts the variable names that are input by the user.)
Tarone.test <- function(N, M) {

    #Check validity of inputs
    if(!(all(N == as.integer(N)))) { stop("Error: Number of trials should be integers"); }
    if(min(N) < 1) { stop("Error: Number of trials should be positive"); }
    if(!(all(M == as.integer(M)))) { stop("Error: Count values should be integers"); }
    if(min(M) < 0) { stop("Error: Count values cannot be negative"); }
    if(any(M > N)) { stop("Error: Observed count value exceeds number of trials"); }

    #Set description of test and data
    method      <- "Tarone's Z test";
    data.name   <- paste0(deparse(substitute(M)), " successes from ",
                          deparse(substitute(N)), " trials");

    #Set null and alternative hypotheses
    null.value  <- 0;
    attr(null.value, "names") <- "dispersion parameter";
    alternative <- "greater";

    #Calculate test statistics
    estimate    <- sum(M)/sum(N);
    attr(estimate, "names") <- "proportion parameter";
    S           <- ifelse(estimate == 1, sum(N),
                          sum((M - N*estimate)^2/(estimate*(1 - estimate))));
    statistic   <- (S - sum(N))/sqrt(2*sum(N*(N-1)));
    attr(statistic, "names") <- "z";

    #Calculate p-value
    p.value     <- 2*pnorm(-abs(statistic), 0, 1);
    attr(p.value, "names") <- NULL;

    #Create htest object
    TEST        <- list(method = method, data.name = data.name,
                        null.value = null.value, alternative = alternative,
                        estimate = estimate, statistic = statistic, p.value = p.value);
    class(TEST) <- "htest";
    TEST; }

Below we create some count data to implement this test and see what the output looks like.  As you can see, the output is the same user-friendly output you get for other hypothesis tests in R, where the components of the test have been pulled out of the list and presented in a nice simple manner.  The output shows the name of the test and describes the data, and then it gives the test statistic and p-value for the test.  It also describes the alternative hypothesis and gives the sample estimate of the parameter.
#Generate example data
TRIALS <- c(30, 32, 40, 28, 29, 35, 30, 34, 31, 39);
COUNTS <- c( 9, 10, 22, 15,  8, 19, 16, 19, 15, 10);

#Apply Tarone's test to the example data
TEST <- Tarone.test(TRIALS, COUNTS);
TEST;

        Tarone's Z test

data:  COUNTS successes from TRIALS trials
z = 2.5988, p-value = 0.009355
alternative hypothesis: true dispersion parameter is greater than 0
sample estimates:
proportion parameter
           0.4359756

Answer: The hypothesis test functions in the stats package use classic S3 object-orientated programming. You write a function that creates a "htest" object, which is a list with a standard set of components, and R has a built-in print method for objects of that class. The user-level function is traditionally called something like yourname.test but can have any name. It can have any appropriate arguments.

Type ?t.test to see the definition of a "htest" object.
See stats:::t.test.default to see an example of a function that creates a "htest" object.
See stats:::print.htest to see how the user-friendly output is created.

Here is a toy example that performs a very simple chisquare test:
demo.test <- function(s2, df=1)
{
  pval <- pchisq(s2, df, lower.tail=FALSE)
  out <- list(
    statistic=s2,
    parameter=NULL,
    p.value=pval,
    null.value=NULL,
    alternative="greater",
    method="demo",
    data.name="s2")
  class(out) <- "htest"
  out
}

Then
> TEST <- demo.test(30, df=10)
> TEST

        demo

data:  s2
= 30, p-value = 0.0008566
alternative hypothesis: greater

If you want to be fancier, you can make your function S3 generic (like the stats package functions) in order to handle different types of input (e.g., a formula instead of data vectors). But an ordinary function like the above example might satisfy your needs.


Technique for integration of following forms

Question: Recently, I've been facing a no. of problems that involve integral of the type:  $\int f(x)dx/f'(x)$ and also of the type $f(x)/√f'(x)$.
So, is there any special method for such type of questions?
One such question was $$\int (x+sinx) \frac1{cosx+1} $$
Clearly this is of the first type. I could make out that such questions must involve the use of integration by parts but I'm unable to apply that. It makes the problem more complex.
Any help is appreciated.
Answer:
$$\int\frac{f'(x)}{f(x)}\space\text{d}x=\ln|f(x)|+\text{C}$$

If you want to use integration by parts, you'll get:
$$\int y(x)z'(x)\space\text{d}x=y(x)z(x)-\int y'(x)z(x)\space\text{d}x$$
So, set $y(x)=f(x)$ and $z'(x)=\frac{1}{\sqrt{f'(x)}}$:
$$\int\frac{f(x)}{\sqrt{f'(x)}}\space\text{d}x=f(x)\cdot\int\frac{1}{\sqrt{f'(x)}}\space\text{d}x-\int\left[f'(x)\cdot\int\frac{1}{\sqrt{f'(x)}}\space\text{d}x\right]\space\text{d}x$$

Now, notice for $\frac{x+\sin(x)}{1+\cos(x)}$ that you cannot use (1) because:
$$\frac{x+\sin(x)}{1+\cos(x)}=\frac{x+\sin(x)}{\frac{\text{d}}{\text{d}x}\left(x+\sin(x)\right)}\ne\frac{\frac{\text{d}}{\text{d}x}\left(x+\sin(x)\right)}{x+\sin(x)}$$
Comment: Thanks.I now tried the technique you mentioned and it made this problem way easy to solve. Just wanted to ask, will this work on all such type of integrals?
Comment: @AmritanshSinghal You're welcome. I'm glad that I could help. And yes of course it does, because you can get to this 'rule' without substituting a function for $f(x)$.


Dificuldade na metodologia de programação e migração do mysqli para o PDO

Question: Olá, pessoal.
Sempre programei na parte do Back-End (com PHP) utilizando o mysqli, porém após ler alguns artigos e comentários, cheguei a conclusão que preciso mudar minha método de programar para o PDO (Por motivos de Segurança e organização dos códigos) e futuramente passar a utilizar o paradigma de Orientação à Objetos, ao invés do meu já tradicional padrão estruturado.
Minha dúvida é a seguinte, sempre fiz o código com mysqli da forma abaixo:

<?php

  //SELECT QUE RETORNA OS DADOS PARA O AJAX
    $select_empresas = "SELECT * from tbl_lista_empresas order by EMPRESA";
    $lista_empresas = mysqli_query($conecta, $select_empresas);

    if(!$lista_empresas)
    {
     die("Erro no Banco - Erro no Select na tabela lista_empresas");
     exit;
    }

    $retorno_empresas = array();
    //PASSANDO OS DADOS DO SELECT PARA UM ARRAY
    while($linha_empresas = mysqli_fetch_object($lista_empresas))
    {
     $retorno_empresas[] = $linha_empresas;
    }

        echo json_encode($retorno_empresas);

?>

Geralmente recebo uma requisição do AJAX, e (quase sempre é desse mesma forma), realizo uma consulta no PHP com mysqli, passo o resultado da consulta para um ARRAY e retorno o resultado da consulta para o AJAX no formato JSON.

E assim eu recebo os dados no AJAX

//Função que faz a alteração dos dados do funcionário
function alterar_empresas(alterarempresas) {
  $.ajax({
    url: "../banco/banco-sistema/pagina-cadastrar-empresas/alterar-empresas.php",
    type: "post",
    data: alterarempresas.serialize(),
    cache: false

  }).done(function(retornoempresas) {
    $.each($.parseJSON(retornoempresas), function(chave, valor) {

      $("input#cod").val(valor.COD);
      $("input#empresa").val(valor.EMPRESA);
      $("select#tributacao").val(valor.TRIBUTACAO);

    });

  }).fail(function() {
    console.log("Erro ao atualizar");
  }).always(function(retornoempresas) {
    console.log(retornoempresas);
  });
}

Basicamente sempre utilizo esse padrão de programação.
Minha dúvida talvez seja simples pra vocês, como eu faria esse mesmo processo no PHP utilizando PDO e como eu pegaria esses dados no retorno do AJAX (presumo que seja da mesma forma no AJAX).
Minha dúvida é principalmente na parte do While no PHP.
Obrigado!
Answer: Não existe muito mistério.

//Abre a conexão
$PDO = db_connect();

//SQL para contar o total de registros
$sql_count = "SELECT COUNT(*) AS total FROM users ORDER BY name ASC";

//SQL para selecionar os registros
$sql = "SELECT id, name, email, gender, birthdate FROM users ORDER BY name ASC";

//Conta o total de registros.
$stmt_count = $PDO->prepare($sql_count);
$stmt_count->execute();
$total = $stmt_count->fetchColumn();

//Seleciona os registros
$stmt = $PDO->prepare($sql);
$stmt->execute();

//Lista os usuário
while ($user = $stmt->fetch(PDO::FETCH_ASSOC)){
 echo $user['email']
}

Créditos: https://github.com/marciellioliveira/crud-php-pdo/blob/master/index.php
Comment: Não. A diferença é que você não passa parâmetros. Use assim `$all = $stmt->fetchAll()`
Comment: Sim. um array. cada elemento vai ser outro array com as propriedades de cada linha
Comment: O fetchColumn do PDO se assemelha ao affected_rows do mysqli ?
Comment: O mysqli_affected_rows retorna o número de linhas afetadas pela operação anterior já o fetchColumn(1) em um select retorna o valor da coluna que você passa como parâmetro na função. Se o select retorna um valor como em `$sql_count = "SELECT COUNT(*) AS total FROM users ORDER BY name ASC";` então ele retorna esse valor. Portnto comportamentos diferentes.
Comment: Beleza, Átila. Eu vi algo sobre isso aqui: $stmt->fetchAll(PDO::FETCH_ASSOC). Isso não substituiria aquele While ali ?
Comment: Sim. é uma alternativa mais limpa
Comment: Mas tem exatamente a mesma função ?
Comment: Mas o $all vai ser um array ?


Derivation of the polarization identities?

Question: For a real (or complex) inner product space $V$, the inner product can be expressed in terms of the norm as either
$$
\langle x,y\rangle=\frac{1}{4}(\|x+y\|^2-\|x-y\|^2)
$$
or
$$
\langle x,y\rangle=\frac{1}{4}(\|x+y\|^2-\|x-y\|^2+i\|x+iy\|^2-i\|x-iy\|^2)
$$
respectively.
These identities are not hard to verify directly once they are given. I would like to know, is there a systematic way one would derive these from scratch without knowing them beforehand, or are both polarization identities just clever observations?
Comment: In the first case, the identity is one of the standard ways to recover a symmetric bilinear form $B(x,y)$ from its values on the diagonal, $B(x,x)$, which is a quadratic form: $B(x+y,x+y) = B(x,x) + 2B(x,y) + B(y,y)$ and $B(x-y,x-y) = B(x,x) - 2B(x,y) + B(y,y)$. Subtract the second equation from the first and solve for $B(x,y)$. It's like asking how to write $xy$ in terms of squares: from $(x+y)^2 = x^2 + 2xy + y^2$ and $(x-y)^2 = x^2 - 2xy + y^2$, subtract the second equation from the first and solve for $xy$.
Comment: Such formulas are similar to how one can show a product of $L^2$-functions $f$ and $g$ is an $L^1$-function: write $fg = (1/2)((f+g)^2 - f^2 - g^2)$, so if you accept that $L^2$-functions are closed under addition then each term on the right side of the formula has a finite integral, and hence $|fg|$ is integrable.
Comment: The more conventional way to recover a symmetric bilinear form from its values on the diagonal just uses the equation $B(x+y,x+y) = B(x,x) + 2B(x,y) + B(y,y)$, where all terms have equal arguments except the $B(x,y)$-term, and solving for that term gives us $B(x,y) = (1/2)(B(x+y,x+y) - B(x,x) - B(y,y))$.
Comment: Interesting, thanks Kcd.
Comment: Pythagoras dixit...
Answer: I explained in the comments to the question how the polarization identity for real inner products can be discovered by looking at the associated quadratic form at $x+y$ and $x-y$, which in their separate ways lead to a sum of terms that involves a single term $B(x,y)$.  Here I'll discuss the complex case.
Let $H(x,y)$ be a Hermitian form, so $\overline{H(x,y)} = H(y,x)$ and the single-variable function $Q(x) = H(x,x)$ satisfies $Q(cx) = H(cx,cx) = c\overline{c}H(x,x) = |c|^2Q(x)$ for $c \in {\mathbf C}$.  Let's play the same game as in the real case by looking at $Q(x+y)$ and $Q(x-y)$:
\begin{eqnarray*}
Q(x+y) & = & H(x+y,x+y) \\ & = & H(x,x) + H(x,y) + H(y,x) + H(y,y) \\ & = & Q(x) + 2{\rm Re}(H(x,y)) + Q(y)
\end{eqnarray*}
and
\begin{eqnarray*}
Q(x-y) & = & H(x-y,x-y) \\ & = & H(x,x) - H(x,y) - H(y,x) + H(y,y) \\ & = & Q(x) - 2{\rm Re}(H(x,y)) + Q(y).
\end{eqnarray*}
Therefore we can solve for the real part of $H(x,y)$ by subtracting the second result from the first:
$$
Q(x+y) - Q(x-y) = 4{\rm Re}(H(x,y)) \Longrightarrow {\rm Re}(H(x,y)) = \frac{1}{4}(Q(x+y) - Q(x-y)).
$$
That is the first part of the complex polarization formula.  To get a formula for the imaginary part, note that ${\rm Im}(H(x,y)) = {\rm Re}(-iH(x,y)) = {\rm Re}(H(x,iy))$, so if we run through the above work with $iy$ in place of $y$ then we get
$$
{\rm Im}(H(x,y)) = {\rm Re}(H(x,iy)) = \frac{1}{4}(Q(x+iy) - Q(x-iy)).
$$
If we write $H(x,y)$ as ${\rm Re}(H(x,y)) + i{\rm Im}(H(x,y))$ and feed the formulas for the real and imaginary parts of $H(x,y)$ into this, the complex polarization formula appears.
We don't have to use $Q(x+y)$ and $Q(x-y)$, or $Q(x+iy)$ and $Q(x-iy)$; just one of each would suffice: since $Q(x+y) = Q(x) + 2{\rm Re}(H(x,y)) + Q(y)$, we have
$$
{\rm Re}(H(x,y)) = \frac{1}{2}(Q(x+y) - Q(x) - Q(y)),
$$
and
$$
{\rm Im}(H(x,y)) = {\rm Re}(H(x,iy)) = \frac{1}{2}(Q(x+iy) - Q(x) - Q(iy)),
$$
and $Q(iy) = Q(y)$, so
\begin{eqnarray*}
H(x,y) & = & {\rm Re}(H(x,y)) + i{\rm Im}(H(x,y)) \\
& = & \frac{1}{2}(Q(x+y) - Q(x) - Q(y) + i(Q(x+iy) - Q(x) - Q(y))) \\
& = & \frac{1}{2}(Q(x+y) + iQ(x+iy) - (1+i)Q(x) - (1+i)Q(y)).
\end{eqnarray*}
Finally, what happens for a Hermitian form on a vector space over an arbitrary field? Let $V$ be a vector space over a field $F$ and $\sigma$ be an automorphism of $F$ with order $2$. If $H \colon V \times V \rightarrow F$ is $\sigma$-Hermitian, so $H(w,v) = \sigma(H(v,w))$, then is $H$ determined by the function $Q(v) = H(v,v)$? For $a \in F$,
$$
Q(av+w) = ({\rm N}a)Q(v) + Q(w) + {\rm Tr}(aH(v,w)),
$$
where ${\rm N}$ and ${\rm Tr}$ are the norm and trace maps $F \rightarrow F^\sigma$ (where $F^\sigma$ is the fixed field of $\sigma$ on $F$, so the extension $F/F^\sigma$ has degree 2 and is Galois). From the nondegeneracy of the trace pairing on separable extensions, such as $F/F^\sigma$, the above formula as $a$ varies in $F$ shows $Q$-values determine $H$-values, even if $F$ has characteristic 2, when the usual polarization formula over $\mathbf C$, with division by 4, makes no sense.
Answer: Let me give a different sort of explanation as to where the formula comes from, at least in the real case.
Say we have a normed vector space $V$ whose norm is known to come from some (unknown) inner product and we want to compute $\langle x, y \rangle$ for two vectors $x, y \in V$.  Let $W$ be the subspace spanned by $x$ and $y$.  (Assume $x$ and $y$ are linearly independent for the moment.)
If we can indeed reconstruct the inner product from the norm, then $W$ may as well be $\mathbb{R}^2$ with the usual dot product.  Drawing $x$ and $y$, we have a picture like this:

It should be obvious from the picture that $t$, and hence the inner product, is uniquely determined.  Of course
$$\langle x, y \rangle = ||x|| \, ||y|| \cos(t),$$
and by the law of cosines we have
$$||x+y||^2 = ||x||^2 + ||y||^2 - 2 ||x|| \, ||y|| \cos (\pi - t),$$
$$||x-y||^2 = ||x||^2 + ||y||^2 - 2 ||x|| \, ||y|| \cos (t).$$
Subtracting and substituting, we obtain
$$||x+y||^2 - ||x-y||^2 = 4\langle x, y \rangle.$$
Hopefully that gives a bit more intuition for where the equations are coming from.
Answer: Here is yet another way to look at it (complex case):
$$ \begin{aligned}\sum_{k=0}^3 i^k\|x+i^ky\|^2
 &=\sum_{k=0}^3 i^k\bigl(\|x\|^2+\|y^2\|+\langle x,i^ky\rangle+\langle i^ky,x\rangle\bigr)
\\&=\sum_{k=0}^3 \bigl(i^k\|x\|^2+i^k\|y\|^2+\langle x,y\rangle+i^{2k}\langle y,x\rangle\bigr)
\\&=4\langle x,y\rangle
\end{aligned}$$
because $\sum_{k=0}^3i^k=\sum_{k=0}^3i^{2k}=0$.
Now you can imagine replacing $i$ by other roots of unity and adjusting the sum correspondingly.
Comment: Seems like any $n$th root of unity except $n=1, 2$ would work!
Comment: @prime235711 Indeed, any $n$th root of unity different from $\pm1$ will work, when $n\ge3$. (Note that $-1$ is an $n$th root of unity when $n$ is even, so we explicitly have to exclude it.)


Magento trigger JS on add to cart

Question: I'm working on a new shopping sidebar that appears on mouseover etc. While I have all the basic functionality up and working the one thing I am having issues with is the following.
I would like the popup to appear for x seconds (via a js function) once an item has been added to cart and the page reloads.
I'm having greatly difficulty finding where to insert this call to the JS, or the general add to cart success messages.
does anyone have any ideas where it is located?
Thanks
Comment: obvious questions here:  1) what magento version are you using (community, etc); 2.) are you building this as a global sidebar or as a page-specific sidebar (as magento depends on block-level code to create views)?  3.) what code have you written so far?
Comment: i'm using community 1.7, it's a modification of the sidebar block called through the header. as far as showing code goes i thought it a tad bit unnecessary as the code itself works fine, i just can't find where to call my JS function from.
Comment: Are you trying to do something like this http://www.aliceandolivia.com/ona-leather-bustier-gown.html, when a product is added to cart you will see a summary of your cart for a few second?
Answer: If this should be shown before the Page is new loaded, you use for example a onClick Event on the addToCart Elements.
If it should be shown, after the Page is new loaded, you need an observer for the AddToCart event, which sets a variable in I think the Session and you add a js trigger, if this variable is true (and set it false after this).

Magento trigger JS on add to cart


Jquery slimjet event delegation not working

Question: again I have huge problem.
First thing I use Slimjet Web Browser with Tampermonkey for chrome.
I can't use in script $('.class:first') or $('.class:contains(...)') etc becouse always I get error

TypeError: V[g].exec is not a function

Someone know why?
Now I'm trying to add to div with specific class link which do something after click on it. I try everything but event fires only once if it works...
var collapse1 = $('')
    .html($('')
    .attr('id', 'alli1')
    .attr('href', '#')
    .text("Kliknij tutaj aby rozwinąć opis"));

$('.clan-desc').first().html(collapse1);

$($('.clan-desc').get(0)).on('click', '#alli1', function(event) {
  if ($(this).text() === "Kliknij tutaj aby rozwinąć opis") {
    $('.clan-desc').first().html(alliance_txt1).append(this);
    $(this).text("Kliknij tutaj aby zwinąć opis");
  } else {
    $(this).text("Kliknij tutaj aby rozwinąć opis");
  }
  event.preventDefault();
});

When I doing like this I have same error like up. Ofc I tried to
$($('.clan-desc').first()).on('click', '#alli1', function(event){...});
or
$(document).on('click', '#alli1', function(event){...});
Always the same error.
Comment: ofc $('.clan-desc') exists on page. There are 2 div with the same class, without id's.
Answer:         function handler(event){
            if ($('#alli1').text()==="Kliknij tutaj aby zwinąć opis"){
                $('.clan-desc').first().html('').append(collapse1);
                $('#alli1').text("Kliknij tutaj aby rozwinąć opis");
            }else{
                $('.clan-desc').first().html(alliance_txt1).append(collapse1);
                $('#alli1').text("Kliknij tutaj aby zwinąć opis");
            }
            event.preventDefault();
        }
        var collapse1 = $('').html($('').attr('id', 'alli1').attr('href',    '#').text("Kliknij tutaj aby rozwinąć opis"));
        $('.clan-desc').first().html('').append(function(){
        return collapse1;
        }).on('click', handler);

I tried to make something like this. It works but I want to:
    .on('click', '#alli1', handler);


Convergence of $\int_b^\infty \left(\sqrt{\sqrt{x+a} - \sqrt{x}} - \sqrt{\sqrt{x} - \sqrt{x-b}}\right)dx$

Question: For what pairs $(a, b)$ of positive real numbers does the improper integral
\begin{equation}
    \int_b^\infty \left(\sqrt{\sqrt{x+a} - \sqrt{x}} - \sqrt{\sqrt{x} - \sqrt{x-b}}\right)dx
\end{equation}
converge.
I conjecture that $a = b$, but I'm not sure how to approach the proof. Some hints would be greatly appreciated!
Answer: 1. If you are aware of the Big-O notation, then using the Taylor's Theorem, we get
$$\sqrt{1+\varepsilon} = 1 + \frac{1}{2}\varepsilon + \mathcal{O}(\varepsilon^2) \quad \text{as} \quad \varepsilon \to 0.$$
As such,
$$ \sqrt{x+a} = \sqrt{x} \sqrt{1 + \frac{a}{x}} = \sqrt{x} + \frac{a}{2\sqrt{x}} + \mathcal{O}\left(\frac{1}{x^{3/2}}\right) \quad \text{as} \quad x \to \infty, $$
and similarly
$$ \sqrt{x-b} = \sqrt{x} - \frac{b}{2\sqrt{x}} + \mathcal{O}\left(\frac{1}{x^{3/2}}\right) \quad \text{as} \quad x \to \infty. $$
Plugging this back and applying the same estimate again,
$$ \sqrt{\sqrt{x+a} - \sqrt{x}}
= \sqrt{\frac{a}{2\sqrt{x}} + \mathcal{O}\left(\frac{1}{x^{3/2}}\right)}
= \sqrt{\frac{a}{2}} \frac{1}{x^{1/4}} + \mathcal{O}\left(\frac{1}{x^{5/4}}\right) $$
and
$$ \sqrt{\sqrt{x} - \sqrt{x-b}}
= \sqrt{\frac{b}{2}} \frac{1}{x^{1/4}} + \mathcal{O}\left(\frac{1}{x^{5/4}}\right). $$
Plugging this back, the integrand is now asymptotically
$$ \left( \sqrt{\frac{a}{2}} - \sqrt{\frac{b}{2}} \right) \frac{1}{x^{1/4}} + \mathcal{O}\left(\frac{1}{x^{5/4}}\right), $$
and for the integral of this over $[b, \infty)$ to converge, the first term must vanish. (The error term $\mathcal{O}(x^{-5/4})$ does not pose any issue to the integrability, because we know that $\int_{b}^{\infty} x^{-5/4} \, \mathrm{d}x$ is finite.) Therefore the integral converges if and only if $a = b$.

2. If you are not used to analyzing the asymptotic behavior of a function, then so called "rationalization" technique will be helpful:
\begin{align*}
\sqrt{x+a} - \sqrt{x}
= (\sqrt{x+a} - \sqrt{x}) \cdot \frac{\sqrt{x+a} + \sqrt{x}}{\sqrt{x+a} + \sqrt{x}}
= \frac{a}{\sqrt{x+a} + \sqrt{x}},
\end{align*}
and similarly we have
$$ \sqrt{x}-\sqrt{x-b} = \frac{b}{\sqrt{x} + \sqrt{x-b}}. $$
Plugging this back,
\begin{align*}
&\sqrt{\sqrt{x+a} - \sqrt{x}} - \sqrt{\sqrt{x}-\sqrt{x-b}} \\
&= \frac{\sqrt{a}}{\sqrt{\sqrt{x+a} + \sqrt{x}}} - \frac{\sqrt{b}}{\sqrt{\sqrt{x} + \sqrt{x-b}}} \\
&= \frac{\sqrt{a \left(\sqrt{x} + \sqrt{x-b}\right)} - \sqrt{b\left(\sqrt{x+a} + \sqrt{x}\right)}}{\sqrt{\left(\sqrt{x+a} + \sqrt{x}\right)\left(\sqrt{x} + \sqrt{x-b}\right)}} \\
&= \frac{a\left(\sqrt{x} + \sqrt{x-b}\right) - b\left(\sqrt{x+a} + \sqrt{x}\right)}{\sqrt{\left(\sqrt{x+a} + \sqrt{x}\right)\left(\sqrt{x} + \sqrt{x-b}\right)}\left(\sqrt{a \left(\sqrt{x} + \sqrt{x-b}\right)} + \sqrt{b\left(\sqrt{x+a} + \sqrt{x}\right)}\right)}.
\end{align*}

If $a = b$, then the numerator becomes
$$ a \left(\sqrt{x+a} - \sqrt{x-a}\right) = \frac{2a^2}{\sqrt{x+a} + \sqrt{x-a}} \sim \frac{a^2}{\sqrt{x}} \quad \text{as} \quad x \to \infty. $$

If $a \neq b$, then the numerator is $\sim 2(a - b)\sqrt{x} $.

In any cases, the denominator is $\sim 2\sqrt{2}\left(\sqrt{a} + \sqrt{b} \right) x^{3/4} $.

Combining these two observations, we know that the integrand is of order $x^{-1/4}$ if $ a\neq b$ and of order $x^{-5/4}$ if $a = b$. So the integral converges if and only if $ a = b$.
Comment: Nice proof (as usual). If $b=a$, the integral is $$-\frac{4}{15} \left(\sqrt{26 \sqrt{2}-14}-2\right) a^{5/4}$$
Comment: All that is mechanized: the command of Mathematica `FullSimplify[
 Series[Sqrt[Sqrt[x + a] - Sqrt[x]] -
   Sqrt[-Sqrt[x - b] + Sqrt[x]], {x, Infinity, 2}],
 Assumptions -> x > 0 && {a, b} \[Element] Reals]` produces $$\frac{\sqrt[4]{\frac{1}{x}} \left(\sqrt{a}-\sqrt{b}\right)}{\sqrt{2}}-\frac{\left(\frac{1}{x}\right)^{5/4} \left(a^{3/2}+b^{3/2}\right)}{8 \sqrt{2}}+O\left(\left(\frac{1}{x}\right)^{9/4}\right) .$$


Remove duplicates in a CSV document using Notepad++

Question: I am using notepad++ and I am trying to remove duplicates...
apple, green, supplier
banana, yellow, supplier
grapes, geen, supplier
apple, red, supplier
apple, brown, supplier
grapefruit, yellow, supplier

I would like to keep just the first instance of apple so the end result would look like this
apple, green, supplier
banana, yellow, supplier
grapes, geen, supplier
grapefruit, yellow, supplier

Anyone have an example?
Answer: Lets say you have it in a text file line by line you'd go through following steps:

Ctrl+F
Choose the Mark tab.
Search mode: Regular expression
Find what: ^apple
Alt+M to check Bookmark line
Click on Mark All

Click to the first instance of apple to clear the first mark.
Select from the menu Search > Bookmark > Remove Bookmarked Lines.
Ready ...


Bounds on the following mixture model?

Question: I have two random variables $y,z$:

$y$ is the product of a normal distribution and an independent lognormal distribution $\rightarrow$ so a lognormal mixture, &
$z \propto {\rm{log}} \ |y|$

In view of the above, how can I simplify the following expression:
$$ \mathbb{E} [\Delta(z,y).y] $$
where $\Delta(z,y) = \frac{z-y}{y}$? And $|\Delta(z,y)| \leq \alpha$ where $\alpha \in \mathbb{R}$.
I would like to ideally get, for some constant $C(y)$ defined in terms of the covariance of $y$: $ \mathbb{E} [\Delta(z,y).y] \leq C(y) .\mathbb{E} [\Delta(z,y)]  \mathbb{E} [y] $
$\underline{Thought}$:
Is there a possibility to get the above upper-bound using results from the sub-gaussianity literature, e.g., http://arxiv.org/pdf/1011.3027v7.pdf?
Answer: $\Delta(z,y).y = \frac{z-y}{y}.y = z-y = K\log\vert y\vert - y$, for some $K$, then $\mathbb{E} [\Delta(z,y).y] = \mathbb{E} [K\log\vert y\vert - y]$.
If $K>0$, then you can use the upper bound $\log\vert y \vert \leq \vert y\vert -1$ to obtain the bound $\mathbb{E} [K\log\vert y\vert - y] \leq \mathbb{E} [K\vert y\vert -K - y]$, and expand it if you wish to do so.

Bounds on the following mixture model?


Permutations (disjoint cycles)

Question: I am doing my revision just keep getting confused with these permutations
$(123)(143)(154)(34)$ on how to write them as disjoint cycles
I know you start from right to left
at the rightmost brackets i.e. $1→1$ then $1→5$ $5→5$.
I used Maple and Wolfram and answer is $25143$,
please help to see what I am missing.
Comment: but they are nog disjoint
Comment: They are *not* disjoint: consider in which cycles,say,  $3$ appears.
Answer: You normally apply the permutations from left to right. So applying the cycle (123) to
1 2 3 4 5 $\ \ \ \ \ \ $we get
2 3 1 4 5 $\ \ \ \ \ \ $then (143) gives
2 1 4 3 5 $\ \ \ \ \ \ $then (154) gives
2 5 1 3 4 $\ \ \ \ \ \ $and finally (34) gives
2 5 1 4 3
So we could write the result in cycle form as (1253).
Comment: @pjs36
"I would actually say it's more common (at least in beginner group theory courses) for permutations to act on the left, so that στ means "do τ first,"...
I think you meant, it's more common for permutations to act on the right .
Comment: I would actually say it's more common (at least in beginner group theory courses) for permutations to act on the left, so that $\sigma \tau$ means "do $\tau$ first," probably the convention the OP is using and refers to.
Comment: @pjs36 Except that he appears to accept that the answer is 25143 and you do not get that if you use the other order.
Comment: Ah, I see. I interpreted their situation differently: I sensed confusion about why two different CAS were spitting out things that seemed to contradict their understanding (but they don't explicitly say what, if anything, *they* got instead).

Permutations (disjoint cycles)


"All that glitters is not Gold" Propositional Logic.

Question: Found this in Pugh's Real Mathematical Analysis.
The problem says to "Recast the following English sentences in Mathematics, using correct mathematical grammar. Preserve their meaning".
(c) All that glitters is not gold.
My thought ( could be way off) was to create functional notation notating that "element $x$ glitters" and "element $x$ is gold". That is $g(x)$ and $Au(x)$ respectively. Then I would say something like...
It is not tru that for each $x,$ $g(x)$ implies $Au(x)$,
which then translates to $$\sim (g(x) \Longrightarrow Au(x)) \equiv g(x) \wedge \sim Au(x).$$
Is this even close? Any hints or direction is appreciated.
Comment: Propositional logic does not suffices; you have to use quantifiers. You have to use : "if it Glitter, then it is not Gold", and universally quantify it.
Comment: How so?
$\forall x \exists y (g(y) \wedge \sim Au(y))$ maybe?
Comment: Also I think the point of the question is to quantify "all that glitters is not NECESSARILY gold", don't you ? Because gold definitely glitters.
Comment: @Luuuuuke That sounds better. But why $\forall x$?
Comment: Pfft idk. I guess I'm trying to say "there exists an element in the set of things that glitter that is not in the set of things that are gold". Maybe $\forall x$ is unnecessary.
Answer: Your proposed sentence is close, but isn't quite there yet. $\ g(x) \wedge \sim Au(x)\ $ says that the this particular $\ x\ $ glitters but isn't gold. This would be true for some values of $\ x\ $ (cellulose sequins, trout scales, etc.) and false for others (gold, matte paper, etc.). To make it synonymous with the target sentence you need to precede it with an existential quantifier:
$$
\exists x: \ g(x) \wedge \sim Au(x)\ ,
$$
which says that there exists an $\ x\ $ which glitters but isn't gold.  Equivalently, you could place a universal quantifier between the negation sign and the remainder of the first version of your two equivalent formulations:
$$
\sim\forall x:g(x)\implies Au(x)\ .
$$
This says it's not true that everything which glistens must be gold.
Answer: You are very close to translating this correctly. You need only add a quantifier to the statement.
Propositional logic alone will not suffice for translating this statement into anything more than a single proposition. For that, you will need first order logic.
If the formal translation of a statement is ever tricky, it generally helps to translate the statement recursively, making it slightly more formal each time while being careful to preserve meaning...
"All that glitters is not gold."
"Not everything that glitters is gold."
"It is not the case that, for any thing $x$, if $x$ glitters, then $x$ is gold."
Now the quantifier and predicates are more clear. If the domain of discourse, S, is the set of all things, then we have the following
$\neg \forall x [G(x) \rightarrow A(x)]$
where $x \in S$
$G(x):x$ giltters
$A(x):x$ is gold
And of course, this is logically equivalent to...
$\Leftrightarrow \exists x \neg [G(x) \rightarrow A(x)]$
$\Leftrightarrow \exists x \neg [ \neg G(x) \vee A(x)]$
$\Leftrightarrow \exists x [\neg \neg G(x) \wedge \neg A(x)]$
$\Leftrightarrow \exists x [G(x) \wedge \neg A(x)]$

“All that glitters is not Gold” Propositional Logic.


Installing Ubuntu as VM on XEN Server Free

Question: I have installed and setup Citrix XEN Server 6.0 Free on my home computer and i need to install Ubuntu 12.04 64 bit on it.
But i cannot install it.I tried using CD Drive and NFS stored iso but all fails with error
**

"Your Installation CD ROM couldnt be mounted.This probably means that
  CD ROM is not in the Drive"

**  \
It fails in step 3 ie

Detetct and Mount CD ROM

even after i tried 4-5 times
Do i need to install any support package for installing VMs on XEN OR should i need to upgrade xen to 6.02 for latest ubuntu support??
Used the same iso for installing many VM using XEN type 2 Hyperviosr on ubuntu
Comment: Question; is your iso correct (md5 sum it) and are you using the virtual disk
Comment: Also are you using Xen or Citrix XenServer?
Comment: yes created virtual disk,and used the same iso for installing VM before.
Comment: using Citrix XEN server 6.0
Answer: When booting you will need to press F6 and disable ACPI (needs to be NOACPI). This should be fixed in the latest version I think.
Comment: ohhh...no.... you solved it again :) :) Thankx alot


Get variables from query with JOIN

Question: I'm sure that my problem is very stupid, but I don't know how to get data from query after JOIN, when I have columns with this same name in several tables used in query, ex.:
$query="SELECT * FROM `clients` JOIN `devices` ON `clients`.`id`=`devices`.`client_id`";
$devices = $Database->select($query);
for($i=0; $i<sizeof($devices); $i++)
    {
        // I need to get 'name' from `devices` AND `clients` tables...
    }

Many thanks in advance.
Answer: You can use alias for table name and for columns
Example
SELECT c.name as clientName, d.name as deviceName
FROM clients c JOIN devices d ON clients.id=devices.client_id

Then in your loop you can get "clientName" and "deviceName"
Answer: First of all, it doesn't look like you need to select the whole table to begin with. So:
SELECT devices.name, clients.name
FROM clients JOIN devices ON clients.id=devices.client_id

Now you just need to access the data, one row at a time from $devices.
Comment: Yep it's true, but after widing the query i'll still have to get 'name' from both tables. Anyway thanks for comment :)

Get variables from query with JOIN


Halton sequence vs Sobol' sequence?

Question: From an answer in a previous question, I was directed toward the Halton sequence, for creating a set of vectors that covered a uniform sample space fairly evenly. But the wikipedia page mentions that higher primes especially are often highly correlated early in the series. This seems to be the case for any pair of high primes with a relatively short sample size - and even when the variables aren't correlated, the sample space isn't evenly sampled, rather there are diagonal bands of high sample density across the space.
Because I'm using vectors of length 6 or more, I will inevitably have to use some primes for which this is a problem (although not as bad as in the example aboved), and some pairs of variables will be non-uniformly sampled in their sample plane. Using the Sobol' sequence to generate a similar set seems to me (just from looking at graphs) to generate samples between pairs of variables that are much more evenly distributed, even for relatively small numbers of samples. This seems much more useful, and so I'm wondering when a Halton sequence would be more beneficial? Or is it just the Halton sequence is easier to compute?
Note: discussion of other multi-dimensional low-discrepancy sequences is also welcome.
Answer: Yes, Halton is easier to calculate, but it has the problems you mentioned. Halton can be improved by the leaped Halton method, but it will be not really better than Sobol. For high dimensions (like $d>10$) and moderate count (like $N$ around 500) all methods will run into problems, e.g. some 2D projections in Sobol will look strange, showing strong patterns, not diagonal but more like a chessboard! One way to improve is randomization and e.g. the so-called tent transformation.
Comment: Could you please expand on your last sentence?

Halton sequence vs Sobol' sequence?


Pega o maior valor dentro do select do linq

Question: Existe alguma forma que dentro do select do linq eu possa pegar o maior valor de um campo do tipo decimal?, conforme o código abaixo?
MaxValor = Math.Max(CF.Janeiro, CF.Fevereiro, CF.Marco, CF.Abril, CF.Maio, CF.Junho, CF.Julho, CF.Agosto, CF.Setembro, CF.Novembro, CF.Dezembro),

 CamposFormImport = CForm
 .Select(CF => new VwCamposFormulario
 {
     IdCampoModelo = CF.IdCampoModelo,
     Janeiro = (CF.Janeiro + (CF.Janeiro * Porcentagem)),
     Fevereiro = (CF.Fevereiro + (CF.Fevereiro * Porcentagem)),
     Marco = (CF.Marco + (CF.Marco * Porcentagem)),
     Abril = (CF.Abril + (CF.Abril * Porcentagem)),
     Maio = (CF.Maio + (CF.Maio * Porcentagem)),
     Junho = (CF.Junho + (CF.Junho * Porcentagem)),
     Julho = (CF.Julho + (CF.Julho * Porcentagem)),
     Agosto = (CF.Agosto + (CF.Agosto * Porcentagem)),
     Setembro = (CF.Setembro + (CF.Setembro * Porcentagem)),
     Outubro = (CF.Outubro + (CF.Outubro * Porcentagem)),
     Novembro = (CF.Novembro + (CF.Novembro * Porcentagem)),
     Dezembro = (CF.Dezembro + (CF.Dezembro * Porcentagem)),
     Media = CF.Total != 00M ? ((CF.Total / 12) + ((CF.Total / 12) * Porcentagem)) : 0,
     MaxValor = Math.Max(CF.Janeiro, CF.Fevereiro, CF.Marco, CF.Abril, CF.Maio, CF.Junho, CF.Julho, CF.Agosto, CF.Setembro, CF.Novembro, CF.Dezembro),
 })
 .ToList();

Pelo que pude ver o método Max só tem suporte para dois parâmetros, nesse caso também não posso usar o método GroupBy do linq.
Answer: Você pode usar várias chamadas do Math.Max para resolver isso:
MaxValor = Math.Max(CF.Janeiro, Math.Max(CF.Fevereiro, ..., Math.Max(CF.Novembro, CF.Dezembro)...))

Ou usar um método adicional que faça isso para você:
static decimal MaxExtended(params decimal[] args)
{
    return args.Aggregate(0m, (d1, d2) => Math.Max(d1, d2));
}

E usá-lo na expressão do Select:
MaxValor = MaxExtended(CF.Janeiro, CF.Fevereiro, ..., CF.Dezembro)

Comment: Gostei do método por ser mais limpo. vlw


How would one estimate the number of commercial airplanes bought in the US every year?

Question: I am not sure where to start with this question. Do you start by estimating number of major airports? How many airplanes decommissioned/and new ones bought?
Comment: Chasing links in http://en.wikipedia.org/wiki/Back-of-the-envelope_calculation will give some insight.
Answer: it rather depends on what information you have available! one simple approach might be to estimate the total size of the fleet, and the average number of years in service for a plane. when talking of number of planes the skewed distribution of plane size means that passenger numbers are not so helpful, though you could assume an approximately lognormal or gamma distribution, for example. to estimate the size of fleet in operation you could try various approaches. one would be based on the fact that there are readily-available airport statistics like "one plane takes off every 4 minutes". here the skewness works to your advantage, as you could get a good initial estimate by just looking at a small number of airports with the largest traffic flows. other relevant data come from the economic stats. get an estimate of how much Americans spend per year on air travel, then try and partition this into different categories of costs. for cars you will find that the amount spent on vehicle purchase is the same order of magnitude as the amount spent on fuel, so that could be a starting point, coupled with information on the distribution of new plane prices, though here the skewness factor would tend to work against you (unless quantitatively modeled using the distributions already suggested). a further line of approach might be based on examination of the employment statistics for flight crew personnel


FITS_rec and selection of data: masking instead of "true" filtering?

Question: Probably a duplicate to Ashley's post (but I can't comment -yet ;) ).
I have the same issue when trying to add a column to a sub-selection/sample of my initial FITS_rec (based on numpy's recarray); all the rows reappear (AND the filling of this new column doesn't seem to be respected...). "hdu_sliced._get_raw_data()" proposed by Vlas Sokolov is a solution that is working very fine for me, but I was wondering:
1) What are "the better ways" suggested by Iguananaut? I certainly need someone to just google it for me; the newbie me is feeling stuck :$ (Staying in a FITS_rec would be required).
2) Is that an expected behaviour? Meaning, are we really wanting to work on a "masked array" which would a copy of our original array? What is worrying me the most is the "collapse" of the values in the new computed column. See below:
# A nice FITS_rec
a1 = np.array(['NGC1001', 'NGC1002', 'NGC1003'])
a2 = np.array([11.1, 12.3, 15.2])
col1 = fits.Column(name='target', format='20A', array=a1)
col2 = fits.Column(name='V_mag', format='E', array=a2)

cols = fits.ColDefs([col1, col2])
hdu = fits.BinTableHDU.from_columns(cols)

ori_rec=hdu.data

ori_rec
`

FITS_rec([('NGC1001', 11.1), ('NGC1002', 12.3), ('NGC1003', 15.2)],
           dtype=(numpy.record, [('target', 'S20'), ('V_mag', '

# Sub-selection
bug=ori_rec[ori_rec["V_mag"]>12.]
bug

FITS_rec([('NGC1002', 12.3), ('NGC1003', 15.2)],
           dtype=(numpy.record, [('target', 'S20'), ('V_mag', '

So far so good...
# Let's add a new column
col0=bug.columns
col1 =fits.ColDefs([fits.Column(name='new',format='D',array=bug.field("V_mag")+1.)])
newbug = fits.BinTableHDU.from_columns(col0 + col1).data

FITS_rec([('NGC1001', 11.1, 13.30000019), ('NGC1002', 12.3, 16.20000076),
            ('NGC1003', 15.2,  0.        )],
           dtype=(numpy.record, [('target', 'S20'), ('V_mag', '

...AND ... the values of the new column for  NGC1002 and NGC1003 are correct but in the row of NGC1001 and NGC1002 respectively... :|
Any enlightenment will be welcomed :)
Comment: Thanks for the nice, detailed post.  I'll have an answer in a few...
Answer: This is a confusing problem, and it stems from the fact that there are many layers of legacy classes and data structures in astropy.io.fits (stemming back from earlier versions of PyFITS).  For example, you can see in your example that hdu.data is a FITS_rec object, which is like a Numpy recarray (itself a soft-deprecated legacy class), but it also has a .columns attribute (as you've noted):
>>> bug.columns
ColDefs(
    name = 'target'; format = '20A'
    name = 'V_mag'; format = 'E'
)

This in turn actually holds references back to the original arrays from which you described the columns.  For example:
>>> bug.columns['target'].array
chararray(['NGC1001', 'NGC1002', 'NGC1003'],
      dtype='|S20')

You can see here that even though bug is a "slice" of your original table, the arrays referenced through bug.columns are still contain the original, unsliced array data.  So when you do something like in your original post
>>> col0 = bug.columns
>>> col1 = fits.ColDefs([fits.Column(name='new',format='D',array=bug.field("V_mag")+1.)])

it's doing its best here to figure out the intent, but col0 here has no idea that bug is a slice of the original table anymore, it only has the original "coldefs" with the full columns to rely on here.
Most of these classes, including FITS_rec, Column, and especially ColDefs almost never need to be used directly anymore.  Unfortunately not all of the documentation has been updated to reflect this fact, and there are a lot of older tutorials and example code that show usage of these classes.  Nobody with the requisite expertise has been able to take the time to update the docs and clarify this point.
On occasion Column is useful if you already have columnar data with each column in a separate array, and you want to build a table from it and give some specific FITS attributes to the table columns.  But I have redesigned much of the API so that you can take native Python data structures like Numpy arrays and save them to FITS files without worrying about the details of how FITS is implemented or annoying things like FITS data format codes in many cases.
This work is slightly incomplete, because it seems if you want to define a FITS table from some columnar arrays, you still need to use the Column class and specify a FITS format at a minimum (but you never need to use ColDefs directly):
>>> hdu = fits.BinTableHDU.from_columns([fits.Column(name='target', format='20A', array=a1), fits.Column(name='V_mag', format='E', array=a2)])
>>> hdu.data
FITS_rec([('NGC1001', 11.1), ('NGC1002', 12.3), ('NGC1003', 15.2)],
      dtype=(numpy.record, [('target', 'S20'), ('V_mag', '<f4')]))

However, you can also work with Numpy structured arrays directly, and I usually find that simpler personally, as it allows you to ignore most FITS-isms and just focus on your data, for those cases where it's not important to finely tweak the FITS-specific stuff.  For example, to define a structured array for your data, there are several ways to go about that, but you might try:
>>> nrows = 3
>>> data = np.empty(nrows, dtype=[('target', 'S20'), ('V_mag', np.float32)])
>>> data['target'] = a1
>>> data['V_mag'] = a2
>>> data
array([('NGC1001', 11.100000381469727), ('NGC1002', 12.300000190734863),
       ('NGC1003', 15.199999809265137)],
      dtype=[('target', 'S20'), ('V_mag', '<f4')])

and then you can instantiate a BinTableHDU directly from this array:
>>> hdu = fits.BinTableHDU(data)
>>> hdu.data
FITS_rec([('NGC1001', 11.1), ('NGC1002', 12.3), ('NGC1003', 15.2)],
      dtype=(numpy.record, [('target', 'S20'), ('V_mag', '<f4')]))
>>> hdu.header
XTENSION= 'BINTABLE'           / binary table extension
BITPIX  =                    8 / array data type
NAXIS   =                    2 / number of array dimensions
NAXIS1  =                   24 / length of dimension 1
NAXIS2  =                    3 / length of dimension 2
PCOUNT  =                    0 / number of group parameters
GCOUNT  =                    1 / number of groups
TFIELDS =                    2 / number of table fields
TTYPE1  = 'target  '
TFORM1  = '20A     '
TTYPE2  = 'V_mag   '
TFORM2  = 'E       '

Likewise when it comes to things like masking and slicing and adding new columns, working directly with the native Numpy data structures is best.
Or, as suggested in the answers to other question, use the Astropy Table API and don't mess with low-level FITS stuff at all if you can help it.  Because as I discussed, it contains several layers of legacy interfaces that make things confusing (and that long term should probably be cleaned up, but it's hard to do because code that uses them in some way or another are pervasive).  The Table API was designed from the ground-up to make table manupulations, including things like masking rows and adding columns, relatively easy.  Whereas the old PyFITS APIs never quite worked for many simple cases.
I hope this answer was edifying--I know it's maybe a bit long and confusing.  If there is anything specific I can clear up let me know.


Drupal set message class

Question: I've been trying to add a class to a drupal_set_message() function. i found one article that said it worked, but i could not get it to work on mine. am i missing something?
I have drupal_set_message(t('an error has occured'),'custom-error');
these are the only output i get from the html

×
an error has occured

any help would be appreciated.
Comment: Can you add the article plz? It seems fine.
Comment: you are missing the $type parameter  status , warning or error. the second parameter is message type separated by space your class name
Comment: refer this link https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_set_message/7#comment-23023
Answer: For drupal set message below is a syntax.
drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE);

Parameters
string $message: (optional) The translated message to be displayed to the user. For consistency with other messages, it should begin with a capital letter and end with a period.
string $type: (optional) The message's type. Defaults to 'status'. These values are supported:
'status'
'warning'
'error'
You should pass any one of the status message with your custom class separated with space as shown below
drupal_set_message(t('an error has occured'),' status custom-error');

Comment: Thank you for the answers. I'm gonna go and try if this will work. I'll get back to you shortly
Comment: hello. I did it as follows

drupal_set_message(t('an error has occured'),' status custom-alert');

but it is still not rendering the class. should i create a custom theme_status_message() instead?
Answer: To solve this issue, i created a theme_status_message on my template.php, inside  it contains the default theme_status_message with some minor changes. Cleared the cache and the classes are adding. It's weird how it's not working when I didn't create one even though it was in the theme.inc file.
Also, it seems like the default has become 'status' instead of 'success' before the changes. Anyone know how to chnage the default without changing the bootstrap.inc file?

Drupal set message class


Calcular o número de elementos com CSS

Question: Estou fazendo uma lista numerada com contadores regressivos usando o counter-reset. Atualmente coloco o número de items da lista manualmente:
.faq { counter-reset:my-counter 2; }
.faq dt { counter-increment: my-counter -1; }
.faq dt:before { content: counter(my-counter, decimal-leading-zero) "."; }

Com o HTML:

Item 1

Item 2

Imprime:

01. Item 1
00. Item 2

Mas, se acrescentar um
 e não ajustar o counter-reset, vai imprimir:

01. Item 1
00. Item 2
-01. Item 3

JSFiddle.
Li Can CSS detect the number of children an element has? e tentei counter-reset:my-counter ~ dt, mas na realidade não entendi muito bem o uso do ~.
Sei que posso fazer com jQuery
var reset = 'my-counter '+ $('.faq dt').length;
$('.faq').css( 'counter-reset', reset );

É possível com CSS puro?
Referência: Numbering In Style | CSS-Tricks
Comment: Essa resposta que do SOEn funciona vendo se o enésimo elemento `li` existe e aplicando a regra tanto a ele quanto aos [_siblings_](http://css-tricks.com/child-and-sibling-selectors/) dele. Infelizmente acho que não tem jeito de obter um número só usando css, você vai ter que usar magic number mesmo (talvez usando pre-processadores de css role, mas ai já não sei dizer)
Comment: Verificando a documentação na MDN notei que o CSS Counter tem três propriedades, sendo estas:

- counter
- counter-increment
- counter-reset

Pelo visto o counter reset realiza o reset para 0, neste caso o que pode ser feito é exibir usando CSS a lista na ordem inversa.
Comment: Corrigindo, resetando para o inteiro desejado.
Neste caso usando CSS pode-se exibir a lista na ordem inversa a que ela está no DOM, alcançando assim o efeito desejado.
Comment: Uai, ooredroxoo, se puder confirmar sua teoria e publicar uma resposta, fantástico.
Comment: Pesquisei um pouco e acho que não dá mesmo. Eu suspeito que o CSS não tenha como saber isso, ele incrementa o contador quando encontra cada elemento, então só sabe o total depois de passar por todos.
Comment: Pior que numa `` seria extremamente simples (exceto pelo IE talvez): http://www.impressivewebs.com/reverse-ordered-lists-html5/
Comment: Acho que o que o ooredroxoo quis dizer foi algo similar a [isso aqui](http://codegolf.stackexchange.com/a/20879/21700): Usar o css para inverter a lista na raça
Answer: Há uma forma de fazer, usando transformações CSS (transform), como descobri no StackOverflow (inglês), com alguns contras:

não é compatível com todos os browsers: Can I use CSS Transforms

tive qua adicionar algum markup ao seu original, então acho que quebrei um pouco a semântica... uns divs, em torno de cada grupo dt+dd.
a seleção de texto, fica com problemas, pois o browser acha que o que está em baixo, vem antes no fluso de seleção

A solução

.faq {
  -webkit-transform: scaleY(-1);
  transform: scaleY(-1);
}
.faq > * {
  -webkit-transform: scaleY(-1);
  transform: scaleY(-1);
}
.faq {
  counter-reset: my-counter 0;
}
.faq dd {
  margin: 0 0 50px;
}
.faq dt:before {
  content: counter(my-counter, decimal-leading-zero)".";
  font: bold 50px/1 Sans-Serif;
  left: 0;
  position: absolute;
  top: 5px;
}
.faq dt,
.faq dd {
  padding-left: 90px;
}
.faq dt {
  counter-increment: my-counter 1;
  font: bold 16px Georgia;
  padding: 4px 0 10px 90px;
  position: relative;
}
body {
  padding: 20px;
  background-color: #eee;
}

Como colocar o umbigo pra dentro?

Aperte o umbago com o dedão. Fonte: Wikipedia.

Onde eu baixo um processador dual core?

AMD ou IBM?

Carne vermelha faz mal, carne branca faz mal, o que devo comer?

Carne humana.

Quando devo falar sobre sexo com meu cachorro?

Quando ele entrar na puberdade.

Como funciona?
O princípio consta em inverter o sistema de coordenadas verticais, usando transformações CSS:
transform: scaleY(-1)

Isso vai inverter o eixo Y, que é tradicionalmente o eixo vertical.
Então passo a passo, isso é o que ocorre:

Se aplicarmos essa transformação apenas uma vez, então, o que acontece é que tudo dentro do elemento com o estilo aplicado fica de cabeça para baixo. No caso, primeiro aplicamos a transformação ao elemento que engloba toda a lista:

Acontece que agora, cada um dos sub-elementos está de cabaça para baixo. Então o que temos que fazer, é inverter cada um deles individualmente, o que na prática os desinverterá:
Comment: O truque é então inverter o Y de cada `div`? O que exatamente o `scaleY(-1)` está fazendo? Porque a escala inverte a posição? . . . . Follow up no [philosophy.se]: *"Is there any limit to human creativity?"* :)
Comment: Hahaha, belo truque, agora eu entendi. @brasofilo É uma lista crescente, mas flipada duplamente (primeiro o container, depois cada item), dando o efeito de regressiva.
Comment: @bfavaretto, yes, lá no SO tem a explicação do código: `mirror in the vertical axis both the container and the childs. The childs follow the inverted y axis of the container, but the children themselves are again head up`. Acho curioso que seja `scale` que faz o truque.
Comment: Pra quem quiser um [jsfiddle](http://jsfiddle.net/masbicudo/osct3Lwc/).
Comment: Essas perguntas são tão *wtf* quanto a solução. +1
Comment: Adicionei uma explicação com algumas imagens pra facilitar a visualização. As imagens tão meio toscas... to num computador que só tem Paint... mas já dá pra ter uma noção visual.

Calcular o número de elementos com CSS


Terence Tao's definition of identity of functions

Question: I'd like to prove, following Terence Tao's Analysis I book, that the relation $R$ in the class of functions from $X$ to $Y$ given by $$f\mathrel{R}g \iff \textrm{ for every } x\in X, f(x)=g(x)$$ satisfies what Tao calls the "Axiom of Substitution", that is, if $f,g:X\to Y$ are functions and $f\mathrel{R} g$, then $h(f)=h(g)$, for every admissible function $h$.
I don't know, however, how to proceed, so I was wondering if someone could help me prove that. How does one prove that $h(f)=h(g)$ just knowing that $f(x)=g(x)$, for all $x\in X$?
Comment: What is an "admissible function"?
Comment: Well, you know that $=$ satisfies the axiom of substitution by definition.
Comment: @TianVlašić You are referring to the equality symbol between $f(x)$ and $g(x)$?
Comment: @GleisonStanlley Yes
Comment: @TrevorGunn Any function where talking about what we want to talk about makes sense. In this case, any function $h$ that have $f$ and $g$ in its domain.
Comment: @TianVlašić And how that proves what we want?
Answer: I suppose you are trying to solve exercise 3.3.1 in Tao's book. The exercise requires to prove that composition of functions obeys the axiom of substitution; i.e., that if $f,\tilde{f}: X \to Y$ and $g,\tilde{g}: Y \to Z$ are functions such that $f = \tilde{f}$ and $g = \tilde{g}$, then $g \circ f = \tilde{g} \circ \tilde {f}$.
This could be proven as follows:
Let $x \in X$. Then, by reflexivity of equality $x = x$. By the axiom of substitution of equality $f(x) = f(x)$. Since $f = \tilde{f} \iff \forall x(f(x) = \tilde{f}(x))$ we can write $f(x) = \tilde{f}(x)$. By the axiom of substitution of equality $g(f(x)) = g(\tilde{f}(x))$. Since $g = g'$ we have $g(f(x)) = \tilde{g}(\tilde{f}(x))$.
Comment: @GleisonStanlley Ok, why do you think that the same reasoning does not apply to the exact proposition you are trying to prove? If $f R g$; i.e., $(\forall x \in X)(f(x) = g(x))$ and $h$ is admissible; i.e., $h: Y \to Z$, then $h(f(x)) = h(g(x))$ by the axiom of substitution again.
Comment: Not really. What I want to prove is what I wrote in the text: if $f,g:X\to Y$ are functions and $f \mathrel{R} g$, then $h(f)=h(g)$, for every admissible function $h$.
Comment: But we want to prove that $h(f)=h(g)$, not that $h(f(x))=h(g(x))$ (which may not make sense if $f(x)$ and $g(x)$ aren't in $h$ domains).
Comment: @GleisonStanlley I'm not sure I understand what you are trying to prove then. Usually Tao proves reflexivity, symmetry and transitivity in general and then he proves substitution once he has defined some operation on the objects under interest. In this case the relation under interest is equality between functions. Thus, functions of such an equality is simply the composition of functions. He also explicitly states to prove this both in the text and in the exercises.  What does $h(f)$ as opposed to $h(f(x))$ mean in your opinion?


Inflar Layout em uma Service

Question: No casso esse código faz uma janela flutuante com um botão para encerrar a atividade, então como faço agora para inflar nela um layout, ou outra forma de construir um layout dentro da service.
public class FloatingWindow extends Service {

    WindowManager wm;
    LinearLayout ll;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();

        wm = (WindowManager) getSystemService(WINDOW_SERVICE);

        ll = new LinearLayout(this);
        ll.setBackgroundColor(Color.RED);
        LinearLayout.LayoutParams layoutParameteres = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, 400);
        ll.setBackgroundColor(Color.argb(235,164,164,164));
        ll.setLayoutParams(layoutParameteres);

        final WindowManager.LayoutParams parameters = new WindowManager.LayoutParams(
                700, 600, WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        parameters.gravity = Gravity.CENTER | Gravity.CENTER;
        parameters.x = 0;
        parameters.y = 0;

      Button     stop = new Button(this);
    stop.setText("Stop");
        ViewGroup.LayoutParams btnParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        stop.setLayoutParams(btnParameters);

        ll.addView(stop);
        wm.addView(ll, parameters);

        ll.setOnTouchListener(new View.OnTouchListener() {
            WindowManager.LayoutParams updatedParameters = parameters;
            double x;
            double y;
            double pressedX;
            double pressedY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        x = updatedParameters.x;
                        y = updatedParameters.y;

                        pressedX = event.getRawX();
                        pressedY = event.getRawY();

                        break;

                    case MotionEvent.ACTION_MOVE:
                        updatedParameters.x = (int) (x + (event.getRawX() - pressedX));
                        updatedParameters.y = (int) (y + (event.getRawY() - pressedY));

                        wm.updateViewLayout(ll, updatedParameters);

                    default:
                        break;
                }

                return false;
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wm.removeView(ll);
                stopSelf();
                System.exit(0);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopSelf();
    }

Comment: Tente explicar melhor o que pretende. Uma das principais características de um serviço é não ter *layout* (interacção com o usuário)
Comment: Então oque eu quero é uma janela flutuante, ok, com esse código já tenho, mais como é uma service não tem layout, e eu não consigo e nem sei como faço para obter esse resultado.
Answer: Amigo você pode fazer desse jeito para construir uma view no seu service.
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mLogoHead = inflater.inflate(R.layout.recording_view, null);
    WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);

    layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
    layoutParams.x = 100;
    layoutParams.y = 100;
    mWindowManager.addView(mLogoHead, mLayoutParams = layoutParams);
    mLogoHead.setOnTouchListener(this);
    mLogoHead.setVisibility(View.GONE);

Comment: o (mLogoHead) é oque?
Comment: é a view que eu coloquei para construir pode se chamar como você quiser.

Inflar Layout em uma Service


How do sound waves travel and their reflections?

Question: I'm studying reverb from a first principles standpoint and I'm finding it difficult to find this answer in my studies.
Firstly is this statement correct?
"The quantity of sound waves ejected into a space is dictated by each individual sound source in a space and what pitches and how many pitches (e.g. chords) they are playing."
In other words, if i pluck an A string on a guitar with the A being 440hz, that means that single pluck has ejected 440 sound waves into the space which are now reflecting off surfaces?
Secondly, how do these waves travel in terms of direction? Is there any consistency to their path of travel or are they uncontrollable in their direction?
Thirdly, once a sound wave bounces off a wall, how does it travel in terms of direction?
Many thanks folks! This is regarding natural reverb.
Comment: I'm voting to *not close this question* as it has a lot to do with music practice - not only for the musicians but also for all the "victims" of musical practice! (because  music is often - as Wilhelm Busch says - connected with noise.
Comment: Ofcourse, music is sound, and acoustics is very important to making music. But I think your question is just about the physics of sound in general. I think your question would be more on topic if you could describe *why* you need to know what you want to know. What do you want to do? How do you imagine to use the information this answers will give in your music-making? As it is now it's like asking about the nature and the physics of photons on a site on the visual arts. But maybe I'm alone with this opinion?
Comment: I'm voting to close this question as off-topic because I think it will be better answered on the physics.SE, and hasn't a practical connection with a problem in music making.
Comment: @Tim I find your position to be rather nonsensical. We are talking about reverberation.. you know, the ones used for classical music live performances in specially designed music venues? Music is physics ultimately so I guess none of it belongs here? And the practical connection is understanding reverb and how it works so I can manage it in my mix. What more of a connection to music making would one need.
Comment: To conclude: I honestly believe you will get much better answers on this specific question on the physics.SE.
Comment: I do think Physics will probably be able to answer this better, but I don't think this is necessarily off-topic here.
Comment: I need to know the answers to these questions to conclude how reverb functions so when I open the reverb plugin, I understand what are the parameters for and what it is I'm trying to achieve through reverb. I think that justifies the questions being asked within this community but given that this also revolves around virtual plugins, it may be more appropriate to ask this on the cyber technology forum.. joke!
Answer: I refer you to Wikipedia.
The motion of sound can be hard to understand because we can't see its propagation.  We can sometimes understand it more easily by analogy to waves we can see, for example waves on the surface of water, or light waves from a light bulb.  Although they are different kinds of waves (sound waves are longitudinal whereas water and light waves are transverse), their behaviour is more similar than different.  Here's a quick demo to understand the difference between longitudinal and transverse waves.

If i pluck an A string on a guitar with the A being 440hz, that means that single pluck has ejected 440 sound waves into the space which are now reflecting off surfaces?

Essentially, yes, but the guitar string is not simply vibrating at 440Hz.  It's also vibrating at 880, 1320, etc -- harmonics.  All of these frequencies are going out into the room.  They don't travel in isolation.  They're all interfering with each other to create a single complicated waveform.  Yes, the sound will reflect off of surfaces in your room.

How do these waves travel in terms of direction? Is there any consistency to their path of travel or are they uncontrollable in their direction?

Under idealized conditions, sound travels outwards in all directions equally.  The wavefront is an expanding sphere created by each 'quanta' of sound traveling in a straight line away from the source.1  By analogy, think of how light travels outwards from a lightbulb.  As the the sphere grows, the sound's kinetic energy is being spread thinner and thinner, which is why sound intensity dissipates over distance in accordance with the inverse-square law.
In the case of both sound and light, obstacles encountered by the wave will impede or alter its course.  Waves can reflect, refract, and diffract, which is to say they can bounce off of and/or bend around obstacles.  Assuming the sound is made up of many frequencies, like a musical tone, the different frequencies may respond to these obstacles differently.

Once a sound wave bounces off a wall, how does it travel in terms of direction?

The sound will reflect off of the surface such that the reflected angle is equal to the incident angle -- eg: if sound traveling northeast strikes a wall running east-west, the reflected sound will be traveling southeast.  To continue the light analogy, if your sound source is a light bulb, then each hard surface in your room is a mirror.  Soft surfaces can absorb sound, ie not reflect it.  Higher frequencies are absorbed more easily.  On the other hand, very low frequencies can actually travel right through walls almost as if they weren't there.  Low frequencies are very difficult to control.
There is a phenomenon called standing waves.  This is when the size of a chamber (such as a room) is the same as the wavelength of a sound (or a multiple of it), resulting in the wave just hanging out there seemingly unchanged overtime.  Because its wavelength matches the size of the space, it appears stationary, hence the name.  For a visual aid, you can setup standing waves in a sink of water.
1 In actuality, each collision between air molecules is like a new tiny sound source creating a new tiny expanding sphere.  But if you average out all the billions of these tiny spheres, you get the one big sphere I'm describing.
Comment: Music must be hard to understand as well, because we can't see it?
Comment: @Seery I think the reason you don't usually put reverb on bass is because it can quickly get muddy, especially if there are other low frequency instruments competing for space in the mix.  You totally can add reverb to kicks and bass, but you'll probably want to high-pass the reverb so that it doesn't contain (much) low frequency information.  You can get the desired sense of space just from mids.  It is not uncommon to put reverb on kick drums, and drum buses often add reverb too.  I don't think any of this has much to do with bass frequencies being able to pass through walls.
Comment: Great answer.  But don't many surfaces give diffuse/scattered reflections, i.e. at many angles not the same as the incident angle?  In any case, I think there should be a TLDR: It's complicated :-)
Comment: @gidds Yes an uneven surface will scatter sound. An uneven surface is just lots of little surfaces, each of which will reflect the sound such that the angle of incidence and reflection are still the same. A TLDR would be a good idea. I'll edit.
Comment: @ibonyun another great answer! " Higher frequencies are absorbed more easily. On the other hand, very low frequencies can actually travel right through walls almost as if they weren't there. Low frequencies are very difficult to control." does this indicate why it isn't favorable to add reverb to bass and kicks? Thank you for your response.
Comment: @piiperi Sound is to music as paint is to art - you can appreciate the result without knowing the science or method behind it.  Do you appreciate Van Gogh's "Sunflowers" more for knowing the techniques of grinding and mixing lead chromate and lead sulphate with linseed oil to make yellow paint?  And for that matter, how sound works is just as applicable in other contexts, in the same way that whitewashing your house walls is also painting but is not art.
Comment: For blind people, _everything_ must be hard to understand, because they can't see at all?
Comment: @piiperi You're a riot. You know that I meant *the motion* of sound is hard to understand because we can't see its propagation. [in fact, edit made!]  Humans are very visual creatures. Sight is front and centre in our conscious experience. We are more intuitively aware of how light moves, including reflection and refraction. Sound, OTOH, is more subliminal.  Most of the time, most people are oblivious to the acoustical properties of their environment.
Answer: 1) The quantity of sound waves produced in air depends on the intensity or amplitude. If you pull your guitar string back a very short distance from its normal resting position, then the oscillations in air particles will be small, and they won't bang against your ear drum as hard. This produces a quieter-sounding noise.
The frequency 440 Hz is how many complete wave cycles you produce per second. So every second, your string is vibrating back and forth 440 times. After the initial pluck, though, the intensity & amplitude start to die off, and eventually, causing the produced waves to become smaller and smaller with time until the string ceases to produce any more waves.
2) Sound waves are spherical, which means they travel outwards in all dimensions. Sound is nothing more than compressions in the air molecules/density, followed by rarefactions/expansions in the air. When your guitar string pushes against the surrounding air, this generates a 3D sphere of compression that travels out in all directions, essentially expanding evenly in all directions as it spreads through the room.
3) Once a wave bounces off a wall, each individual ray follows the law of reflect (angle of incidence = angle of reflection).

Reflected wavefronts can be easily mapped using ray tracing, i.e., the reflected ray leaves at an angle to the surface equal to the angle of incidence ("law of reflection").
https://ccrma.stanford.edu/~jos/pasp/Reflection_Spherical_Plane_Waves.html

Here's an example of what this looks like.
Comment: Check out https://reuk.github.io/wayverb/ which is a software reverb simulator that uses ray tracing.
Comment: @Seery, sounds like you've got the right idea! Also, check out [this answer](https://music.stackexchange.com/questions/58372/is-fundamental-frequency-the-same-thing-as-fundamental-bass-chord-root/58397#58397) where I talk some about the physical origins of sound. Regarding spherical waves and linear motion: if a sound is produced in the middle of the room, then the rays will travel out in all directions. Each ray travels in a straight line until it reaches a boundary, and then it reflects. But the rays are sent out in all directions.
Comment: Great answer! So to summarize, a spherical wave will eject firstly in a linear motion from a sound source and the size of that wave will depend on the level of amplitude from the sound source. If a string vibrates 440 times per second along with its additional harmonics, there are 440+ sound waves being ejected into the room per second. Correct?
Answer:
In other words, if i pluck an A string on a guitar with the A being 440hz, that means that single pluck has ejected 440 sound waves into the space which are now reflecting off surfaces?

No. The string will start generating sound waves at a rate of 440/second. How many waves it will generate, depends on how long you allow the string to vibrate. If you don't dampen the string, it will vibrate for a few seconds, generating waves that get weaker and weaker until they disappear under the threshold of our hearing.
If you allow the string to vibrate for exactly 1 second, you will generate 440 waves.
Actually it's a bit more complicated than that. A guitar also generates harmonics: frequencies that are a multiple of the 440 Hz ground tone.


Limiting of Power Sets

Question: This is, I believe, a relatively simple set-theoretical question.  I am ,however, not sure of the answer.  If we take a set, say $A$, and if we call the power set of $A$, $P_{1}(A)$, and we define $$P_{n}(A)=P_{1}(P_{n-1}(A)),$$ and then if we take the limit $$\lim_{n\to\infty} P_{n}(A),$$ is this set actually a set in NBG or does it lead to some sort of contradiction?
Answer: This is a confusing notation, note that you are indexing by ordinals and not by real numbers, and the notation $\infty$ makes so that you think about it as if you are using the real numbers, and the $\infty$ is that formal symbol of "the point beyond the edge of the universe".
In ZF we have the axiom schema of replacement which tells us that definable functions whose domain is a set have a set for an image. In particular the function $n\mapsto\mathcal P^n(A)$. Therefore $\{\mathcal P^n(A)\mid n\in\mathbb N\}$ is a set.
Furthermore the axiom of union tells us that if there is a set, then its union exists, namely if $X$ is a set then $\bigcup X=\{y\mid\exists u\in X: y\in u\}$ is a set.
The limit, if so, can reasonable taken to be $\bigcup\{\mathcal P^n(A)\mid n\in\mathbb N\}$. However we don't necessarily have $X\subseteq\mathcal P^n(X)$, and in particular this is true for power sets. If $A$ is transitive, namely $B\in A\rightarrow B\subseteq A$, then this works out just fine.
You may also want to consider the product, $\prod_{n\in\mathbb N}\mathcal P^n(A)$. This is a non-empty product, in ZF, and again it is a set by similar considerations as with the union. One reason to consider is that if we want to think about this as a directed system with $x\mapsto\{x\}$ as the map from $\mathcal P^n(A)\to\mathcal P^{n+1}(A)$ then the limit must embed $x$ into $\{\ldots x\ldots\}$, that is an infinite number of braces, which is impossible in ZF. But replacing $\mathcal P^n(A)$ by the finite product of $\mathcal P^k(A)$ for $k\leq n$ (cardinality wise this is the same) this is easily corrected.
Where the limit corresponds to the direct limit, this is the inverse limit. And do note that they are very different, for one in their cardinality. The product is larger.
Comment: A quick summary: "Limit" in the question isn't defined, but any reasonable substitute for it leads to a perfectly good set.
Comment: I'm feeling dirty after talking about direct and inverse limits... :-) But then again, with my recent invasion into the lands of iterated forcing, it seems reasonable to do so! :-)
Answer: Yes, that is a fine set in either NBG or ZF. Though it would be a bit more unambiguous to write $\bigcup_{n\in\omega}P_n(A)$ instead of the limit.
If $A=\varnothing$ then the result is the set of hereditarily finite sets.
Comment: "a bit more unambiguous" ==> A bit less ambiguous? :-)
Comment: @amWhy: Your phrasing is a bit more unambiguous than Henning's! :-P
Comment: @Asaf: You always see a way to find the humor in things!

Limiting of Power Sets


jQuery trigger event and send backspace key to input, but input text could not be deleted at all

Question: I have below codes to delete input text.
<code>$(document).on('click', "button[id='del_btn']", function(event) {
  $("input[id='lvl4_text1']").select()
  $("input[id='lvl4_text1']").focus()
  //trigger backspace keycode 8, keydown and keyup envent to input
  var e = $.Event('keydown', {
    keyCode: 8,
    which: 8
  })
  $("input[id='lvl4_text1']").trigger(e)

  e = $.Event('keyup', {
    keyCode: 8,
    which: 8
  })
  $("input[id='lvl4_text1']").trigger(e)
});

//I can see keyup and keydown event was triggered successfully.
$(document).on('keyup', "input[id='lvl4_text1']", function(event) {
  console.log("level 4 text keyup" + event.which)
});

$(document).on('keydown', "input[id='lvl4_text1']", function(event) {
  console.log("level 4 text down" + event.which)
});
</code>
it is quite straightforward and simple, but the text in input was not deleted.
I am using chrome55 and jquery1.8.
I do not want a workaround to delete input text, just would like to know why backspace keyboard evnet was triggerd already, but input text was not deleted.
and I tried trigger delete key(keycode 46) event also, nothing changed as same. I also trigger 'a'(keycode 65) to input, but input text can not be replaced.
I am newbie to js/jquery, can any one help?
Answer: I recommend splitting the input into an array, removing the last part of the array
<code>myarray.pop()
</code>
Then joining it back into a regular sentence, to then focus on the input.
Also, .trigger() triggers it for jQuery, but does not create the actual event as though the delete button is being pressed on your keyboard.