Outlier in differentiated series

Question: I'm studying methods for time series analysis, using gretl. I have this time series.
I used TRAMO and X12-ARIMA to detect probable outlier, but I found nothing. So I used difference-log of first order to make the serie stationary, and I had this:

It seems that there is something in the end of 2008. Infact TRAMO found a temporary change on November 2008
<code> 106 TC    (11 2008)
</code>
First question: Is it possible that the series before being differentiated had no outlier and after yes?
I continued the analysis, linearizing the serie, obtaining

So I can begin to study the ACF and PACF

TRAMO suggested me to use ARIMA(1,0,0)(0,1,1), but I found that a simple AR(1) give the same result. These are the ACF-PACF of ARIMA(1,0,0)(0,1,1) residuals:

and these of AR(1) residuals

Comparing AIC and BIC, theory suggests to choose the AR(1). This is the output for the ARIMA
<code>    Modello 3: ARIMA, usando le osservazioni 2001:03-2017:09 (T = 199)
    Stimato usando il metodo BHHH (MV condizionale)
    Variabile dipendente: (1-Ls) ld_Finla_xl

                 coefficiente   errore std.      z        p-value
      ------------------------------------------------------------
      const       7,67509e-05   0,000137004     0,5602   0,5753
      phi_1       0,307572      0,0671470       4,581    4,64e-06  ***
      Theta_1    −0,765016      0,0511360     −14,96     1,33e-050 ***

    Media var. dipendente  0,000170   SQM var. dipendente    0,008292
    Media innovazioni      0,000046   SQM innovazioni        0,006505
    Log-verosimiglianza    719,6341   Criterio di Akaike    −1431,268
    Criterio di Schwarz   −1418,095   Hannan-Quinn          −1425,937
    Note: SQM = scarto quadratico medio; E.S. = errore standard

                          Reale   Immaginario   Modulo  Frequenza
      -----------------------------------------------------------
      AR
      Radice  1           3,2513     0,0000     3,2513     0,0000
      MA (stagionale)
      Radice  1           1,3072     0,0000     1,3072     0,0000
      -----------------------------------------------------------
</code>
this for the AR model
<code>    Modello 1: ARMA, usando le osservazioni 2000:03-2017:09 (T = 211)
    Stimato usando i minimi quadrati (MV condizionale)
    Variabile dipendente: ld_Finla_xl

                 coefficiente   errore std.     z     p-value
      --------------------------------------------------------
      const      0,000623196    0,000402829   1,547   0,1219
      phi_1      0,312608       0,0644261     4,852   1,22e-06 ***

    Media var. dipendente  0,000935   SQM var. dipendente    0,006078
    Media innovazioni      0,000000   SQM innovazioni        0,005776
    Log-verosimiglianza    789,1005   Criterio di Akaike    −1574,201
    Criterio di Schwarz   −1567,497   Hannan-Quinn          −1571,491
    Note: SQM = scarto quadratico medio; E.S. = errore standard

                          Reale   Immaginario   Modulo  Frequenza
      -----------------------------------------------------------
      AR
      Radice  1           3,1989     0,0000     3,1989     0,0000
      -----------------------------------------------------------
</code>
Second question: TRAMO suggests to use seasonale difference, but from the ACF/PACF it seems that it's not necessary. I know that seasonal difference is requested when there is no stationary caused by the seasonal component. Is it true?
Answer:
There are three kinds of additive outliers viz, Pulses, Level Shifts and Seasonal Pulses. Tramo Seats does not treat Seasonal Pulses correctly or perhaps not all due to ineffective implementation as it is non-trivial to implement. A Seasonal Pulse is an old-fashioned (but very useful) seasonal dummy which doesn't necessarily start at the beginning of the data. For example if we have 213 historical values but starting at 2004/12 (period 60) there is a consistently higher observation by .306 reflecting Christmas. This would lead to a dummy indicator of the form 59 0's followed by a 1 at the next period and each successive December. Additionally there is detected seasonal dummy required for February starting at period 86 reflecting a trading-day effect as February has fewer business days. The identified equation is here . IMO the fact that only two months have a hint of seasonality in no way suggests seasonal differencing.
The model statistics are here using AUTOBOX a piece of siftware that I have helped develop   and here
The plot of the residuals is here  with companion acf
The cleansed vs actual plot is revealing  and the actual/fit/forecast here  with possible anomalies in the future.
DIRECT ANSWERS:
1) Is it possible that the series before being differentiated had no outlier and after yes?  Yes as the outlier may be hidden due to predictive structure that has yet to be identified much like being unable to "see" if your eyeglasses(filter/model) have a crack in them.
2) TRAMO suggests to use seasonale difference, but from the ACF/PACF it seems that it's not necessary.  No there is no need for seasonal differencing just better analytics from Tramo-Seats identifying the need for Seasonal Pulses and their starting point. Unwarranted seasonal differencing INJECTS structure into the residuals (Slutsky effect ? e.g differencing a white noise series creates a new series with greater variance) rather than eliminating structure .
For an extended discussion of the flaws in TS see
https://www.researchgate.net/publication/264993978_About_model-based_time_series_procedures_some_remarks_to_TRAMOSEATS_and_CENSUS_X-12-ARIMA
and less so here
https://books.google.com/books?id=HMcJoXf4EJ0C&pg=PA196&lpg=PA196&dq=stier+tramo+seats&source=bl&ots=mHnKXg2CKo&sig=SDJ8S9xYJ9ned4bnEm5Wz7FN67E&hl=en&sa=X&ved=0ahUKEwjw0pLX2NnXAhVDkeAKHcMRDGEQ6AEIQTAE#v=onepage&q=stier%20tramo%20seats&f=false
Finally the presence of a significant acf(11) might be suggestive that the current model is inadequate. There a few possible reasons for this 1) the need to add seasonal arima OR 2) the need to add seasonal dummies OR  3) an unwarranted differencing or power transformation.
In reviewing period 107 and 108  , AUTOBOX found their effect to be insignificant given the model at that time. The whole idea is to identify , estimate and validate the need for the coefficients and the sufficiency of the model. TS in its log model without seasonal pulses may have found 107 and 108 to be important.
Comment: Don't worry IrishStat, that's enough. Thank you for helping!
Comment: Thanks for the answer IrishStat. I understood what you said, but I don't see the significant ACF(12). Maybe ACF(11)?
Comment: I meant the acf(12) in your analysis. falsely suggesting the need for a seasonal arima structure to be added OR as TS falsely suggested the need for seasonal differencing. Modifications to models need to be as simple as necessary BUT not too simple. TS was just relying on the only remedy they have (perhaps killing the patient !).
Comment: I don't think to have understood.. In my analysis the ACF/PACF haven't significative lag 12, both differentiated series and resiual on AR(1) model. But you said " the presence of a significant acf(12) is suggestive that the current model is inadequate", what you meant? The residual of ARIMA one or of AR one? Thanks again.
Comment: Perhaps your/TS (unwarranted) need to take logs caused the big difference in detecting the first major anomaly . Logs like any other forms of transformations (differencing,arima,detrending et al) can have negative consequences. See here for when and why to take power transforms https://stats.stackexchange.com/questions/18844/when-and-why-should-you-take-the-log-of-a-distribution-of-numbers. Notice that my plot of residuals in no way suggests a linkage between the expected value and the local variance.
Comment: when you observe a significant acf say at lag(11) or perhaps lag(12) or perhaps lag13  or mildly in your case (value .17 for lag 11 or so  reading your graph) one might consider adding either a ma(12) or an ar(12) to the current model ... this is the iterative activity suggested by Box . Simply I was suggesting that TS was incorrectly responding to the (.17 for lag 11 from your graph) by suggesting ( as you wrote : TRAMO suggests to use seasonal difference) the incorrect need to consider adding seasonal differencing.
Comment: Ok, I understood. The problem is that without seasonal differencing every model I use (with seasonal part or not) cannot delete the significative correlation at lag(11). If I add seasonal differencing, I can find a model that delete that significative lag. What do you think about this? Is it possible that TRAMO suggests seasonal differencing just to make lag more significative and delete it using models with seasonal part?
Comment: note that the acf of lag 11 in the AUTOBOX model is .07 ... quite non-significant.. A possible reason is that your models with and without seasonal differencing are deficient is that the only seasonality that exists is deterministic for two months of the year. Free software often comes with a price.
Comment: If you want to continue this offline I would be glad to help you as dialogues are often more useful than monologues
Comment: glad to have helped
Comment: If I have helped to bring you closure promote my answer by an uptick and accept to close the question

Outlier in differentiated series


Baumslag-Solitar Group $G=\langle a,t \mid tat^{-1}=a^k\rangle\cong\mathbb{Z}[1/k]\rtimes\langle t\rangle$?

Question: Let $G$ be the Baumslag-Solitar group $\langle a,t \mid tat^{-1}=a^k\rangle$ and
$$\mathbb{Z}[1/k]:=\left\{\frac{x}{k^n}\mid x\in\mathbb{Z},n\in\mathbb{N}\cup\{0\}\right\}.$$
I'm searching for an isomorphism $G=\langle a,t \mid tat^{-1}=a^k\rangle\cong\mathbb{Z}[1/k]\rtimes\langle t\rangle$. I only need to know the map $\Psi:\langle a\rangle^G\to\mathbb{Z}[1/k]$.
I defined $$\Psi(t^na^xt^{-n}):=\frac{x}{k^n}.$$
But for one hour I'm calculating to prove that this map induces an homomorphism, but I always get for $n>m$:
$$\Psi(t^na^xt^{-n})\cdot \Psi(t^ma^yt^{-m})=\frac{x}{k^n}+\frac{y}{k^m}=\frac{x+y\cdot k^{n-m}}{k^n}$$
and
$$\Psi(t^na^xt^{-n}\cdot t^ma^yt^{-m})=\Psi(t^ma^{(x\cdot k^{n-m})}t^{-m}t^myt^{-m})=\Psi(t^ma^{x\cdot k^{n-m}+y}t^{-m})=\frac{x\cdot k^{n-m}+y}{k^m}.$$
And these images are obvisually unequal. So what is my fault?
Is this map the wrong one?
Thanks for your help.
Comment: I think Baumslag–Solitar group is correct but I am not sure.
Comment: Yes. Thank you.
Comment: $tat^{-1}=a^k$, so $\Psi(t^n a^x t^{-n})$ should multiply (not divide) the exponent of $a$ by $k$.  Hence the image should be $xk^n$.
Answer: You need to modify the definition of $\Psi$: put $$\Psi(t^na^xt^{-n})=xk^n$$ (instead of $\Psi(t^na^xt^{-n})=xk^{-n}$). The homomorphic property should follow easily along the lines of the computations given in the original question.
Alternatively, you could replace $t$ by $t^{-1}$ in the definition of the Baumslag-Solitar group, in which case the $\Psi$ as originally given is a homomorphism.


In Active Directory, how do I delegate write permissions on specific attributes of protected user accounts?

Question: We have a tool being developed that will keep specific attributes of Active Directory user objects up to date with an authoritative source of employee information truth elsewhere, so that when someone's phone number or manager or location changes, Active Directory is automatically updated.
For normal users, delegation of manipulating to those properties is simple to handle using the delegation tools, but protected users, who have the adminSDHolder ACL applied, it's more difficult.
When adding an ACE to the adminSDHolder ACL using the UI, you're only able to grant access to all properties (which we don't want for security reasons), or properties that exist on the adminSDHolder object itself - not user properties like department.
How do you grant access to specific properties of user objects under the protection of adminSDHolder?
Comment: Not to be **that** guy, but why do you have users who are affected by adminSDHolder who need to have HR information updated? You should be following an LPU model of system administration and using separate named accounts for administration, such as ShaneMaddenAdmin (or whatever), so you shouldn't have any user accounts that would need HR information updated as members of any protected groups.
Comment: @joeqwerty Key word being "should" - not all of the accounts are split currently, but agreed that they should be.
Answer: This is doable, but only through the command line tools - the UI is incapable of making the changes (and of figuring out what those ACEs actually are once they're in place).
In order to grant access to a specific user object attribute, for example telephoneNumber, use dsacls:
dsacls "CN=AdminSDHolder,CN=System,DC=example,DC=com" /G Allow-User-Management:RPWP;telephoneNumber;

This creates an ACE for that attribute, which is meaningless on adminSDHolder since it doesn't have a telephoneNumber, but is then applied to the protected users.
Note that the UI tools will look like this, which a each of these properties you grant for creating an ACE that it isn't sure what to make of:

But, dsacls "CN=AdminSDHolder,CN=System,DC=example,DC=com" will show the truth:
Allow Allow-User-Management
                                      SPECIAL ACCESS for sn
                                      WRITE PROPERTY
                                      READ PROPERTY
Allow Allow-User-Management
                                      SPECIAL ACCESS for telephoneNumber
                                      WRITE PROPERTY
                                      READ PROPERTY


Doctrine: Relacionamento ManyToMany com Campos Extras

Question: Tenho um relacionamento muitos para muitos entre duas tabelas: Produtos e Pedidos.
O Doctrine gera então uma terceira tabela. Até aí tranquilo.
Porém queria gerar nesta terceira tabela mais campos (qtde e valor unitário no momento da compra).
A pergunta é: Como faço esse relacionamento funcionar no Doctrine (com as annotations direto nas Entidades) e como faço para pegar/setar depois a quantidade e o valor de um determinado produto do pedido (terceira tabela)?
O mais perto de uma explicação que achei foi isso: https://stackoverflow.com/questions/15616157/doctrine-2-and-many-to-many-link-table-with-an-extra-field/15630665#15630665
Mas ali não é explicado o funcionamento do ArrayCollection para casos assim e nem como fazer para pegar ou setar os campos extras da terceira tabela.
Desde já agradeço toda ajuda que puderem dar.
Tabela Products (Tabela 1)
Id           (pk)
Name
Value

Tabela Orders (Tabela 2)
Id           (pk)
TotalValue

Tabela ProductsOrders (Tabela de Instersecção)
Product      (fk)
Order        (fk)
Quantity
UnityValue

--
Entidades
Segue abaixo as entidades feitas conforme instruções. Note, porém, que falta o método correto de se trabalhar com as colunas extras - i. e., como fazer para e EntityManager pegar as colunas extras da entidade ProductOrder (através, claro, dos campos de ligação nas entidades Product e Order).
Também é importante a informação de como proceder para fazer o relacionamento desta terceira tabela com uma outra, já que ela não possui ID prórpio, posto que o ID é formado pelo conjunto de ID do Produto + ID do Pedido.
<?php

/**
 * @Entity(repositoryClass="Repositories\ProductRepository")
 * @Table(name="Products")
 */
class Product
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue
     */
    protected $id;

    /**
     * @Column(length=100)
     */
    protected $name;

    /**
     * @Column(type="decimal", precision=10, scale=2)
     */
    protected $value;

    /**
     * @OneToMany(targetEntity="ProductOrder", mappedBy="product")
     */
    protected $orders;

    public function __construct()
    {
        $this->orders = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getId(): int
    {
        return $this->id;
    }

    public function setId(int $id): Product
    {
        $this->id = $id;
        return $this;
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function setName(string $name): Product
    {
        $this->name = $name;
        return $this;
    }

    public function getValue(): float
    {
        return $this->value;
    }

    public function setValue(float $value): Product
    {
        $this->value = $value;
        return $this;
    }

    public function getOrders()
    {
        return $this->orders;
    }

    public function addOrder(Order $order)
    {
        if ($this->getOrders()->contains($order)) {
            return $this;
        }

        $this->getOrders()->add($order);
        $order->addProduct($this);

        return $this;
    }

    public function removeOrder(Order $order)
    {
        if (!$this->getOrders()->contains($order)) {
            return $this;
        }

        $this->getOrders()->removeElement($order);
        $order->removeProduct($this);

        return $this;
    }
}

/**
 * @Entity(repositoryClass="Repositories\OrderRepository")
 * @Table(name="Orders")
 */
class Order
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue
     */
    protected $id;

    /**
     * @Column(type="decimal", precision=10, scale=2)
     */
    protected $totalValue;

    /**
     * @OneToMany(targetEntity="ProductOrder", mappedBy="order")
     */
    protected $products;

    public function __construct()
    {
        $this->products = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getId(): int
    {
        return $this->id;
    }

    public function setId(int $id): Order
    {
        $this->id = $id;
        return $this;
    }

    public function getTotalValue(): float
    {
        return $this->totalValue;
    }

    public function setTotalValue(float $totalValue): Order
    {
        $this->totalValue = $totalValue;
        return $this;
    }

    public function getProducts()
    {
        return $this->products;
    }

    public function addProduct(Product $product)
    {
        if ($this->getProducts()->contains($product)) {
            return $this;
        }

        $this->getProducts()->add($product);
        $product->addOrder($this);

        return $this;
    }

    public function removeProduct(Product $product)
    {
        if (!$this->getProducts()->contains($product)) {
            return $this;
        }

        $this->getProducts()->removeElement($product);
        $product->removeOrder($this);

        return $this;
    }
}

/**
 * @Entity(repositoryClass="Repositories\ProductOrderRepository")
 * @Table(name="ProductsOrders")
 */
class ProductOrder
{
    /**
     * @Id
     * @ManyToOne(targetEntity="Order", inversedBy="products")
     * @JoinColumn(name="order", referencedColumnName="id")
     */
    protected $order;

    /**
     * @Id
     * @ManyToOne(targetEntity="Product", inversedBy="orders")
     * @JoinColumn(name="product", referencedColumnName="id")
     */
    protected $product;

    /**
     * @Column(type="integer")
     */
    protected $quantity;

    /**
     * @Column(type="decimal", precision=10, scale=2)
     */
    protected $unityValue;

    public function getOrder()
    {
        return $this->order;
    }

    public function setOrder($order)
    {
        $this->order = $order;
        return $this;
    }

    public function getProduct()
    {
        return $this->product;
    }

    public function setProduct($product)
    {
        $this->product = $product;
        return $this;
    }

    public function getQuantity()
    {
        return $this->quantity;
    }

    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;
        return $this;
    }

    public function getUnityValue()
    {
        return $this->unityValue;
    }

    public function setUnityValue($unityValue)
    {
        $this->unityValue = $unityValue;
        return $this;
    }
}

Exemplo de uso da EM
<?php

$product = $em->getReference(User::class, 1);
$order = $em->getReference(User::class, 1);

$productOrder = new ProductOrder();
$productOrder
    ->setOrder($order)
    ->setProduct($product)
    ->setQuantity(5)
    ->setUnityValue(99.9);

// Isso está cadastrando corretamente.
$em->getRepository(ProductOrder::class)->create($productOrder);

// Porém, isso não está funcionando:
echo $order->getProducts()[0]->getQuantity();

Comment: Poderia postar seus models? O que a resposta linkada sugere é que seja criada uma terceira entidade, algo como um `OrderItems`
Comment: A terceira tabela não eh orderitens. A terceira tabela (ou como ela deve ficar) eh a ProductsOrders. Já que eu posto as entidades como estão no momento.
Comment: Para facilitar minha necessidade, adicionei como estou fazendo no momento. Note que o cadastro funciona (embora acredito que posa ser feito de outro jeito) porém não encontrei uma forma de, pela entidade Order pegar os dados extras dos produtos do pedido (como quantidade comprada, por exemplo)
Answer: Uma forma de fazer é tratar a terceira tabela (PorductsOrders) como um entidade normal.
Neste caso você não usará ArrayCollections (pelo menos não nas entidades) e fará as pesquisas usando apenas a tabela de intersecção.
Para isso remova a opção InversedBy das anotations da entidade ProductOrder e remova as propriedades Store#products e Product#stores.
/**
 * @Entity(repositoryClass="Repositories\ProductOrderRepository")
 * @Table(name="ProductsOrders")
 */
class ProductOrder
{
    /**
     * @Id
     * @ManyToOne(targetEntity="Order")
     * @JoinColumn(name="order", referencedColumnName="id")
     */
    protected $order;

    /**
     * @Id
     * @ManyToOne(targetEntity="Product")
     * @JoinColumn(name="product", referencedColumnName="id")
     */
    protected $product;

    /**
     * @Column(type="integer")
     */
    protected $quantity;

    /**
     * @Column(type="decimal", precision=10, scale=2)
     */
    protected $unityValue;

    public function getOrder()
    {
        return $this->order;
    }

    public function setOrder($order)
    {
        $this->order = $order;
        return $this;
    }

    public function getProduct()
    {
        return $this->product;
    }

    public function setProduct($product)
    {
        $this->product = $product;
        return $this;
    }

    public function getQuantity()
    {
        return $this->quantity;
    }

    public function setQuantity($quantity)
    {
        $this->quantity = $quantity;
        return $this;
    }

    public function getUnityValue()
    {
        return $this->unityValue;
    }

    public function setUnityValue($unityValue)
    {
        $this->unityValue = $unityValue;
        return $this;
    }
}

Você pode fazer uso da entidade de intersecção assim:
<?php

$product = $em->getReference(User::class, 1);
$order = $em->getReference(User::class, 1);

$productOrder = new ProductOrder();
$productOrder
    ->setOrder($order)
    ->setProduct($product)
    ->setQuantity(5)
    ->setUnityValue(99.9);

// Isso está cadastrando corretamente.
$em->getRepository(ProductOrder::class)->create($productOrder);

Para pesquisar, pode ser feito assim:
<?php

// Pesquisando:
$productOrder = $em->findBy([
    'order' => 1,
    'product' => 1
]);

Obs: Opcionalmente, em seu repositório ProductOrderRepository, você pode criar o método findByIds($orderId, $productId), o método findOrderProducts($orderId) e o método findProductOrders($productId)
Comment: Muito obrigado!
Answer: Segundo esse post a solução é considerar a tabela de join como uma entidade separada e mapear os relacionamentos como One-To-Many.
Na implementação que mostrastes o mapeamento de Product.orders e Orders.product já deve retornar uma lista de ProductOrders, assim já tens acesso às colunas extra.
Vais precisar acrescentar um constructor em ProductOrders que receba o Product e o Order:

ProductOrder{
    ...
    public function __construct(Order $order, Product $product, $quantity= 0, $unitValue=0)
    {
        $this->product= $product;
        $this->order= $order;
        $this->quantity= $quantity;
        $this->unitValue= $unitValue;
    }
}

Podes também acrescentar os getters e setters da mesma maneira que fizeste nas outras entidades.
Comment: Agradeço a disposição, porém a necessidade está principalmente acessar os campos extras pela EntityManager. Note também que é solicitado a melhor maneira de se fazer uso das ArrayCollections para este caso nas entidades Product#orders e Order#products
Comment: @Szag-Ot Sendo que `ProductOrder` é mapeado como uma entidade tu vais utilizar o EM(EntityManager) da mesma forma que faria para fazer uma query de `Product` ou `Order`. Com relação ao `ArrayCollections` não ficou claro qual é a dúvida.
Comment: Product e Order possuem ID. Já em ProductOrder, o ID é um conjunto de ambas entidades. Como fazer um $em->find()? Uma forma seria usar o $em->findBy() passando ambos os ids, mas isso não me parece ser o certo. Também, ao usar a entidade Product ou a Order para pegar a coleção da contra-tabela, os campos extras não são trazidos. (Exemplo: $orders->getProducts() retorna a lista de entidades Produto relacionadas ao pedido, porém SEM OS CAMPOS EXTRAS). Perceba o pq necessito de uma resposta bem completa....
Comment: para faciliar minha necessidade, adicionei como estou fazendo no momento. Note que o cadastro funciona (embora acredito que posa ser feito de outro jeito) porém não encontrei uma forma de, pela entidade Order pegar os dados extras dos produtos do pedido (como quantidade comprada, por exemplo)


How run grunt when server start from node?

Question: I would like to refresh automatically my generated files, generated by grunt. To do so, I would like to run automatically grant from nodeJs.
I found the reverse, run node server from grunt, but it's not what I want to do.
Do you have tips to run grunt when the server start? Maybe it's something like call command line from node, but I'm not used to do that. Thanks.
Answer: Final solution:
<code>    var spawn = require('child_process').spawn;
    var cp = spawn(process.env.comspec, ['/c', 'grunt']);// ['/c', 'command', '-arg1', '-arg2']

    cp.stdout.on("data", function(data) {
        console.log(data.toString());
    });

    cp.stderr.on("data", function(data) {
        console.error(data.toString());
    });
</code>
Found here: Spawn on Node JS (Windows Server 2012)
Thanks to @Diadara.
Answer: You could use child process
<code>var spawn = require('child_process').spawn,
grunt    = spawn('grunt', ['args']);

grunt.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
</code>
As you can see the child process is run asynchronously, if you want to run grunt synchronously then look at this question node.js execute system command synchronously
Comment: Yes, but I try before ;) And I have some trouble under windows OS. https://github.com/joyent/node/issues/2318 or https://www.google.dk/search?q=spawn+enoent&oq=spawn+enoent&aqs=chrome..69i57.3004j0j1&sourceid=chrome&ie=UTF-8#q=spawn+enoent+windows&safe=off
Comment: Your solution is OK under !windows (mac & linux work)


CSS - Como fazer referência a outro Combobox?

Question: Caros, tenho 2 combobox autocomplete em cascata para Estado e Cidade. Quando troco o tamanho no CSS, muda o tamanho dos 2 combobox e preciso mudar de apenas 1.
Utilizo o código de exemplo do JQuery-UI e o seguinte CSS:
.custom-combobox-input {
  margin: 0;
  padding: 5px 10px;
  width: 186px;
  height: 24px;
  border: thin #1E56A0 solid;
  padding-left: 5px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 16px;
}

HTML:

  <select id="selestado" name="selestado" ></select>

  <select id="selcidade" name="selcidade" ></select>

Não entendo muito de CSS, como fazer referência ao segundo combo?
Acho que podem entender melhor no seguinte exemplo que usei de base: https://jsfiddle.net/mindlessbaby/zbjk1ss1/70/
Comment: Sobre o "combobox" na verdade é de melhor compreensão chama-lo de `select` ou então `dropdown` que é um `select` personalizado do jQuery. Pois o `select` é o elemento responsável por atuar desta forma no HTML. Outra coisa é que aparentemente o seu html está incompleto, pois você referencia a classe `.custom-combobox-input` porém não utiliza no seu código html disponibilizado aqui na sua pergunta. Forneça o uma fração maior do código para que possa obter respostas.
Comment: Todavia, uma forma de referenciar o segundo `select`, seria através deste seletor (baseado no html da sua pergunta): `select[name=selcidade] { }` ou então pelo id: `#cmbcidade { }`
Comment: Usando o código de exemplo do JQuery-UI na verdade é usado um campo INPUT (onde pode ser digitado os valores e que é buscado no JSON) e o JQuery lista como se fosse um select. Acho que voces poderão entender melhor no seguinte exemplo em que usei de base: https://jsfiddle.net/mindlessbaby/zbjk1ss1/70/
Comment: Dessa forma que você apresentou no fiddle, acredito que utilizar `.custom-combobox-input:nth-child(1)` para a combo de estado e `.custom-combobox-input:nth-child(2)` para a combo de cidade seria uma opção.
Answer: Os combobox são criado pelo jQuery de forma assíncrona. Neste caso, você pode alterar a largura de qualquer um deles após a função que os cria terminarem.
Você pode fazer isso incluindo uma linha em jQuery:
$(".custom-combobox-input:eq(1)").css("width","400px");

Onde :eq(1) é o segundo combobox (o primeiro seria :eq(0)).
Adicione o código no local indicado abaixo pela seta:
$(function () {
    $("#one").append($('<option selected></option>').val('1').html('1'));

    $("#one").append($('<option></option>').val('2').html('2'));

    $("#one").combobox({
        select: function (event, ui) {
            updateTwo($(this).val());
        }
    });

    // added- update one box value and refresh ui -BD
    $("#two").combobox();
    $("#one").val("1").combobox("refresh");
    updateTwo($("#one").val());

   $(".custom-combobox-input:eq(1)").css("width","400px"); // ←
});

Veja funcionando:

(function ($) {
    $.widget("custom.combobox", {
        _create: function () {
            this.wrapper = $("")
                .addClass("custom-combobox")
                .insertAfter(this.element);

            this.element.hide();
            this._createAutocomplete();
            this._createShowAllButton();
        },

        _createAutocomplete: function () {
            var selected = this.element.children(":selected"),
                value = selected.val() ? selected.text() : "";

            this.input = $("<input>")
                .appendTo(this.wrapper)
                .val(value)
                .attr("title", "")
                .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
                .autocomplete({
                delay: 0,
                minLength: 0,
                source: $.proxy(this, "_source")
            })
                .tooltip({
                tooltipClass: "ui-state-highlight"
            });

            this._on(this.input, {
                autocompleteselect: function (event, ui) {
                    ui.item.option.selected = true;
                    this._trigger("select", event, {
                        item: ui.item.option
                    });
                },

                autocompletechange: "_removeIfInvalid"
            });
        },

        _createShowAllButton: function () {
            var input = this.input,
                wasOpen = false;

            $("")
                .attr("tabIndex", -1)
                .attr("title", "Show All Items")
                .tooltip()
                .appendTo(this.wrapper)
                .button({
                icons: {
                    primary: "ui-icon-triangle-1-s"
                },
                text: false
            })
                .removeClass("ui-corner-all")
                .addClass("custom-combobox-toggle ui-corner-right")
                .mousedown(function () {
                wasOpen = input.autocomplete("widget").is(":visible");
            })
                .click(function () {
                input.focus();

                // Close if already visible
                if (wasOpen) {
                    return;
                }

                // Pass empty string as value to search for, displaying all results
                input.autocomplete("search", "");
            });
        },

        _source: function (request, response) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
            response(this.element.children("option").map(function () {
                var text = $(this).text();
                if (this.value && (!request.term || matcher.test(text))) return {
                    label: text,
                    value: text,
                    option: this
                };
            }));
        },

        _removeIfInvalid: function (event, ui) {

            // Selected an item, nothing to do
            if (ui.item) {
                return;
            }

            // Search for a match (case-insensitive)
            var value = this.input.val(),
                valueLowerCase = value.toLowerCase(),
                valid = false;
            this.element.children("option").each(function () {
                if ($(this).text().toLowerCase() === valueLowerCase) {
                    this.selected = valid = true;
                    return false;
                }
            });

            // Found a match, nothing to do
            if (valid) {
                return;
            }

            // Remove invalid value
            this.input.val("")
                .attr("title", value + " didn't match any item")
                .tooltip("open");
            this.element.val("");
            this._delay(function () {
                this.input.tooltip("close").attr("title", "");
            }, 2500);
            this.input.autocomplete("instance").term = "";
        },
        // added- inserted refresh function -BD
        refresh: function () {
            selected = this.element.children(":selected");
            this.input.val(selected.text());
        },
        _destroy: function () {
            this.wrapper.remove();
            this.element.show();
        }
    });
})(jQuery);

$(function () {
    $("#one").append($('<option selected></option>').val('1').html('1'));

    $("#one").append($('<option></option>').val('2').html('2'));

    $("#one").combobox({
        select: function (event, ui) {
            updateTwo($(this).val());
        }
    });

    // added- update one box value and refresh ui -BD
    $("#two").combobox();
    $("#one").val("1").combobox("refresh");
    updateTwo($("#one").val());

   $(".custom-combobox-input:eq(1)").css("width","400px");
});

function updateTwo(arg1) {
    $("#two").empty();

    if (arg1 == "1") {
        $("#two").append($('<option selected></option>').val('1.1').html('1.1'));

        $("#two").append($('<option></option>').val('1.2').html('1.2'));
    } else if (arg1 == "2") {
        $("#two").append($('<option selected></option>').val('2.1').html('2.1'));

        $("#two").append($('<option></option>').val('2.2').html('2.2'));
    }

    // added- update second box value and refresh ui -BD
    $("#two").val("").combobox("refresh");

}
.custom-combobox {
    position: relative;
    display: inline-block;
}
.custom-combobox-toggle {
    position: absolute;
    top: 0;
    bottom: 0;
    margin-left: -1px;
    padding: 0;
}
.custom-combobox-input {
    margin: 0;
    padding: 5px 10px;
}

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

    <select id="one"></select>

    <select id="two"></select>

Comment: Beleza, boa resposta e concordo que funciona, mas precisa mesmo utilizar jQuery? se ele souber a qtde. de combos que serão criadas e a ordem de cada uma não seria necessário.
Comment: @PauloRoberto Pelo CSS eu não consegui. Acho que o CSS do jquery UI não deixa alterar. Como são apenas dois campos, acho bem mais simples apenas adicionar uma linha e o problema tah resolvido.
Comment: tentou utilizar com **important**? `input.custom-combobox-input:nth-child(2){ width: 400px !important; }` é provavel que funcione, a não ser que haja outro **important** atribuido na `width` deles pelo proprio jQuery UI, dai teria que ver uma forma de especificar mais ainda o seletor, pois quanto mais específico o seletor CSS é, a prioridade é maior, portanto em determinado nível de específico, sobrescreverá o jQuery UI. Eu estou comentando pois estou impossibilitado de testar, o proxy daqui bloqueia alguns sources e fico com problemas em determinados Fiddles.
Comment: @PauloRoberto Já testei com !important, com nth-child, tentei inserir um CSS dinâmico após 5 segundos, nada funcionou.
Comment: Perfeito. Obrigado @ÐvÐ, obrigado a todos. Abs


Let $V=\Bbb{R}^2$ and $S$ is the set of all vectors $(x,y)$ in $V$ satisfying $3x+2y=0$. Is it a subspace of $V$?

Question: the set is $\{(x,y)\in \Bbb{R}^2 \mid 3x+2y=0\}$ Is it right I have no idea how to determine it is a subspace $(0,0)$ is a zero vector and it is in $S$ what about inverse.I see it is closed under scalar multiplication and addition then how should I prove? can anyone give a detailed solution and set notation form.
Comment: In order for a subset of a vector space to be a subspace, all you need to check if it is closed under addition and scalar multiplication, which is a simple exercise.
Answer: You already checked it is not empty as the zero vector is in it, so now you must check that
1) Whenever $\;(a,b),\,(c,d)\in S\;$ , also $\;(a,b)+(c,d)\in S\;$ , and also
2) Whenever $\;(a,b)\in S\;$ and for any $\;k\in\Bbb R\;$,  also $\;k(a,b)\in S\;$ .
Both things are very easy to verify in this case.
Answer: Hint
You  can simply note that from the definition of $S$ you have:
$$
3x+2y=0 \quad \iff \quad y=-\frac{3}{2}x
$$
si the vectors in $S$ have the form:
$$
\begin{bmatrix}
x\\-\frac{3}{2}x
\end{bmatrix}
$$
Can you do from this?


Hosting: 1 Windows, 1 Linux, 1 Internet IP Address. How?

Question: I have 1 Internet IP address.
I have 2 PHYSICAL web servers.
1 Windows IIS7 hosting 3 websites. Host-header names are configured in IIS7. This works OK until I add:
1 Linux (Ubuntu lucid) Apache2 hosting 1 website. VirtualHost is configured in Apache2. I followed theses steps: http://ubuntu-tutorials.com/2008/01/09/setting-up-name-based-virtual-hosting/
The two servers seem to play "tug-of-war." Could this be just a misconfiguration, or are problems supposed to occur with this kind of setup?
Answer: One possible solution is to give the external IP address to the Ubuntu system and the use it's Apache to reverse proxy for the IIS7 server.
Create a virtualhost for each of the hosts on the IIS server in for example /etc/apache2/sites-avilable/iisproxyhosts
<VirtualHost *:80>
        ServerName IIS.Domain1.TLD
        ProxyRequests Off
        <Proxy *>
                Order deny,allow
                allow from all
        </Proxy>
        ProxyPreserveHost On
        ProxyPass / http://AddressOfIIServer/
        ProxyPassReverse / http://AddressOfIIServer/
</VirtualHost>

<VirtualHost *:80>
        ServerName IIS.Domain2.TLD
        ProxyRequests Off
        <Proxy *>
                Order deny,allow
                allow from all
        </Proxy>
        ProxyPreserveHost On
        ProxyPass / http://AddressOfIIServer/
        ProxyPassReverse / http://AddressOfIIServer/
</VirtualHost>

<VirtualHost *:80>
        ServerName IIS.Domain3.TLD
        ProxyRequests Off
        <Proxy *>
                Order deny,allow
                allow from all
        </Proxy>
        ProxyPreserveHost On
        ProxyPass / http://AddressOfIIServer/
        ProxyPassReverse / http://AddressOfIIServer/
</VirtualHost>

Enable proxying
a2enmod proxy_http
a2enmod proxy

Enable the iisproxyhosts and retstart apache
a2ensite iisproxyhosts
/etc/init.d/apache2 reload

Comment: This is probably what I'd do, only with Varnish, rather than Apache, but same difference.
Answer: Name-based virtual hosting only works when all virtual hosts are running on the same web server instance.  In this case, you will need to use NAT to get both machines on the network and either configure the NAT box to forward connections to a nonstandard port to one of the boxes, or arrange for one of the web servers to proxy for the other (name based virtual hosting would then be useful to invoke the proxy).  Or just buy another IP address.
Comment: For the record, what you're after here is a "reverse proxy", there are quite a lot of [questions about it here](http://serverfault.com/search?q=reverse+proxy)
Answer: Microsoft TMG Server as the firewall in front of these two servers can host multiple web URL's on one public IP address and "reverse proxy" to multiple hosts behind it using NAT.  Easy solution is to get another public IP as @geekosaur said.
Comment: Great solution, but expensive
Answer: You can forward port 80 to an Apache on Linux that would serve as reverse proxy to Both Apache (On port other than 80) and IIS.
It would send request to Apache (Linux) or IIS depending on domain name in request.
Answer: You are having a server with a public IP and apache is running on it.Now you want to host your applications on LAN and also want them to be accessible on internet the important part is these applications are still running on the machines on LAN.
For this situation a Reverse Proxy is  needed.
Here is some explanation of such a setup
let say the websites are :
a)internal1.example.com should map to internal1.example.com
b)internal2.example.com should map to internal2.example.com
c)internal3.example.com should point to internal3 .example.com
d)internal4.example.com should point to internal4 .example.com
                           |--------------192.168.1.3
                           |            (internal3.example.com)
                           |
                           |--------------192.168.1.4
                           |            (internal4.example.com)
  (Public IP )             |
            A-------------|
(reverse proxy server)     |
  (192.168.1.25)           |
example.com                |
                           |--------------192.168.1.1
                           |            (internal1.example.com)
                           |
                           |--------------192.168.1.2
                           |            (internal2.example.com)

I am using Ubuntu to host Apache the vhost definition in case of Debian based systems the definiton of websites is done on system A in above diagram which has public IP
/etc/apache2/sites-enabled/internal1.conf
/etc/apache2/sites-enabled/internal2.conf
/etc/apache2/sites-enabled/internal3.conf
/etc/apache2/sites-enabled/internal4.conf

The vhost definition of each of these sites will be as follows
/etc/apache2/sites-enabled/internal1.example.conf
<virtualhost *:80>

      ServerAdmin webmaster@localhost
      ServerName internal1.example.com
      ProxyRequests off
      <proxy *>
      Order deny,allow
      Allow from all
      </proxy >
      ProxyPass / http://192.168.1.1/
      ProxyPassReverse / http://192.168.1.1/
</VirtualHost >

/etc/apache2/sites-enabled/internal2.example.conf
<virtualhost *:80>

      ServerAdmin webmaster@localhost
      ServerName internal2.example.com
      ProxyRequests off
      <proxy *>
      Order deny,allow
      Allow from all
      </proxy >
      ProxyPass / http://192.168.1.2/
      ProxyPassReverse / http://192.168.1.2/
</VirtualHost >

/etc/apache2/sites-enabled/internal3.example.conf
<virtualhost *:80>

      ServerAdmin webmaster@localhost
      ServerName internal3.example.com
      ProxyRequests off
      <proxy *>
      Order deny,allow
      Allow from all
      </proxy >
      ProxyPass / http://192.168.1.3/
      ProxyPassReverse / http://192.168.1.3/
</VirtualHost >

/etc/apache2/sites-enabled/internal4.example.conf
<virtualhost *:80>

      ServerAdmin webmaster@localhost
      ServerName internal4.example.com
      ProxyRequests off
      <proxy *>
      Order deny,allow
      Allow from all
      </proxy >
      ProxyPass / http://192.168.1.4/
      ProxyPassReverse / http://192.168.1.4/
</VirtualHost >

Note in all of the above vhost definitions I have dropped the options of Log files.
So if you apply to a production server add them in each of the vhost file.
Above is just to give you a clear cut example as how it can be working.


How to split parts of list elements separated by commas into new lists?

Question: I have read the contents of a file into a list by reading each line as a new element. Now I want to separate these further into their own sublists. For example, the first value before the first comma in each string is a date, so I want to make a new list with only the dates from this given list, and so on. How can I go about doing this?
['2019/01/11,1640.5600,4670093.0000,1640.5500,1660.2940,1636.2200', '2019/01/10,1656.2200,6487252.0000,1641.0100,1663.2500,1621.6150', '2019/01/09,1659.4200,6333528.0000,1652.9800,1667.7989,1641.3953',  '2014/01/13,390.9800,2843810.0000,397.9800,399.7800,388.4500']

I've tried using list.split to separate the values indicated by commas, but I can't get it to work on this whole list.
Comment: I think you would have to loop through each of the values of the `list` with a `for-loop`. Look at the documentation [here](https://docs.python.org/3/tutorial/controlflow.html#for-statements) for more information.
Answer: lines = [
    '2019/01/11,1640.5600,4670093.0000,1640.5500,1660.2940,1636.2200',
    '2019/01/10,1656.2200,6487252.0000,1641.0100,1663.2500,1621.6150',
    '2019/01/09,1659.4200,6333528.0000,1652.9800,1667.7989,1641.3953',
    '2014/01/13,390.9800,2843810.0000,397.9800,399.7800,388.4500',
]

dates = [line.split(',')[0] for line in lines]
print(dates)


Laravel 5 - Eloquent JOIN confusion

Question: I have two simple tables, cats and breeds:
mysql> select * from cats;
+----+--------+---------------+----------+---------------------+---------------------+
| id | name   | date_of_birth | breed_id | created_at          | updated_at          |
+----+--------+---------------+----------+---------------------+---------------------+
|  1 | Rita   | 2008-07-06    |        1 | 2015-05-09 20:40:49 | 2015-05-09 20:50:20 |
|  2 | Muni   | 1992-05-15    |        3 | 2015-05-09 20:50:54 | 2015-05-09 20:50:54 |
|  3 | Hector | 2005-01-23    |        4 | 2015-05-09 21:08:23 | 2015-05-09 21:08:23 |
+----+--------+---------------+----------+---------------------+---------------------+
3 rows in set (0.00 sec)

mysql> select * from breeds;
+----+------------+
| id | name       |
+----+------------+
|  1 | Domestic   |
|  2 | Persian    |
|  3 | Siamese    |
|  4 | Abyssinian |
+----+------------+
4 rows in set (0.00 sec)

All I want to do is get a list of the cats that are of a certain breed. In the cats table, breed_id is a FK that points to the PK of the breeds table. The example code in my book which is supposed to return a view with all cats of a specific breed returns no results:
The url I am trying is /cats/breeds/Domestic
The view that is generated uses this logic in the routes.php file:
Route::get('cats/breeds/{name}', function($name)
{
    $cats = Furbook\Cat::with('breeds')
        ->whereName($name)
        ->get();
dd($cats);
});

When I dd($cats) I get zero results even though I have a cat with a domestic breed_id of 1. What have I done wrong here?
EDIT:
I can get it to work with the following hacky code, which first gets the id from the breeds table by querying against the name field, then queries the cats table with that id:
$breed = Furbook\Breed::whereName($name)->get();
$id = $breed[0]['attributes']['id'];
$cats = Furbook\Cat::whereId($id)->get();

How do I make this into one Eloquent query? I see no examples for this kind of query on the Laravel site.
For more information this is how the models look:
class Breed extends Model {

    public $timestamps = false;

    public function cats()
    {
        return $this->hasMany('Furbook\Breed');
    }

}

class Cat extends Model {

    protected $fillable = [
        'name',
        'date_of_birth',
        'breed_id',
    ];

    public function breed()
    {
        return $this->belongsTo('Furbook\Breed');
    }

}

Answer: You're asking the system to give you all cats with a name of Domestic - not all cats of the breed name Domestic.
Assuming your model relationships are in order, you could do e.g.
$cats = Furbook\Breed::whereName($name)->first()->cats;

Also, my Burmese cat just hit the monitor; I think she's upset that she's not in the breeds list.
Comment: Your solution produced a sql error. I can share it if you want to see it. It was basically querying the breeds table with a field that only exists in cats, breed_id.
Comment: fyi it's "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'breeds.breed_id' in 'where clause' (SQL: select * from `breeds` where `breeds`.`breed_id` = 1 and `breeds`.`breed_id` is not null)"
Comment: Then I assume you have not set up relationships between the breeds and the cats in your models? I mean, I'm essentially doing the same thing as in your edit.
Comment: I updated my original post. FYI all the code besides my little hack is coming straight from the book 'laravel 5 essentials' (a new book with a surprising number of errors).
Comment: Great, relevant code always makes it easier. It looks like both models are referring to `Furbook\Breed`; the one in the `cats()` function should be `Furbook\Cat`. That also explains the SQL error you got above - Laravel is trying to search your breeds table for cats.
Comment: In the Breed class I changed the line to this: return $this->hasMany('Furbook\Cat'); and it finally worked. Thank you Joel. To anyone else reading this, don't buy 'Laravel 5 Essentials'. This is only one of several errors in the book.
Comment: Sucks to hear about the book being bad, but I'm glad you got it working. Hope the rest of the book is less crappy.

Laravel 5 - Eloquent JOIN confusion


How to create a fast loading wrapping ListBox?

Question: I've made a nice little three-item wide list of tiles that work as switches. It looks something like this:

Looking good huh? Well, I have about 130 of these tiles in a vertically scrolling list, and it takes ages to load. According to the performance analysis tool, each element takes about 18ms to render - which gives me about a 2.3 second rendering time. On the device, it's often twice that time. This wouldn't really be a crisis, but the UI is totally black and unresponsive up until these elements have been drawn.
After some research online, I realized this is because the WrapPanel control from the toolkit doesn't virtualize its items - thus making the GPU render all objects at once (using up a lot of memory in the process).
Now, are there any ways to make this go faster?
XAML:
<ListBox x:Name="ChannelsListBox" Grid.Row="2" Margin="0,40,0,0">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <toolkit:WrapPanel />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.Template>
        <ControlTemplate>
            <ItemsPresenter />
        </ControlTemplate>
    </ListBox.Template>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid x:Name="ChannelTile" Margin="6,6,6,6" Tap="ChannelTile_Tap">

                <Rectangle Width="136" Height="136" Fill="{StaticResource LightGrayColor}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

The ListBox's ItemsSource is set in the codebehind - if you wondered.
Answer: Well, if you populate the listbox asynchronously from another thread, you can avoid the unresponsive UI.
EDITED2:
public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();

        /* In the xaml code:
           <ListBox x:Name="ChannelsListBox" ItemsSource="{Binding ListOfTestClasses}" ...
        */

        var vm = new MainPageViewModel();
        DataContext = vm;

        vm.StartLoadingDataAsync(10000);
    }
}

public class MainPageViewModel
{
    public ObservableCollection<TestClass> ListOfTestClasses { get; set; }
    private BackgroundWorker workerThread;
    public MainPageViewModel()
    {
        ListOfTestClasses = new ObservableCollection<TestClass>();
        workerThread = new BackgroundWorker();
        workerThread.DoWork += new DoWorkEventHandler((object sender, DoWorkEventArgs e) =>
        {
            for (int i = 0; i < (int)e.Argument; i++)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    ListOfTestClasses.Add(new TestClass { Text = "Element " + (i + 1) });
                });

                Thread.Sleep(150);
            }
        });
    }

    public void StartLoadingDataAsync(int numberOfElements)
    {
        workerThread.RunWorkerAsync(numberOfElements);
    }
}

public class TestClass
{
    public string Text { get; set; }
}

Comment: Try to use some simplier "container" insted of the Grid (for example, Canvas).
And a shitty solution can be for example, waiting some time before adding the next element. In this case the whole rendering takes more time, but the UI won't be unresponsive.
Comment: Thanks @laszlokiss88 - this actually worked quite well. I still have some problems with the threads messing up the order and what not, but with a bit of luck, I'll make it work. Thanks for spending time on writing some example code for me as well :-)
Comment: is there a reason Thread.Sleep is set exactly to 150 ms? Anything lower (like 50 or 100) results in each element being shown several times.
Comment: No, it's just a "random" number. You should define this according your rendering time.
Comment: why does it keep on adding the same item several times though? Doesn't make sense to me.
Comment: oh my god, can't believe I didn't see this before. Thanks so much. +1
Answer: A few ideas which might be helpful:

Find or implement a virtualizing WrapPanel. It's the most appropriate solution, but I don't think I've seen a solid implementation of one yet. But for this purpose, maybe you don't need perfection and can get away with something someone else has already written.
Use a parent virtualizing vertical StackPanel containing horizontal StackPanel children. To do this, you'd need to re-shape your single sequence of data into a shorter sequence of 3-item entries. However, that may not be too hard and should give you most of the benefits of the ideal solution.
Consider implementing "lazy" containers like I did for DeferredLoadListBox. The basic idea is to delay rendering containers until they show up on screen. I have more info and example code here: http://blogs.msdn.com/b/delay/archive/2010/09/08/never-do-today-what-you-can-put-off-till-tomorrow-deferredloadlistbox-and-stackpanel-help-windows-phone-7-lists-scroll-smoothly-and-consistently.aspx
Comment: All great ideas David - I've looked into creating a virtualizing WrapPanel, but since I'm on a schedule, getting into that might be a bit overkill. A nice sideproject idea for later, though. The vertical / horizontal StackPanel combo probably won't work too well for me, since I need to be able to drag these suckers around later on. A "lazy" implementation, however, might be what I'll do. Thanks for your thougths on the subject.


jQuery $.post() and PHP issue

Question: It's not updating and I'm missing what I'm doing wrong.  Uses HTML, jQuery, and PHP.  All code is posted below.
What I'm trying to do is allow a user to change a 'client' seed and when it' changed it's updated.  In the  it's displayed.  All that does is refresh every 100ms from a file that's echoing it out.  There's no issue there.
PHP Code:
<?php
session_start();
include_once('db.php');

if(isset($_POST['action'])) {
    switch($_POST['action']) {

        case 'get_client':
            echo json_encode(array('result' =>  $_SESSION['client']));
        break;

        case 'modify_client':
            if(isset($_POST['client']) && strlen($_POST['client']) == 6 && is_numeric($_POST['client']))  {
                $_SESSION['client'] = $_POST['client'];
                echo json_encode(array('result' => true));

              $secret = 123;
                    $_SESSION['server'] = hash('sha512', $_SESSION['roll'] . $_SESSION['client'] . $secret );
            }

            else {
                echo json_encode(array('result' => false));
            }
        break;
    }
}
?>

Javascript/jQuery:

HTML:
  Current Client Seed:

    <input type="text" placeholder="Change your Client Seed" name="client" id="cient_seed" class="client_seed">

    <input type="submit" value="Change Client Seed" style="width: 360px;" name="client_seed_modify" id="client_seed_modify">

Comment: Is the JavaScript bit your actual code without typos?
Answer: You are confusing server side code and client side code. PHP executes on the server, meaning that any links to resources should be file paths to where the actual files on the server are located. Javascript/JQuery is client side code, meaning that it runs in the user's browser, so any links should be urls not file paths.
Instead of using a local file path on the server like you are now with:
$.post('./php/show_client.php' ...

Your url passed to $.post() should be a URL which accesses that PHP script.
$.post('mysite.com/directory/show_client.php' ...

Comment: No... That's not the issue.

jQuery $.post() and PHP issue


Append custom css class to default class of FormItem in SmartGWT

Question: SmartGWT will set the css class for some FormItem by default value if we don't set the class explicitly. For example, a TextItem will look like this:
<input ... class="textItem" ...>

There is a method in SmartGWT which sets a css class for some FormItem explicitly:
textItem.setTextBoxStyle("foo");

BUT this method removes all previous css classes including the default class. Is there a way not to remove but to append (or insert) some custom class to the FormItem? I want to get the following result:
<input ... class="textItem foo" ...> or

SmartGWT will be changing the last css class during the user interaction according to the fired events. So I would insert my custom class before the default class in order to keep the FormItem looking the same:
<input ... class="foo textItem" ...>
<input ... class="foo textItemFocused" ...>
<input ... class="foo textItemDisabled" ...> ect.

Is it possible to do so?
Answer: I never used SmartGWT, so perhaps this is not the best solution.
You can use getTextBoxStyle (Javadoc) to get the class string and then you add this to your own class and set it back again.
You only need to "save" your css class, if you intend to remove the class later on.
Comment: Thanks for the answer! But I've tried the getTextBoxStyle() and it always returned null. I suppose SmartGWT sets the default classes somewhere deep inside itself before the actual rendering of the page.


Is an instrument out of tune really a drawback to having perfect pitch?

Question: I myself have perfect pitch and I don't feel cursed because my upright piano has been slowly getting out of tune over the years. I have genetic perfect pitch. In other words, it is my DNA and not my ear training that caused me to have perfect pitch. I can hear pitch in noise and tell exactly what pitch and octave it is in. Other than the difference between violin and viola where it is only at low notes that I hear a difference, I can tell exactly what instrument the note came from.
If anything, I think that perfect pitch is beneficial when it comes to an instrument being out of tune. If you have relative pitch, you could adjust it sure but you might not get the pitches right, just the relations. If you have perfect pitch, you can tell exactly how much it is out of tune and in what direction and adjust it accordingly so that it is at exactly the pitch needed.
I have tuned a guitar a few times before and have always been able to get it to the right pitch. I get 2 strings in tune and then I get a third string in tune and it knocks the tuned strings out of tune. I keep going until all the strings are in tune. In this case, perfect pitch is extremely helpful.
So why does everybody say that a drawback to having perfect pitch is knowing that an instrument is out of tune? Is it really a drawback when in fact perfect pitch is extremely helpful to get the instrument back in tune?
Comment: I assume people mean that it's annoying to have perfect pitch when an instrument is out of tune but you can't tune it yourself, e.g. because it's a piano, or your neighbor's violin, or a whole orchestra and you're an audience member.
Comment: When you say the piano's 'out if tune', surely you mean it's not at concert pitch. Being 'out of tune' would affect anybody listening, not just those with absolute pitch!
Comment: How much does it matter if several guitars are in tune with each other, but not at concert pitch? I think it doesn't matter..
Comment: @caters: I didn't realize that it's you who asked this question when I posted my answer. I've read your profile two months ago. There you say: I'm knitting. I'm knitting DNS ... Then I saw your sympathetic compositions and I told you: go on knitting. (I hope you got it as a friendly  joke). But now I ask  you seriously: Are you knitting music theory too? ;)
Comment: So,.... what particular "A" is your perfect pitch set to?   See , for example, replete's answer
Answer: I think there are two misunderstandings in your question:
in the title you're asking:

Is an instrument out of tune really a drawback to having perfect pitch?

Then in the bottom we read:

So why does everybody say that a drawback to having perfect pitch is knowing that an instrument is out of tune?

This is quite a different question.
I never heard somebody say that this would be a drawback for this case. It must be a drawback for all who don't hear it.
(If you want to  make a transfer for your whole life: you are not unhappy if you don't know how great your misery is.)
Having perfect is a drawback as you suffer from the instruments out of tune, that's what most people say with perfect pitch. They even suffer when they play violon and don't play the right pitch, but this happens to all musicians with a good ear and relative pitch. Latter also suffer when a LP has got "effect" and is not turning round. Also they realize when the pitch of their brass instrument (as a D or Db of a trumpet) or a some strings of a piano is not fine tuned.
But only people with perfect pitch may notice that the tuning of the recordplayer is not "perfect" or that the pitch of an orchestra is different form 440.

Is it really a drawback when in fact perfect pitch is extremely helpful to get the instrument back in tune?

Of course in this case perfect pitch is not a drawback at all but an advantage! And also  musicians - like me - with a good relative pitch can tune a guitar or a brass band without problems. But with absolute or perfect pitch you won't be a better musician at all. So you will be gifted to become a good piano tuner.
Answer: Caters, an awful lot of drivel has been written about perfect pitch by people who don't have it. It is true that it can be a nuisance, and that it can lead to other faculties not developing. This is well documented in education. I had to work quite hard as a teenager to overcome its interference in transposition, which people without it handled much more easily. Later, playing on instruments with different tunings like A415 and even A466 has further eroded the hold it originally had on me.
The point is that it should be the servant not the master. So long as the faculty is tamed, it is a help not a hindrance.
Answer: Perfect pitch can be a drawback when someone who has it listens to music that is out of tune. You can't control the tuning of a recording or someone else's voice, for example.
Arguably an extreme version is listening to works tuned in A415 (a tuning used in the Baroque era, or so I've heard); since A415 sounds like an A flat, this results in cognitive dissonance when the name of the piece and/or its sheet music does not match the heard music and its perceived key.
Yes, as someone with perfect pitch (but not your genetic kind), I've been distressed when listening to music with A415 tuning. While that tuning doesn't prevent me from liking the music, I start questioning why the piece says it's in, for example, "G major" when it sounds like it's in F sharp major.
Depending on how strong your perfect pitch is, it might not help you get your instrument back in tune that well. I cannot tell you how many cents flat or sharp your notes are; I can only tell you whether you're significantly flat or sharp from A440 (or so off that you're hitting quarter tones or close enough to them). Whenever I've tuned the plastic ukulele at my sister's place by ear, I generally manage to tune the strings so they are in tune with each other but not necessarily to A440. (I can barely play a ukulele.)
Comment: Is this similar to hearing a piece played at a different speed? Yes, it's different, but maybe only academically so.
Comment: @RosieF - I understand what you're saying. My point is that the whole basis of that harmony, perceived in an 'incorrect' key - unknown at the time - wouldn't be any different harmony (except in pitch) from the original written key. One would believe it's in a certain key - but so what? Hotel California was actually written in a different key from the Bm it's usually heard in. Does that make it wrong every time someone with absolute pitch hears it? Point being, ignorance is bliss. Hear something without being told its proper key, accept it as such?
Comment: If you listened to a piece, and perceived it was in, say, key E, only to find out later it was 'Symphony X in F', what difference would it make?
Comment: @Tim A fundamental difference. It'd mean you'd misunderstood the whole basis of the harmony, which is fundamental with tonal music. A visual analogy which is perhaps relevant: an old oil painting looks dull and gloomy because dark brown dominates. But that's only patina. If that is then cleaned off, we see the colours that the painter intended. It makes a big difference to learn that, with what you were used to, you'd misunderstood the maker, who had in fact intended something different.
Comment: "You can't control the tuning of a recording..."  Duuude, this isn't 1950!  Toss that recording into Audacity or other digital processing tool and you can adjust the pitch however you like!
Comment: @Tim - Regarding "If you listened to a piece, and perceived it was in, say, key E, only to find out later it was 'Symphony X in F', what difference would it make?", it would make a fairly substantial difference. If Key "F" is one semitone up from Key "E", I would suspect the recording uses A415. If Key "F" is away from Key "E" in any other way, I would strongly question why the piece was named in that key if that piece is the first movement. (cont'd)
Comment: @Tim - Regarding "Hear something without being told its proper key, accept it as such?", it depends on the type of piece. For folk songs, Christmas carols, national anthems, and music of that vein, I'd accept it and accept all transpositions of that piece. For other pieces that do not have the key in their names, I'd accept the first recording I hear as such, then downvote all non-established transpositions (e.g. I downvote all versions of *Undertale*'s "Death By Glamour" that are in neither the in-game key of E flat minor nor the OST key of E minor). (cont'd)
Comment: @Tim - (cont'd) If I find out later that the first recording I ever heard was pitch-shifted from the original, I get mad. If the original does not use A440 tuning, I reluctantly accept the two closest transpositions that use A440 (e.g. though *Deltarune Chapter 1*'s "Rude Buster"'s true key is close to F sharp-G-quarter tone minor, I accept both F sharp minor and G minor versions, even though I think it's closer to G minor).
Answer: Your question suggests you haven't played much with other people.  For example, in a symphony orchestra, your personal definition of "A" is irrelevant.  The conductor, or more likely the orchestra Union, decides what frequency to tune to, the oboist tries to get to that pitch, and everyone must be exactly in tune with the oboist.
Even for a solo instrument (guitar, e.g.), being "in tune" means all strings are matched to each other.  What value of "A" you use is irrelevant when there's no other instrument to match with.
Answer: The faculty of learning absolute pitch can be useful. But there is a hindrance if you learnt it from a piano which was a bit flat, so your absolute pitch is not "perfect". So it was with me, and I would sometimes be unsure of the key of the music I was listening to -- until I learnt again with music at/near A=440.
Comment: I don't think this is what he's asking.


substituting algebraic numbers for their conjugates in rational functions

Question: If I have two algebraic numbers $\alpha$ and $\beta$ and a rational function $w$ with rational coefficients (a function that's the ratio of two rational polynomials)  that relates the two $\alpha = w(\beta)$ if I were to substitute $\beta$ with one of it's algebraic cojugates $\beta^{'}$ in the rational function will I get a conjugate of $\alpha$ or rather is $w(\beta^{'})$ an algebraic conjugate of alpha? I feel like there is a very obvious counter example but I've been struggling to find one.
Comment: Sure for any homomorphism $\sigma$ to the algebraic closure then $$ w(\sigma(\beta))=\sigma(w(\beta))$$ is conjugate to $w(\beta)$.
Answer: Let $f,F\in\Bbb Z[X]$ be irreducible. Let $g,h\in \Bbb Z[X]$ with $h\ne 0$. Let $\beta\in\Bbb C$ with $f(\beta)=0$ and $F(\frac{g(\beta)}{h(\beta)})=0$ (and in particular, $h(\beta)\ne 0$).
Note that by cancellation of $h$'s, $$p(X):=h(X)^{\deg F}F(\tfrac{g(X)}{h(X)})$$ is actually $\in \Bbb Z[X]$. As $p(\beta)=0$, we conclude that $\beta$'s minimal polynomial $f$ divides $p$. On the other hand, $h(\beta)\ne 0$ implies that $f$ does not divide (or even has a common factor with)  $p$.
But that means that for every $\beta'$ with $f(\beta')=0$, we have $p(\beta')=0$ and $h(\beta')\ne 0$, hence $$F(\tfrac{g(\beta')}{h(\beta')})=0,$$
i.e., $\tfrac{g(\beta')}{h(\beta')}$ is a conjugate of $\tfrac{g(\beta)}{h(\beta)}$.


Para que serve o ~ em expressão regular?

Question: Estou com o código:
function addhttp($url){

    if(!preg_match('~^(http)s?://~i', $url)){

        $url = 'http://'.$url;
    }

    return $url;

}

Ele add o HTTP caso a URL informada não contenha, mas o que estou com dúvida é na questão do ~ que tem no inicio e depois no fim ~i . Queria saber pra que serve isso
Answer: Expressões regulares PCRE(Perl Compatible Regular Expressions) necessitam de  delimitadores que são um par de caracteres não alfanumericos onde um fica no início e outro no final. Também é comum o uso da barra / como delimitador caso sua regex precisa capturar alguma você precisa escapa-la.
 '~^(http)s?://~i    <---- modificador PCRE
--^           ^----
inicio         fim

A letra i ou qualquer outra após o demilitar é um dos modificadores PCRE, o i significa que a expressão será analizada como case insensitive ou seja não diferencia maiusculas de minusculas que seria o equivalente a [a-zA-Z].
Comment: O mesmo vale para o ~i ?
Comment: @AlissonAcioli O `i` é uma flag usada para indicar que a comparação deve ser case-**i**nsensitive, ou seja, *não* diferencia maiúsculas e minúsculas.
Comment: Entendi... Tentei fazer assim **/^(http)s?:///** e deu erro por causa da **/** . Por isso usar **~** ?
Comment: Só assim deu: **/^(http)s?:\/\//i**
Comment: Precisa escapar a barra se não ele entende que você fechou e abriu duas regexs. @AlissonAcioli
Comment: Entendido. Muito obrigado aos dois!! @rray


How to apply Google Analytics (GA4) tracking code to every page in a Bubble webapp?

Question: I am using the official GA4 plugin for Bubble.io. However there is only one tracking code field per app, while an app might consist of multiple pages. From what I understood, tracking code is to be applied to every page of the application. How do I gather data from each of the pages then? Thanks!
Answer: If you want to add a tracker to every page, within your app, navigate to Settings -> SEO/metatags and scroll down to Script/metatags in Header or Script in body to add your tracking snippet.


Drawing disappears on minimize or resizing the window in MONO Cairo drawing

Question: I have a desktop application built on MONO. The Application has a button and a drawing area, on-click of the button it draws a house in the drawing area.. till here i don't have any problem but once i re size the window or minimize the window the drawing disappears.
Please let me know if any one came across this problem or if any one knows about it.
Thanks,
Best Regards,
Veeresh
Answer: This is a common "issue". It's not really an issue though, it's just the way things work. When you draw something to the screen it's just there in video card ram. When you minimise or move another window over it, something needs to redraw the image. In your case you have nothing to redraw it. You probably need to move your code to draw it to the paint event so that it paints it every time the window needs painting.
Another option would be to draw to a bitmap and display the bitmap in a image control but this is wasteful of memory. It can be the right choice in the correct situation.


How to deal with subjects who cannot receive the treatment in an experiment?

Question: Imagine an experiment where you are trying to establish that cell phone users who receive a a local offer tend to spend more. How do you deal with those in the test group that cannot receive the treatment (say, there are no local offers when they're using their phone)?
For that matter, the same type of users might exist in the control group. How do you deal with subjects that cannot receive the treatment even if you wanted to give them treatment, but you only find this out after you've assigned them to control or test group?
Comment: Is this a true experiment? Are you randomly assigning people to receive local offers or not? Your description is unclear; I wonder if you are talking about observational data.
Comment: @gung It is a true experiment: the randomization is the first step, as soon as a user comes online.
Comment: Do you know who cannot receive the treatment in both groups?
Comment: Not in advance. I only get to know only when I want to give them the treatment.
Comment: But you know now, right? For every person in your study, you know now whether they can receive the treatment or not, & you know this for both intervention & control groups. Is that right?
Comment: Yes, I know at the end of the experiment.
Answer: If it isn't possible for the treatment to actually be applied, prima facie it makes less sense to include those data in the analysis.  This suggests you should just throw them out as outliers—i.e., data that come from a data generating process other than what you are studying.  However, I would argue that it's best to keep them.  I would use one or both of the following approaches:

Mark those who could not receive the treatment with an indicator variable, whether they were actually in the intervention group or not.  Then fit a model with treatment.group, not.treatable and the interaction, treatment.group X not.treatable, all included.  You can test the interaction, and the simple effect of being in the treatment group when it could possibly be applied.  If you use reference level coding and make those who could not receive the treatment the reference level of the not.treatable factor, what the model will display as the 'main effect' of treatment.group will actually be the simple effect of interest.
Ignore the fact that some people will not be able to get the treatment and simply test treatment.group (e.g., with a $t$-test).  This is a test of the marginal association of being assigned to the treatment with the response.  You could also just estimate the means of the treatment groups (again without taking whether people can get the treatment into account) and the standardized mean difference.

Number 2 may seem like an odd suggestion.  In fact, you may not end up using it, but it's worth considering.  There is a concept in biomedical sciences / epidemiology called "efficacy vs. effectiveness" (see also this CV thread: What is the difference between effectiveness and efficacy in determining the benefit of therapy 'A' on condition 'B'?).  The idea is that an intervention has a possible pure effect which can be measured under ideal conditions, but which is likely to have a lesser effect in practice when conditions are not ideal, and that it would be worth knowing what both of those magnitudes are.  In your case, 1 lets you test your treatment effect and tells you its 'true' (in some sense) magnitude, but 2 tells you how well to expect it to work in the future, since evidently you won't know in advance if the treatment can actually be applied when you try it.
Comment: @user765195, 1 is more complete & honest, & 1 will have more power.
Comment: one more question: What is the difference between 1) and throwing out the untreatable cases?
Comment: Thank you very much for the clear and complete answer. It might seem surprising, but we are currently doing 2 and something about it seemed odd to me, hence my question here in SE.  Incidentally, a friend mentioned the word "Counterfactual" in this context, but the only thing I could find about it was in the context of observational studies, rather than experiments.
Comment: You're welcome, @user765195.


CCAvenue Payment Error code 10002 Merchant Authentication failed. Don't worry... It happens to the best of us

Question: I am using cc-avenue jsp integration kit in my website. I have used the code which is provided by cc-avenue but when I try to checkout from my site it gives an error

10002 Merchant Authentication failed. Don't worry... It happens to
  the best of us.

Please any one help me to resolve this problem.
Comment: Are you using the test account or the actual one?
Answer: This error can be caused by an incorrect merchant ID, an incorrect access code, or if the order originates from an unregistered URL. Make sure that all three of these values are correct.

For your security, CCAvenue does not report exactly which of these three values might be in error.

Update:

You can find CCAvenue setup for ASP.net from here: http://aravin.net/complete-guide-integrate-ccavenue-payment-gateway-asp-net-website-screenshot/
Also, you can find steps to solve the 10002 here: http://aravin.net/how-to-test-ccavenue-payment-gateway-in-localhost-avoid-error-code-10002-merchant-authentication-failed/
Comment: Worked for me as a sub domain was not registered in my case. Thanks
Comment: I have valid registerded url. that is http://blahblah.com. but the request i make is overs https. Can this cause 10002 error.
Answer: The Error code 10002 means that Access code or URL not valid so request you to confirm that you are posting the Access code value to CCAvenue and also confirm that the request URL posting to CCAvenue has to be the same as the registered URL with us, as we are having the URL Validation at our end.
The post action URL must be https://secure.ccavenue.com/transaction/transaction.do?command=initiateTransaction
Kindly confirm that you're passing the correct API keys in the integration kit.
We would like to inform you that the API keys that are generated in your account, are for the live website URL and live server (i.e. secure.ccavenue.com). Thus, if we receive any request other that the website URL, (e.g. Local host / sub-domain), or for the test server (i.e. https://test.ccavenue.com/transaction/transaction.do?command=initiateTransaction), you will get the merchant authentication failed error.
We request you to kindly check at your end.
Comment: I have valid registerded url. that is blahblah.com. but the request i make is overs https. Can this cause 10002 error.
Answer: Error Code: 10002     Merchant Authentication failed.
Don't worry... It happens to the best of us.
This might be due to incorrect MERCHANT ID, WORKING KEY or ACCESS CODE. The most likely it is possible due to incorrect URL so to make sure this is implemented on the Registered Domain for Testing URL/Live url for which the API keys are issued.
Please check the registered ccavenue Testing/Live URL for the same.
Comment: I have valid registerded url. that is blahblah.com. but the request i make is overs https. Can this cause 10002 error.
Comment: Sorry for late response if your domain URL (blahblah.com) is registered with ccavenue it should work without any issues on https. it will not work for any other location for example blahblah2.com
Answer: Are you using it on localhost?
If you need to test your code from your local machine, you should write to CCAvenue service desk at firstname.lastname@example.com with your merchant ID and localhost URL to white-list. Else CCAvenue will throw error "Merchant Authentication Failed".
Otherwise this error can be caused by an incorrect access code or if the order originates from an unregistered URL. Make sure that all three of these values are correct.
After your web address gets approved then recheck the new access key and working key
Also use  https://secure.ccavenue.com/transaction/transaction.do?command=initiateTransaction this URL for payments
Answer: I was having same error.
Note below points

whitelist your IP or Domain - ask ccavenue care, they will do whitelist it.
it will work default in live envirement for URL https://secure.ccavenue.com/xyz
for development or test enrolment we need to ask ccavenue to enable our merchant id(need to give our merchant id) for test environment for   URL https://test.ccavenue.com/xyz

Once it enable, then it will work. also double check your merchant_id and access_code too.


Find all triples of positive integers $(x,y,z)$ such that $2^x+y^2=z!+14$

Question: I have been working on the following practice problem:
Find all triples of positive integers $(x,y,z)$ such that $2^x+y^2=z!+14$ and show that you have found all solutions.
I have found the following $(1,6,4)$, $(2,4,3)$ and $(4,2,3)$ but I am unsure whether I have found all the solutions.
Comment: Some thoughts: Assume $z\geq 7 \Rightarrow z! \mod 14 = 0$. Now if we take the whole expression in $\mod 14$, we see that $2^x \mod 14$ can only have values $1, 2,4$ and 8; meaning that if we want $0 = 0$ on both sides, we would need $y^2 \mod 14 $ to be one of $6,10,12$ or $13$. But this never happens. So no solutions beyond $z \geq 7$.
Comment: How did you find the solutions?
Comment: I rearranged the equation to this: $y^2=z!-2^x+14$ then basically tried different values for $x$ and $z$ such that RHS is a square number. It seemed like $y$ could only be even so that helped.
Comment: $x,y,z$ must be positive integers. Sorry I must have accidentally deleted those conditions
Answer: It is plain $y$ must always be even and therefore $y^2 \equiv 0 \mod 4$. Now, if $z \geq 4$, the right hand side is $2 \mod 4$.  Thus the only solution is $x = 1$, which is one of the solutions you have found.  It is also easy to see there are no solutions when $ z \leqslant 2$ (just test the very few cases).  which leaves $z = 3$ for the remaining solutions.
Comment: Thank you! Can I ask how you know $y$ is even? I just keep thinking that $n!$ can be 1.
Comment: You can test the few cases that occur when $z=1$.  $y$ has to be $1$ or $9$ and neither of those can work with any $x$.
Answer: Since $x$ is positive, $2^x\equiv 0$ mod $2$.
(1) If $z=1$, the equation is $2^x+y^2 = 15$, hence $x = 1, 2, 3$ but then $y^2 = 13, 11, 7$, which is a contradiction.
(2) Let $z\ge 2$. Then $z!\equiv 0$ mod $2$, hence $y^2\equiv 0$ mod $2$, and $y$ is even, $y^2\equiv 0$ mod $4$.
(2-i) If $z = 2$, the equation is $2^x+y^2 = 16$, and $x = 1, 2, 3$, then $y^2 = 14, 12, 8$. Thus there's no solution in this case, too.
(2-ii) If $z=3$, the equation is $2^x+y^2 = 20$, so $x =1, 2, 3, 4$, $y^2 = 18, 16, 12, 4$. Hence only solutions in this case are $(2, 4, 3)$ and $(4, 2, 3)$.
(2-iii) Let $z\ge 4$. Then $z!\equiv 0$ mod $8$. Hence $2^x = z!-y^2+14\equiv 2$ mod $4$, and this forces $x = 1$. Then the equation is reduced to $y^2 = z!+12$. Let $y = 2y'$. Then $y'^2 = z!/4 + 3$.
(2-iii-a) If $z = 4$, $y'^2 = 6+3 = 9$, hence $y' = 3$ and $(1, 6, 4)$ is a solution.
(2-iii-b) If $z = 5$, $y'^2 = 33$, which is impossible.
(2-iii-c) If $z\ge 6$, $z!/4\equiv 0$ mod $4$. Hence $y'^2\equiv 0$ mod $4$, which is impossible.
Thus the three solutions $(1, 6, 4), (2, 4, 3)$ and $(4, 2, 3)$ are all solutions.


Inequality. $3(x^2+xy+y^2)(y^2+yz+z^2)(z^2+zx+x^2)\geq (x+y+z)^2(xy+yz+zx)^2$

Question: Let $x,y,z$ be positive real numbers. We have to prove that:
$$3(x^2+xy+y^2)(y^2+yz+z^2)(z^2+zx+x^2)\geq (x+y+z)^2(xy+yz+zx)^2.$$
Thanks :)
Comment: It is Indian NMO 2007, Problem 6. See [here](http://www.artofproblemsolving.com/Forum/viewtopic.php?p=746414&sid=ea9ba90e0d49b4fb52cea22c2227135f#p746414) for lots of different solutions.
Answer: Note that $x^2+xy+y^2=\frac{3}{4}(x+y)^2+\frac{1}{4}(x-y)^2\ge \frac{3}{4}(x+y)^2 $
Repeating the argument for y and z and then for x and z,we get $$3(x^2+y^2+z^2)(y^2+yz+z^2)(x^2+xz+z^2)\ge \frac{81}{64}(x+y)^2(y+z)^2(z+x)^2$$
or $$8(x+y+z)(xy+yz+zx)\leq 9(x+y)(y+z)(z+x)\dots (1)$$
iff $\sum x(y-z)^2\ge 0$ which is true! where the sum is taken cyclically over x,y and z.
P.S. Alternatively,you can proceed from (1) as follows:
$(x+y)(y+z)(z+x)=(x+y+z)(xy+xz+yz)-xyz$ which reduces the problem to proving $(x+y)(y+z)(z+x)\ge 8xyz$ which is true by AM-GM.


What could cause uids to not be numbered consecutively?

Question: I just noticed something weird in a site I'm working on. The first account is user/1 as usual. A second account I created two weeks later is user/20, and a third one a couple days later is user/32. Etc. Two accounts I just created right after each other are numbered consecutively as expected.
There are no custom modules modifying the registration process or anything. I wonder what could cause this, and if there's something I need to fix.
Comment: Is it a public site where users can create their own accounts? Is there any module that deletes accounts created by spammers, or somebody else who is administering that site, and who could delete accounts created by spammers?
Comment: I started on a local server, so the gap between uid 1 and 20 can't be explained by something like that. The site does accept user registrations, but it's running on an unadvertised subdomain and we haven't had any spam registrations. No account deletion modules.  Could it have anything to do with moving the site to another hosting environment?
Answer: So, it turns out this is indeed normal since Drupal 7: the users table is not auto-increment but uids are created with a sequences API that is shared with actions and batch jobs. Uids can therefore be non-consecutive.
Several reasons for changing back from auto-increment table in D6 are pointed out here by chx.
(From reading chx's response to this blog post)
Answer: I noticed the same, I had some gaps between new user ids that even reached at some points 1000 because I was relying on the batch API at my site which shared the same incremental ids for its jobs with the user table. Here is a tested solution that ensures that user id's will always increase by one.
<code>function MYMODULE_user_presave(&$edit, $account, $category) {
  if (isset($account->is_new) && !empty($account->is_new)) {
   $account->uid = db_query('SELECT MAX(uid) FROM users')->fetchField() + 1;
  }
}
</code>


Use Ito formula to solve SDE

Question:
If $Z_t$ is a progressive process and $X_t$ is defined by $X_t = 1+\int_0^t Z_s dB_s$, then use Ito's formula to $Y_t=ln(X_t)$, to show that
$$ X_t = \exp\Bigl(\int_0^t \frac{Z_s}{X_s} dB_s - \frac{1}{2}\int_0^t \bigl(\frac{Z_s}{X_s}\bigr)^2 ds \Bigr)$$

Consider $Y_t = ln(X_t) = \int_0^t \frac{Z_s}{X_s} dB_s - \frac{1}{2}\int_0^t \bigl(\frac{Z_s}{X_s}\bigr)^2 ds $.
So $$dY_t = \frac{Z_t}{X_t} dB_s - \frac{1}{2}\bigl(\frac{Z_t}{X_t}\bigr)^2 $$
and $d\langle Y \rangle_t = (\frac{Z_S}{X_s})^2. $
Then by Ito's formula:
$$ X= df(Y_t) = f'dY_t+\frac{1}{2}f''d\langle Y\rangle_t$$
$$ = \frac{1}{Y_t}dY_t - \frac{1}{2Y_t^2}\left(\frac{Z_S}{X_s}\right)^2dB_s$$
This is clearly completely wrong, how should I have approached this instead...? My end goal is to get this in the form $X_t = 1+\int_0^t Z_s dB_s$.
Answer: From Ito's formula applied to $Y_t := \ln(X_t)$, we have
\begin{align*}
dY_t &= \frac{1}{X_t}dX_t - \frac 12 \frac{1}{X_t^2}d\langle X,X\rangle_t \\
&= \frac{Z_t}{X_t} dB_t - \frac 12 \left( \frac{Z_t}{X_t} \right)^2dt
\end{align*}
so $\ln(X_t) = \ln(X_0) + \int_0^t \frac{Z_s}{X_s}dB_s - \frac 12 \int_0^t(\frac{Z_s}{X_s})^2ds = \int_0^t \frac{Z_s}{X_s}dB_s - \frac 12 \int_0^t(\frac{Z_s}{X_s})^2ds.$  Now just exponentiate both sides: $$X_t = \exp\left(\int_0^t \frac{Z_s}{X_s}dB_s - \frac 12 \int_0^t\left(\frac{Z_s}{X_s}\right)^2ds\right)$$
Comment: How is taking the logarithm of $x$ and taking the exponential of that result any kind of proof?
Comment: Oh, sorry, I thought you found $dY_t$ differently.  I will edit the answer in a moment.

Use Ito formula to solve SDE


Does $\sum_{k=1}^∞ \frac1{\prod_{i=0}^{l(k)} (\ln^i k) · {(\ln^{l(k)} k)}^{l(k)}}$ converge, where $l(x) = \min \{ c\in\Bbb{N} : \ln^c x < e \}$?

Question:
Define $\def\lnc{\operatorname{lnc}}$$\lnc x$ is the minimum natural $c$ such that $\ln^c x < e$, for each real $x ≥ 1$.
Prove that $\displaystyle\sum_{k=1}^∞ \frac1{\prod_{i=0}^{\lnc k} (\ln^i k) · {(\ln^{\lnc k} k)}^{\lnc k}}$ diverges.
Prove that $\displaystyle\sum_{k=1}^∞ \frac1{\prod_{i=0}^{\lnc k} (\ln^i k) · {(\ln^{\lnc k} k)}^{(\lnc k)^r}}$ converges for every $r > 1$.

I came up with this for fun, just to try to squeeze the gap between the well-known boundary:

$\displaystyle\sum_{k=1}^∞ \frac1{\prod_{i=0}^p (\ln^i k)}$ diverges for every natural $p$.

$\displaystyle\sum_{k=1}^∞ \frac1{\prod_{i=0}^p (\ln^i k) · (\ln^p k)}$ converges for every natural $p$.

My proofs are below. Any comments are welcome! Downvoters should note that such questions are explicitly encouraged.
Answer: Let $\def\lnc{\operatorname{lnc}}$$M(c)$ as the minimum natural $k ≥ 1$ such that $\lnc k = c$.
Then $\exp^c(1) ≤ M(c) ≤ \exp^c(1) + 1 ≤ \exp^c(2)$ for any natural $c$.
So
$$
\begin{split}
\sum_{c=2}^\infty \sum_{k=M(c)}^{<M(c+1)}
         \frac1{\prod_{i=0}^{\lnc k} (\ln^i k) · {(\ln^{\lnc k} k)}^{\lnc k}}
  &= \sum_{c=2}^\infty \sum_{k=M(c)}^{<M(c+1)}
         \frac1{\prod_{i=0}^c (\ln^i k) · {(\ln^c k)}^c} \\
  &\ge \sum_{c=2}^\infty \int_{M(c)}^{M(c+1)}
         \frac1{\prod_{i=0}^c (\ln^i x) · {(\ln^c x)}^c}\ dx \\
  &= \sum_{c=2}^\infty \Big[\! -\frac1{c·{(\ln^c x)}^c} \Big]_{x=M(c)}^{M(c+1)} \\
  &\ge \sum_{c=2}^\infty \frac1{c} \Big( \frac1{(1+1/M(c))^c} - \frac1{e^c} \Big) \\
  &\to \infty,
\end{split}
$$
 where we obtained $\ln^c M(c) ≤ 1+1/M(c)$ by using $\ln(x+1) ≤ 1+1/x$ for every real $x > 0$.
But
$$
\begin{split}
\sum_{c=1}^∞ \sum_{k=M(c)}^{<M(c+1)} \frac1{\prod_{i=0}^{\lnc k} (\ln^i k) · {(\ln^{\lnc k} k)}^{(\lnc k)^r}}
 &= \sum_{c=1}^∞ \sum_{k=M(c)}^{<M(c+1)} \frac1{\prod_{i=0}^c (\ln^i k) · {(\ln^c k)}^{c^r}} \\
 &\le \sum_{c=1}^∞ \int_{M(c)-1}^{M(c+1)-1} \frac1{\prod_{i=0}^c (\ln^i x) · {(\ln^c x)}^{c^r}}\ dx \\
 &= \sum_{c=1}^∞ \Big[\! -\frac1{c^r·{(\ln^c x)}^{c^r}} \Big]_{x=M(c)-1}^{M(c+1)-1} \\
 &\le \sum_{c=1}^∞ \frac1{c^r·{(\ln^c (\exp^c(1)-1))}^{c^r}} \\
 &\le \sum_{c=1}^∞ \frac1{c^r·{(1-1/(\exp^c(1)-1))}^{c^r}}\\
 &< \infty,
\end{split}
$$
for every real $r > 1$,
 where we obtained $\ln^c (\exp^c(1)-1) ≥ 1-1/(\exp^c(1)-1)$ by using $\ln(x-1) ≥ \ln(x)-\frac1{x-1}$ for every real $x ≥ 2$.


remove SVG tag from html string

Question: How to remove an HTML svg <tspan> tag which has coordinate dy=\"14\" from the following string
      "<text x=\"264\" style=\"color:#606060;cursor:default;font-
    size:11px;fill:#606060;width:140px;text-overflow:clip;\" text-anchor=\"middle\"
    transform=\"translate(0,0)\" y=\"389\" opacity=\"1\"><tspan>xyz</tspan>
<tspan dy=\"14\" x=\"264\">abc</tspan>"

is there a way I can use the JavaScript match() and replace() the whole tag when it identifies the string ' dy=\"14\" '
In this case the whole tspan tag which contains abc should be removed.
Comment: Yes I did, this is a duplicate of countless similar questions, use the site search.
Comment: Don't try to use regex to parse XML, this is a solved problem already. Use search.
Comment: If this is a duplicate, kindly flag it
Comment: did you understand the question?? @Nit
Answer: jQuery can parse a string of HTML into a useable jQuery object.  For instance, you could try something like this:
var rawDocument = "<text x=\"264\" style=\"color:#606060;cursor:default;font-size:11px;fill:#606060;width:140px;text-overflow:clip;\" text-anchor=\"middle\" transform=\"translate(0,0)\" y=\"389\" opacity=\"1\"><tspan>xyz</tspan><tspan dy=\"14\" x=\"264\">abc</tspan>";

var document = $(rawDocument);

document.find("tspan[dy=14]").remove()

console.log(document);

Why would this be preferred over some JavaScript methods like String.match or String.replace? Well, both those either take a Regex or string input.  Since it'd be a bit difficult to parse that with a string using one of those functions, you'd have to resort to Regex.  But Regex wasn't designed to parse, and on top of that JavaScript's Regex engine isn't the best.  Since you have jQuery at your disposal, I'd take advantage of that.

remove SVG tag from html string